Home >Backend Development >Python Tutorial >How to Create a Pandas DataFrame Row by Row?

How to Create a Pandas DataFrame Row by Row?

Susan Sarandon
Susan SarandonOriginal
2024-12-15 18:00:24573browse

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:

  1. Initialize an empty DataFrame:
import pandas as pd

df = pd.DataFrame(columns=['lib', 'qty1', 'qty2'])
  1. Add rows using df.loc[i]:

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]
  1. Repeat for subsequent rows:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn