简体   繁体   English

如何在熊猫的DataFrame中插入一行? (蟒蛇)

[英]How to insert a row in DataFrame in pandas? (Python)

Say I have the following dataframe: 说我有以下数据框:

a=np.array([[10,20,30,40],[5,20,35,50],[0,5,10,15]])
b=pd.DataFrame(a, columns=["n1", "n2", "n3", "n4"])

I do the following calculation on it (difference between 1st and 2nd row): 我对其进行以下计算(第一行和第二行之间的差异):

c=b.diff(1,0)
c.loc[[1]]

And then I want to insert this row of differences (given by c.loc[[1]] ) into my dataframe b . 然后,我要将这一行差异(由c.loc[[1]]赋予)插入到数据c.loc[[1]] b How do I do that? 我怎么做? When I try, I get an error ValueError: cannot set a row with mismatched columns" 尝试时,出现错误ValueError: cannot set a row with mismatched columns"

Use setting with enlargement by Series selected by loc with one [] : 使用具有放大设置通过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

Or use concat with DataFrame with [[]] : 或者将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

Try 尝试

c = b.diff(axis=0).iloc[1]

or 要么

c = b.diff(axis=0).loc[1]

The output: 输出:

print(c)
    n1    -5.0
    n2     0.0
    n3     5.0
    n4    10.0
    Name: 1, dtype: float64

to add c to b use append 将c添加到b使用追加

b = b.append(c)

output of print(b) 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM