从指定列中减去 pandas 列 [英] Subtract pandas columns from a specified column

查看:49
本文介绍了从指定列中减去 pandas 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从指定的列中动态减去多个pandas数据框列中的值.在这种情况下,如何从存款中减去A,B和C列,然后将值放在相应的A,B和C列中.

How can I dynamically subtract values in multiple pandas dataframe columns from a specified column. In this case, how can I subtract columns A, B, and C from deposit and place the value in the corresponding A, B, and C columns.

   date         deposit       A                 B           C
0  2017-01-15   12            5                 10          12
1  2017-01-16   20            10                4           32
2  2017-01-17   5             50                10          18
3  2017-01-18   22            15                20          12

应产生:

   date         deposit       A                 B           C
0  2017-01-15   12            7                 2           0
1  2017-01-16   20            10                16         -12
2  2017-01-17   5            -45               -5          -13
3  2017-01-18   22            7                 2           10

推荐答案

In [226]: df[['A','B','C']] = df.deposit.values[:, None] - df[['A','B','C']]

In [227]: df
Out[227]:
         date  deposit   A   B   C
0  2017-01-15       12   7   2   0
1  2017-01-16       20  10  16 -12
2  2017-01-17        5 -45  -5 -13
3  2017-01-18       22   7   2  10

这篇关于从指定列中减去 pandas 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆