python - Pandas 根据其他行的和/差添加新行

标签 python pandas dataframe sum difference

df 有

id    measure   t1  t2  t3
1     savings   1    2   5
1     income    10   15  14
1     misc       5    5   5
2     savings    3   6   12
2     income     4   20  80
2     misc       1   1    1

df want- 为每个 id 添加一个新行,称为支出,通过减去 measure=income - measure=savings 计算,对于每个 id 的每个时间段 t1、t2、t3

id    measure   t1  t2  t3
1     savings   1    2   5
1     income    10   15  14
1     misc      5     5   5
1     spend     9    13  9
2     savings    3   6   12
2     income     4   20  80
2     misc       1    1   1
2     spend      1   14  68

尝试:

df.loc[df['Measure'] == 'spend'] =          
                        df.loc[df['Measure'] == 'income']-
                        (df.loc[df['Measure'] == 'savings'])

失败是因为我没有合并 groupby 以获得期望的结果

最佳答案

这是使用 groupby diff

的一种方式
df1=df[df.measure.isin(['savings','spend'])].copy()

s=df1.groupby('id',sort=False).diff().dropna().assign(id=df.id.unique(),measure='spend')
df=df.append(s,sort=True).sort_values('id')
df
Out[276]: 
   id  measure    t1    t2    t3
0   1  savings   1.0   2.0   5.0
1   1   income  10.0  15.0  14.0
1   1    spend   9.0  13.0   9.0
2   2  savings   3.0   6.0  12.0
3   2   income   4.0  20.0  80.0
3   2    spend   1.0  14.0  68.0

更新

df1=df.copy()
df1.loc[df.measure.ne('income'),'t1':]*=-1
s=df1.groupby('id',sort=False).sum().assign(id=df.id.unique(),measure='spend')
df=df.append(s,sort=True).sort_values('id')

关于python - Pandas 根据其他行的和/差添加新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57378381/

相关文章:

python - 洗牌的程序

mysql - 如何使用并行插入语句在 MySQL 表中插入巨大的 Pandas Dataframe?

python - 如何在 pandas 的特定列添加列表值?

python - 如何获取 pandas DataFrame 中第二大行值的列名

python - 拆分字母数字列,不带分隔符 pandas 数据框

python - 箱线图 : custom width in seaborn

python - 登录 django 之前应该存储状态吗?

python-3.x - 如何使用命名绑定(bind)与 pandas 数据帧中的 cx_Oracle 中的批量插入 (executemany)

python - 在 pyspark 中聚合 5 分钟窗口

r - 如何从 R 中的自定义函数向数据框添加多列