如何在新数据帧中只追加一行?我只看到过附加整个数据帧的示例。我正在使用iterrows to,这样我就有了要附加到新数据帧的行的索引。
for index1, row1 in df.iterrows():
if df.iloc[index][0] == "Text":
在这个if语句中,我想附加那一行。
如果要将一行附加到DataFrame,则必须首先将其分配给一个变量。例如,如果您想将DataFrame中的第一行附加到相同的DataFrame:
r = df.iloc[0]
df.append(r, ignore_index=True)
要向现有数据帧添加一行数据,您应该提供符合现有数据帧的一行数据。
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
我有一个来自pandas的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
我建议你看看这个关于DataFrame迭代速度的答案。