[英]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"])
我對其進行以下計算(第一行和第二行之間的差異):
c=b.diff(1,0)
c.loc[[1]]
然后,我要將這一行差異(由c.loc[[1]]
賦予)插入到數據c.loc[[1]]
b
。 我怎么做? 嘗試時,出現錯誤ValueError: cannot set a row with mismatched columns"
使用具有放大設置通過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
與帶[[]]
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
嘗試
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使用追加
b = b.append(c)
print(b)
輸出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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.