减去 Pandas 或 Pyspark 数据框中的连续列 [英] Subtract consecutive columns in a Pandas or Pyspark Dataframe

查看:60
本文介绍了减去 Pandas 或 Pyspark 数据框中的连续列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 pandas 或 pyspark 数据帧中执行以下操作,但我仍然没有找到解决方案.

I would like to perform the following operation in a pandas or pyspark dataframe but i still havent found a solution.

我想从数据框中的连续列中减去值.

I want to subtract the values from consecutive columns in a dataframe.

我描述的操作如下图所示.

The operation I am describing can be seen in the image below.

请记住,输出数据帧在第一列上不会有任何值,因为输入表中的第一列不能被前一列减去,因为它不存在.

Bear in mind that the output dataframe wont have any values on first column as the first column in the input table cannot be subtracted by its previous one as it doesn't exist.

推荐答案

diff 有一个 axis 参数,所以你可以一步完成:

diff has an axis param so you can just do this in one step:

In [63]:
df = pd.DataFrame(np.random.rand(3, 4), ['row1', 'row2', 'row3'], ['A', 'B', 'C', 'D'])
df

Out[63]:
             A         B         C         D
row1  0.146855  0.250781  0.766990  0.756016
row2  0.528201  0.446637  0.576045  0.576907
row3  0.308577  0.592271  0.553752  0.512420

In [64]:
df.diff(axis=1)

Out[64]:
       A         B         C         D
row1 NaN  0.103926  0.516209 -0.010975
row2 NaN -0.081564  0.129408  0.000862
row3 NaN  0.283694 -0.038520 -0.041331

这篇关于减去 Pandas 或 Pyspark 数据框中的连续列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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