【问题标题】:Is there a way to subtract the values of a column with another shifted column in pandas?有没有办法用熊猫中的另一个移位列减去一列的值?
【发布时间】:2021-08-08 10:23:24
【问题描述】:

我的数据如下所示:

       Coln_A   Coln_B
----------------------
Row_1      12    22000
Row_2      40    25000
Row_3      34    27000
Row_4      21    35000
Row_5      32    53000
Row_6      41    36000
Row_7      17    64000

我正在尝试用“Coln_A”减去“向下移动 2 行 Coln_B”的值。

import pandas as pd

cars = {'Coln_A': [12,40,34,21,32,41,17],
        'Coln_B': [22000,25000,27000,35000,53000,36000,64000]
        }
df = pd.DataFrame(cars, columns = ['Coln_A','Coln_B'], 
                  index=['Row_1','Row_2','Row_3','Row_4','Row_5','Row_6','Row_7'])

# Shifting Coln_B 2 rows down
df['Coln_B'] = df['Coln_B'].shift(2)

# Subtracting Coln_B with Coln_A
df['New']= df['Coln_B']- df[ 'Coln_A']

print (df)

这是输出,它可以工作。但是有没有更好/更短的方法可以用 pandas 解决这个问题?

       Coln_A    Coln_B      New

Row_1     12        NaN      NaN
Row_2     40        NaN      NaN
Row_3     34    22000.0  21966.0
Row_4     21    25000.0  24979.0
Row_5     32    27000.0  26968.0
Row_6     41    35000.0  34959.0
Row_7     17    53000.0  52983.0

【问题讨论】:

    标签: python pandas dataframe subtraction


    【解决方案1】:

    您可以使用分配。但这只是做你已经做的事情的语法糖(这可能是最有效的方式):

    df.assign(Coln_B=df['Coln_B'].shift(2),
              New=df['Coln_B'].shift(2)-df['Coln_A']
             )
    

    输出:

           Coln_A   Coln_B      New
    Row_1      12      NaN      NaN
    Row_2      40      NaN      NaN
    Row_3      34  22000.0  21966.0
    Row_4      21  25000.0  24979.0
    Row_5      32  27000.0  26968.0
    Row_6      41  35000.0  34959.0
    Row_7      17  53000.0  52983.0
    

    【讨论】:

      猜你喜欢
      • 2013-12-04
      • 2017-02-20
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 2017-09-01
      • 1970-01-01
      • 2020-10-08
      • 2019-02-05
      相关资源
      最近更新 更多