我有一个数据集,其中每个月的值如下所示:
Date Platform Name Value
1-31-2019 Pine Dave 100
1-31-2019 Pine Sam 300
1-31-2019 Cherry Sam 200
2-28-2019 Pine Dave 150
2-28-2019 Pine Sam 200
2-28-2019 Cherry Sam 250
我需要使用上个月的值来运行计算,并且我想添加一列作为上个月的值。所以我想要一个看起来像这样的最终结果
Date Platform Name Value Previous Value
1-31-2019 Pine Dave 100 NaN
1-31-2019 Pine Sam 300 NaN
1-31-2019 Cherry Sam 200 NaN
2-28-2019 Pine Dave 150 100
2-28-2019 Pine Sam 200 300
2-28-2019 Cherry Sam 250 200
我将日期列设置为日期时间数据类型。是否可以进行日期计算来创建新列?
最佳答案
IIUC,你可以这样做:
d=df.set_index([df.Date.dt.month,'Platform','Name'])['Value'].to_dict()
df['Previous_Value']=(df.set_index([df.Date.dt.month-1,'Platform','Name']).
index.to_series().map(d).reset_index(drop=True))
print(df)
<小时/>
Date Platform Name Value Previous_Value
0 2019-01-31 Pine Dave 100 NaN
1 2019-01-31 Pine Sam 300 NaN
2 2019-01-31 Cherry Sam 200 NaN
3 2019-02-28 Pine Dave 150 100.0
4 2019-02-28 Pine Sam 200 300.0
5 2019-02-28 Cherry Sam 250 200.0
关于python - 使用之前的日期从现有列创建新的 Pandas 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56794872/