0

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 new dataframe.

for index1, row1 in df.iterrows():
    if df.iloc[index][0] == "Text":

Inside this if statement I want to append that row.

3 Answers3

0

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)
Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48
0

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)
print df

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, row in 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.

Community
  • 1
  • 1
Myeongsik Joo
  • 609
  • 7
  • 7
0

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  1
1  bar  1
2  foo  2
3  bar  3
4  foo  2
5  bar  2
6  foo  1
7  foo  3

df.append({'A':"foobar",'B':4},ignore_index=True,)
Out[45]: 
        A  B
0     foo  1
1     bar  1
2     foo  2
3     bar  3
4     foo  2
5     bar  2
6     foo  1
7     foo  3
8  foobar  4

df.append(pd.Series(["barfoo",54],index=['A','B']),ignore_index=True,)
Out[46]: 
        A   B
0     foo   1
1     bar   1
2     foo   2
3     bar   3
4     foo   2
5     bar   2
6     foo   1
7     foo   3
8  barfoo  54
WoodChopper
  • 4,265
  • 6
  • 31
  • 55