【问题标题】:Pandas - percent difference within column熊猫 - 列内的百分比差异
【发布时间】:2017-12-02 01:09:09
【问题描述】:

这与to this question 密切相关 - 但我想根据前一行而不是示例中的第一行来找到百分比差异。

所以我的输入是

security    date        price
IBM         1/1/2016    100
IBM         1/2/2016    102
IBM         1/3/2016    108
AAPL        1/1/2016    1000
AAPL        1/2/2016    980
AAPL        1/3/2016    1050
AAPL        1/4/2016    1070

我的结果输出将是

security    date        price   change
IBM         1/1/2016    100     NA
IBM         1/2/2016    102     2%
IBM         1/3/2016    108     5.8%
AAPL        1/1/2016    1000    NA
AAPL        1/2/2016    980     -2%
AAPL        1/3/2016    1050    7.14%
AAPL        1/4/2016    1070    1.9%

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我们使用pct_change

    df.groupby('security').price.pct_change()
    Out[1393]: 
    0         NaN
    1    0.020000
    2    0.058824
    3         NaN
    4   -0.020000
    5    0.071429
    6    0.019048
    Name: price, dtype: float64
    

    【讨论】:

    • 哦 pct_change 我忘了这个
    • 一如既往的感谢文
    • @Craig yw~ 快乐编码
    【解决方案2】:

    使用 groupby diff()/shift() * 100 即

    g = df.groupby('security')['price']
    
    df['new'] = (g.diff()/g.shift())*100
    
      security      date  price       new
    0      IBM  1/1/2016    100       NaN
    1      IBM  1/2/2016    102  2.000000
    2      IBM  1/3/2016    108  5.882353
    3     AAPL  1/1/2016   1000       NaN
    4     AAPL  1/2/2016    980 -2.000000
    5     AAPL  1/3/2016   1050  7.142857
    6     AAPL  1/4/2016   1070  1.904762
    

    【讨论】:

      猜你喜欢
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 2023-01-26
      • 2022-11-29
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多