Create a Pandas Dataframe by appending one row at a time

PandasServer Side ProgrammingProgramming

To create a Pandas DataFrame by appending one row at a time, we can iterate in a range and add multiple columns data in it.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print the input DataFrame.

  • Iterate in a range of 10.

  • Assign values at different index with numbers.

  • Print the created DataFrame.

Example

 Live Demo

import pandas as pd
import random

df = pd.DataFrame(
   {
      "x": [],
      "y": [],
      "z": []
   }
)
print "Input DataFrame:\n", df

for i in range(10):
   df.loc[i] = [i, random.randint(1, 10), random.randint(1, 10)]

print "After appending row at a time: \n", df

Output

Input DataFrame:
Empty DataFrame
Columns: [x, y, z]
Index: []

After appending row at a time:
     x    y    z
0  0.0   9.0   3.0
1  1.0   2.0   1.0
2  2.0   5.0   5.0
3  3.0   7.0   1.0
4  4.0   2.0  10.0
5  5.0   5.0   4.0
6  6.0   1.0   3.0
7  7.0   4.0   2.0
8  8.0   2.0   2.0
9  9.0  10.0   8.0
raja
Published on 30-Aug-2021 09:31:57
Advertisements