Python 使用上一个日期从现有列创建新列
我有一个数据集,其中每个月的值如下所示:Python 使用上一个日期从现有列创建新列,python,pandas,Python,Pandas,我有一个数据集,其中每个月的值如下所示: 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
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)
每个月是否都有相同数量的条目?每个月的日期是否总是唯一的?看起来像
df.groupby(['Platform','Name'])。Value.shift()
就可以了,考虑到上面的注释。你能发布到目前为止你尝试过的代码吗?
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