【问题标题】:pandas compare certain colum entries by date and valuepandas 按日期和值比较某些列条目
【发布时间】:2020-02-18 17:31:23
【问题描述】:

我的问题:

 df1 = [{'Day': '2019-12-01', 'Issue Date': '2019-12-01', 'Price': '50'},
 {'Day': '2019-12-02', 'Issue Date': '2019-12-01', 'Price': '45'},
 {'Day': '2019-12-03', 'Issue Date': '2019-12-01', 'Price': '40'},
       {'Day': '2019-12-02', 'Issue Date': '2019-12-02', 'Price': '50'},
 {'Day': '2019-12-03', 'Issue Date': '2019-12-02', 'Price': '42'},
 {'Day': '2019-12-04', 'Issue Date': '2019-12-02', 'Price': '41'}, 
      {'Day': '2019-12-03', 'Issue Date': '2019-12-03', 'Price': '60'},
 {'Day': '2019-12-04', 'Issue Date': '2019-12-03', 'Price': '50'},
 {'Day': '2019-12-05', 'Issue Date': '2019-12-03', 'Price': '48'} 

]

现在我想自动将发行日期的价格与前一天同一日期的价格进行比较。

要找出从昨天到今天的价格上涨了多少,并使用该值创建一个新列。

例如:我想比较 'Issue Date: 2019-12-02 (Price = 45) 中 12 月 2 日的价格, 至“发行日期:2019-12-01”中 12 月 2 日的价格(价格 = 50)。结果应该是加 10 %。

等等。 我该怎么做?

【问题讨论】:

  • 问题。 Day字段中还有多个Issue Date,使用哪个? IE... 2019-02-02 是Issue Date,但是Date 栏中有多个2019-02-02,使用哪个价格?
  • 前一天的价格,发行日期减一,然后这个价格就可以了。
  • 到底是什么问题?你有没有尝试过,做过任何研究? Stack Overflow 不是免费的代码编写服务。请参阅:tourHow to Askhelp centermeta.stackoverflow.com/questions/261592/…

标签: python pandas datetime


【解决方案1】:

好的,如果我理解你的问题,试试这个:

df1 = [{'Day': '2019-12-01', 'Issue Date': '2019-12-01', 'Price': '50'},
 {'Day': '2019-12-02', 'Issue Date': '2019-12-01', 'Price': '45'},
 {'Day': '2019-12-03', 'Issue Date': '2019-12-01', 'Price': '40'},
       {'Day': '2019-12-02', 'Issue Date': '2019-12-02', 'Price': '50'},
 {'Day': '2019-12-03', 'Issue Date': '2019-12-02', 'Price': '42'},
 {'Day': '2019-12-04', 'Issue Date': '2019-12-02', 'Price': '41'}, 
      {'Day': '2019-12-03', 'Issue Date': '2019-12-03', 'Price': '60'},
 {'Day': '2019-12-04', 'Issue Date': '2019-12-03', 'Price': '50'},
 {'Day': '2019-12-05', 'Issue Date': '2019-12-03', 'Price': '48'} 

]

df = pd.DataFrame(df1)

df['Price'] = df['Price'].astype(int)

df['Issue Price'] = df.loc[df['Day'] == df['Issue Date'], 'Price']

df['Issue Price'] = df['Issue Price'].ffill()

df['Pct Change'] = (df['Issue Price'] - df['Price']) / df['Issue Price']
df

输出:

          Day  Issue Date  Price  Issue Price  Pct Change
0  2019-12-01  2019-12-01     50         50.0    0.000000
1  2019-12-02  2019-12-01     45         50.0    0.100000
2  2019-12-03  2019-12-01     40         50.0    0.200000
3  2019-12-02  2019-12-02     50         50.0    0.000000
4  2019-12-03  2019-12-02     42         50.0    0.160000
5  2019-12-04  2019-12-02     41         50.0    0.180000
6  2019-12-03  2019-12-03     60         60.0    0.000000
7  2019-12-04  2019-12-03     50         60.0    0.166667
8  2019-12-05  2019-12-03     48         60.0    0.200000

【讨论】:

    猜你喜欢
    • 2020-12-03
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    相关资源
    最近更新 更多