2015-12-29 165 views
0

如何将一行附加到新的数据框?我只看到了附加整个数据框的例子。我正在使用iterrows,所以我有我想追加到新数据框的行的索引。Dataframe追加一行

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

在这个if语句里面我想追加那行。

+0

您是否想将DataFrame中的某行添加到同一个DataFrame中? –

回答

0

如果你想追加一行到数据框,你必须先将它分配给一个变量。例如,如果你想在你的数据帧中的第一行追加到相同的数据框:

r = df.iloc[0] 
df.append(r, ignore_index=True) 
0

我有熊猫一DataFrames:

import pandas as pd 
inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}] 
df = pd.DataFrame(inp) 
print df 

输出:

c1 c2 
0 10 100 
1 11 110 
2 12 120 

然后,您可以在新的DataFrame中附加特定的行。

for index, row in df.iterrows(): 
    if row[0] == 10: 
     new_df = pd.DataFrame(row).transpose() 
print new_df 

输出:

c1 c2 
0 10 100 

我建议看this answer有关数据帧迭代速度。

0

要将一行数据添加到现有数据框,您应该提供符合现有数据框的一行数据。

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