Dataframe Append A Row
How do I append only one row to a new dataframe? I have only seen examples appending a whole dataframe. I am using iterrows to so I have the index of the row I want to append to a
Solution 1:
If you wan to append a row to the DataFrame you have to assign it to a variable first. For example if you want to append the first row in your DataFrame to the same DataFrame:
r = df.iloc[0]
df.append(r, ignore_index=True)
Solution 2:
To add one row of data to existing dataframe you should provide the data of one row compliant to existing dataframe.
df
Out[40]:
A B
0 foo 11 bar 12 foo 23 bar 34 foo 25 bar 26 foo 17 foo 3
df.append({'A':"foobar",'B':4},ignore_index=True,)
Out[45]:
A B
0 foo 11 bar 12 foo 23 bar 34 foo 25 bar 26 foo 17 foo 38 foobar 4
df.append(pd.Series(["barfoo",54],index=['A','B']),ignore_index=True,)
Out[46]:
A B
0 foo 11 bar 12 foo 23 bar 34 foo 25 bar 26 foo 17 foo 38 barfoo 54
Solution 3:
I have a DataFrames from pandas:
import pandas as pd
inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)
printdf
Output:
c1 c2
0 10 100
1 11 110
2 12 120
then, you can append a specific row in a new DataFrame.
for index, rowin df.iterrows():
if row[0] ==10:
new_df = pd.DataFrame(row).transpose()
print new_df
Output:
c1 c2
0 10 100
I recommend to see this answer about DataFrame iterating speed.
Post a Comment for "Dataframe Append A Row"