数据框的百分比变化

huangapple go评论68阅读模式
英文:

Percent change of dataframe

问题

我有一个类似这样的DataFrame

    Date        Close   Symbol
    0 2018-03-05  44.21   AAPL
    1 2018-03-06  44.17   AAPL
    2 2018-03-07  43.76   AAPL
    3 2018-03-08  44.24   AAPL
    4 2018-03-09  44.99   AAPL
    5 2018-03-12  45.43   AAPL
    6 2018-03-13  44.99   AAPL
    7 2018-03-14  44.61   AAPL
    8 2018-03-15  44.66   AAPL
    9 2018-03-16  44.51   AAPL
    ...
    2506 2023-02-16  50.99   CSCO
    2507 2023-02-17  50.77   CSCO
    2508 2023-02-21  49.69   CSCO
    2509 2023-02-22  49.31   CSCO
    2510 2023-02-23  49.21   CSCO
    2511 2023-02-24  48.48   CSCO
    2512 2023-02-27  48.73   CSCO
    2513 2023-02-28  48.42   CSCO
    2514 2023-03-01  48.34   CSCO
    2515 2023-03-02  48.53   CSCO

我需要计算每个Symbol的每日百分比变化,将Close列替换为该值,然后以Date Close Symbol的格式呈现结果。

我尝试过使用groupby,参考这个帖子,但我无法使它完全工作。

英文:

I have a DataFrame like this:

Date  Close Symbol
0 2018-03-05  44.21   AAPL
1 2018-03-06  44.17   AAPL
2 2018-03-07  43.76   AAPL
3 2018-03-08  44.24   AAPL
4 2018-03-09  44.99   AAPL
5 2018-03-12  45.43   AAPL
6 2018-03-13  44.99   AAPL
7 2018-03-14  44.61   AAPL
8 2018-03-15  44.66   AAPL
9 2018-03-16  44.51   AAPL
...
2506 2023-02-16  50.99   CSCO
2507 2023-02-17  50.77   CSCO
2508 2023-02-21  49.69   CSCO
2509 2023-02-22  49.31   CSCO
2510 2023-02-23  49.21   CSCO
2511 2023-02-24  48.48   CSCO
2512 2023-02-27  48.73   CSCO
2513 2023-02-28  48.42   CSCO
2514 2023-03-01  48.34   CSCO
2515 2023-03-02  48.53   CSCO

I need to take the daily percent change of each Symbol, replace the Close column with that value, and then bring back the result in this Date Close Symbol format.

I have tried groupby following this post, but I can't quite get it to work.

答案1

得分: 1

如果可能的话,我建议您为百分比变化使用一个新的列名。将其命名为Close 会让事情变得相当混乱。

您可以尝试这样做:

# 或 df["Close"] = ...
df["Change"] = df.groupby("Symbol")["Close"].pct_change()
英文:

If possible, I suggest that you use a new column name for the percentage change. Naming it Close makes things rather confusing.

You can try this:

# or df["Close"] = ...
df["Change"] = df.groupby("Symbol")["Close"].pct_change()

huangapple
  • 本文由 发表于 2023年3月4日 09:44:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75633174.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定