Home >Backend Development >Python Tutorial >How to Create a Pandas DataFrame Row by Row?
Creating Pandas Dataframes Row by Row
To create an empty Pandas DataFrame and add rows one by one, follow these steps:
import pandas as pd df = pd.DataFrame(columns=['lib', 'qty1', 'qty2'])
Append rows to the DataFrame by referencing the specific index using df.loc[i]. For example, to add the first row:
df.loc[0] = ['name0', 10.0, 20.0]
Continue adding rows, incrementing the index for each one:
for i in range(1, 5): df.loc[i] = ['name' + str(i), randint(10, size=1)[0], randint(10, size=1)[0]]
Example:
import pandas as pd from numpy.random import randint df = pd.DataFrame(columns=['lib', 'qty1', 'qty2']) for i in range(5): df.loc[i] = ['name' + str(i)] + list(randint(10, size=2)) print(df)
Output:
lib qty1 qty2 0 name0 3 3 1 name1 2 4 2 name2 2 8 3 name3 2 1 4 name4 9 6
The above is the detailed content of How to Create a Pandas DataFrame Row by Row?. For more information, please follow other related articles on the PHP Chinese website!