提问人:Alex 提问时间:2/12/2018 更新时间:2/12/2018 访问量:2232
如何在pandas的DataFrame中插入一行?(蟒蛇)
How to insert a row in DataFrame in pandas? (Python)
问:
假设我有以下数据帧:
a=np.array([[10,20,30,40],[5,20,35,50],[0,5,10,15]])
b=pd.DataFrame(a, columns=["n1", "n2", "n3", "n4"])
我对它进行以下计算(第 1 行和第 2 行之间的差异):
c=b.diff(1,0)
c.loc[[1]]
然后我想将这一行差异(由 给出)插入到我的数据帧中。我该怎么做?当我尝试时,我收到一个错误c.loc[[1]]
b
ValueError: cannot set a row with mismatched columns"
答:
1赞
sgDysregulation
2/12/2018
#1
尝试
c = b.diff(axis=0).iloc[1]
或
c = b.diff(axis=0).loc[1]
输出:
print(c)
n1 -5.0
n2 0.0
n3 5.0
n4 10.0
Name: 1, dtype: float64
要将 C 添加到 B,请使用 APPEND
b = b.append(c)
输出print(b)
n1 n2 n3 n4
0 10.0 20.0 30.0 40.0
1 5.0 20.0 35.0 50.0
2 0.0 5.0 10.0 15.0
1 -5.0 0.0 5.0 10.0
2赞
jezrael
2/12/2018
#2
使用放大设置,选择由一个:Series
loc
[]
b.loc[len(b)] = b.diff().loc[1]
print (b)
n1 n2 n3 n4
0 10.0 20.0 30.0 40.0
1 5.0 20.0 35.0 50.0
2 0.0 5.0 10.0 15.0
3 -5.0 0.0 5.0 10.0
或者将 concat
与 with 一起使用:DataFrame
[[]]
c = pd.concat([b, b.diff().loc[[1]]], ignore_index=True)
print (c)
n1 n2 n3 n4
0 10.0 20.0 30.0 40.0
1 5.0 20.0 35.0 50.0
2 0.0 5.0 10.0 15.0
3 -5.0 0.0 5.0 10.0
评论