熊猫通过日期和值比较某些列条目

时间:2020-02-18 17:31:23

标签: python pandas datetime

我的问题:

 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'} 

]

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

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

例如:我想比较“发行日期:2019-12-02(价格= 45)”中12月2日的价格, 到“发行日期:2019-12-01”中12月2日的价格(价格= 50)。结果应为正10%。

以此类推。 我该怎么办?

1 个答案:

答案 0 :(得分:0)

好的,如果我正确理解了您的问题,请尝试以下操作:

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