pandas fastest way to add row code example
Example 1: how to add a row to a dataframe in python
import pandas as pd
data = {'name': ['Somu', 'Kiku', 'Amol', 'Lini'],
'physics': [68, 74, 77, 78],
'chemistry': [84, 56, 73, 69],
'algebra': [78, 88, 82, 87]}
df_marks = pd.DataFrame(data)
print('Original DataFrame\n------------------')
print(df_marks)
new_row = {'name':'Geo', 'physics':87, 'chemistry':92, 'algebra':97}
df_marks = df_marks.append(new_row, ignore_index=True)
print('\n\nNew row added to DataFrame\n--------------------------')
print(df_marks)
Example 2: add row to dataframe with index
In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
In [100]: s = df.xs(3)
In [101]: s.name = 10
In [102]: df.append(s)
Out[102]:
A B C D
0 -2.083321 -0.153749 0.174436 1.081056
1 -1.026692 1.495850 -0.025245 -0.171046
2 0.072272 1.218376 1.433281 0.747815
3 -0.940552 0.853073 -0.134842 -0.277135
4 0.478302 -0.599752 -0.080577 0.468618
5 2.609004 -1.679299 -1.593016 1.172298
6 -0.201605 0.406925 1.983177 0.012030
7 1.158530 -2.240124 0.851323 -0.240378
10 -0.940552 0.853073 -0.134842 -0.277135