我有一个 30 行的数据框。我需要在第 10 个索引处插入一行,为其命名,然后将所有单元格放入其中,作为其下方所有单元格的总和。它将代表性能较低的部件的总数。
pd.DataFrame(np.insert(df.values, 0,)
我想给它一个索引名称,并保留下面的所有其他数据。简单地进行插入以及其下方所有行的求和。
最佳答案
我存在 Pandas DataFrame.insert
,但仅适用于列,因此需要更复杂的东西:
df = pd.DataFrame({
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
})
包含索引为 idx
的行求和的解决方案:
idx = 3
df1 = df.iloc[:idx]
df2 = df.iloc[idx:]
df = pd.concat([df1, df2.sum().to_frame('new').T, df2])
print (df)
B C
0 4 7
1 5 8
2 4 9
new 14 9
3 5 4
4 5 2
5 4 3
或者:
idx = 3
df.loc[idx + .5] = df.iloc[idx:].sum()
df = df.sort_index().rename({idx + .5:'new'})
print (df)
B C
0.0 4.0 7.0
1.0 5.0 8.0
2.0 4.0 9.0
3.0 5.0 4.0
new 14.0 9.0
4.0 5.0 2.0
5.0 4.0 3.0
使用 idx
排除行求和的解决方案:
idx = 3
df1 = df.iloc[:idx+1]
df2 = df.iloc[idx+1:]
df = pd.concat([df1, df2.sum().to_frame('new').T, df2])
print (df)
B C
0 4 7
1 5 8
2 4 9
3 5 4
new 9 5
4 5 2
5 4 3
<小时/>
idx = 3
df.loc[idx + .5] = df.iloc[idx + 1:].sum()
df = df.sort_index().rename({idx + .5:'new'})
print (df)
B C
0.0 4.0 7.0
1.0 5.0 8.0
2.0 4.0 9.0
3.0 5.0 4.0
new 9.0 5.0
4.0 5.0 2.0
5.0 4.0 3.0
如果所有列都是数字,也可以使用np.insert
:
idx = 3
arr = df.to_numpy()
s = arr[idx:].sum(axis=0)[None, :]
np.insert(arr, 1, s, 0)
df = pd.DataFrame(arr, columns=df.columns).rename({idx:'new'})
print (df)
B C
0 4 7
1 5 8
2 4 9
new 5 4
4 5 2
5 4 3
关于python - 我需要在第 n 个索引处插入一行,该行将对其下方的所有行进行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58117330/