How to append a new line to a dataframe (previously a dictionary)?

Viewed 249

I created a pandas dataframe from a dictionary where the index is the key from the dictionary.

data = {'row_1': [1], 'row_2': [2], 'row_3': [3]}
df = pd.DataFrame.from_dict(data, orient='index')

>>>df
       0
row_1  1
row_2  2
row_3  3

new_row = {'row_4': [4]}

How can I append the new row to the df in the same structure?

2 Answers

Try:

new_row = {"row_4": [4]}

print(df.append(pd.DataFrame(new_row).T))

Prints:

       0
row_1  1
row_2  2
row_3  3
row_4  4

Or:

print(df.append(pd.DataFrame(new_row.values(), index=new_row)))
import pandas as pd
data = {'row_1': [1], 'row_2': [2], 'row_3': [3]}
df = pd.DataFrame.from_dict(data, orient='index')
new_row = {'row_4':[4],'row_5':[5]}
df=df.append(pd.DataFrame.from_dict(new_row,orient='index'))
print(df)
Related