pandas 添加新行,最后一行和第一行不同

ryoqjall  于 2023-10-14  发布在  其他
关注(0)|答案(4)|浏览(130)

我想创建一个汇总行,以显示最后一行和第一行之间的差异。
例如

import pandas as pd

data = [
    ['A',1,5],
    ['B',2,4],
    ['C',3,3],
    ['D',4,2],
    ['E',5,1],
    ['F',6,0]
    ]
df = pd.DataFrame(data,columns=['name','x','y'])
print(df)

输出数据框应为:

:   name  x  y
: 0    A  1  5
: 1    B  2  4
: 2    C  3  3
: 3    D  4  2
: 4    E  5  1
: 5    F  6  0
: 6    diff  5  -5

最好的办法是什么?

hivapdat

hivapdat1#

从最后一行中减去第一行,concat沿沿着索引轴的差异

c = ['x', 'y']
diff = df[c].iloc[-1] - df[c].iloc[0]
diff['name'] = 'diff'

pd.concat([df, diff.to_frame().T], ignore_index=True)
name  x   y
0     A  1   5
1     B  2   4
2     C  3   3
3     D  4   2
4     E  5   1
5     F  6   0
6  diff  5  -5
wmomyfyw

wmomyfyw2#

通过在隐含值切片上使用np.diff

df.loc[df.shape[0]] = ['diff', *np.diff(df[['x', 'y']].values[[0, -1]].T).ravel()]

np.diff(df[['x', 'y']].values[[0, -1]].T)的替代方案(默认情况下按列进行diff)是np.diff(df[['x', 'y']].values[[0, -1]], axis=0)

name  x  y
0     A  1  5
1     B  2  4
2     C  3  3
3     D  4  2
4     E  5  1
5     F  6  0
6  diff  5 -5
vyu0f0g1

vyu0f0g13#

可以使用以下

df.loc[df.shape[0]] = ['diff', *list(df.iloc[-1][['x', 'y']] - df.iloc[0][['x', 'y']])]

输出量:
| | X| y| y |
| --|--|--|--|
| 0 |一| 1 | 5 |
| 1 |B| 2 | 4 |
| 2 |C| 3 | 3 |
| 3 |D| 4 | 2 |
| 4 |E| 5 | 1 |
| 5 |F| 6 | 0 |
| 6 |diff| 5 |-5|

mqkwyuun

mqkwyuun4#

试试看:

df = pd.concat(
    [
        df,
        pd.DataFrame(
            [
                {
                    "name": "diff",
                    "x": df.iloc[-1]["x"] - df.iloc[0]["x"],
                    "y": df.iloc[-1]["y"] - df.iloc[0]["y"],
                }
            ]
        ),
    ],
    ignore_index=True,
)
print(df)

图纸:

name  x  y
0     A  1  5
1     B  2  4
2     C  3  3
3     D  4  2
4     E  5  1
5     F  6  0
6  diff  5 -5

相关问题