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
Release: 2024-12-15 18:00:24
Original
568 people have browsed it

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'])
Copy after login
  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]
Copy after login
  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]]
Copy after login

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)
Copy after login

Output:

     lib qty1 qty2
0  name0    3    3
1  name1    2    4
2  name2    2    8
3  name3    2    1
4  name4    9    6
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template