减去 Pandas 或 Pyspark Dataframe 中的连续列

Subtract consecutive columns in a Pandas or Pyspark Dataframe

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

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

我描述的操作可以在下图中看到。

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

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

diff 有一个 axis 参数,因此您可以一步完成此操作:

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