Home > Software engineering >  Add row to an existing dataframe
Add row to an existing dataframe

Time:09-23

I have an existing data frame with known columns. I want to insert a row with data for each column inserted one at a time.

I first created an empty data frame with few columns-

df = pd.DataFrame(columns=['col1', 'col2', 'col3'])
df.to_csv('test.csv', sep='|', index=False)

test.csv

col1|col2|col3

Then, added a row with data inserted for each column one at a time.

list = ['col1', 'col2', 'col3']
turn = 2
df = pd.read_csv('test.csv', sep='|')
while turn:
    for each in list:
        df[each] = turn
    turn-=1

Expected output test.csv

col1|col2|col3
2   |2   |2
1   |1   |1

But I am unable to get the expected output, instead, I'm getting this

col1|col2|col3

Kindly let me know where I'm making mistake, I would really appreciate any sort of help.

CodePudding user response:

To modify your while loop, do:

turn = 2
while turn:
    for each in list:
        df.loc[len(df.dropna()), each] = turn
    turn-=1

>>> df
  col1 col2 col3
0    2    2    2
1    1    1    1
>>> 

The reason it doesn't work is because you're assigning to the whole column... Not the specific row value.

CodePudding user response:

You can use df.append() to append a row

import pandas as pd

df = pd.DataFrame(columns=['col1', 'col2', 'col3'])

turn = 2
while turn:
  new_row = {'col1':turn, 'col2':turn, 'col3':turn}
  df = df.append(new_row, ignore_index=True)
  turn-=1
Out[11]: 

 col1 col2 col3
0    2    2    2
1    1    1    1
  • Related