“”“ SO。”“”我有一个商店每月收入的数据。如何创建每个月的每日行?
df = pd.DataFrame({
'date': ['2019-01-01','2019-01-01','2019-01-01','2019-02-01',
'2019-02-01','2019-02-01','2019-03-01','2019-03-01','2019-03-01'],
'Company': ['Store A', 'Store B', 'Store C', 'Store A', 'Store B',
'Store C','Store A', 'Store B', 'Store C'],
'Monthly Revenue': [200, 800, 400, 400, 300, 600, 400, 400, 900]
})
print(df)
date Company Monthly Revenue
0 2019-01-01 Store A 200
1 2019-01-01 Store B 800
2 2019-01-01 Store C 400
3 2019-02-01 Store A 400
4 2019-02-01 Store B 300
5 2019-02-01 Store C 600
6 2019-03-01 Store A 400
7 2019-03-01 Store B 400
8 2019-03-01 Store C 900
所需结果:
date Company Monthly Revenue
0 2019-01-01 Store A 200
1 2019-01-02 Store A 200
2 2019-01-03 Store A 200
3 2019-01-04 Store A 200
........
30 2019-01-31 Store A 200
31 2019-02-01 Store A 400
32 2019-02-02 Store A 400
32 2019-02-03 Store A 400
[每个月都有特定天数的通知。我的所有数据都是从1月到12月的每月数据,因此正确的每日行数必须与一个月中的天数相匹配(1月31行,2月28行,3月31行等)。
如果每个商店的date
列均从每月的第一天开始,则可以执行.pivot_table()
,然后用.ffill()
重新采样:
df = pd.DataFrame({'date': ['2019-01-01','2019-01-01','2019-01-01','2019-02-01','2019-02-01','2019-02-01',
'2019-03-01','2019-03-01','2019-03-01'],
'Company': ['Store A', 'Store B', 'Store C', 'Store A', 'Store B', 'Store C',
'Store A', 'Store B', 'Store C'],
'Monthly Revenue': [200, 800, 400, 400, 300, 600, 400, 400, 900]})
df['date'] = pd.to_datetime(df['date'])
df = pd.DataFrame(pd.concat([df['date'], df['date'] + pd.tseries.offsets.MonthEnd(1)]), columns=['date']).combine_first(df)
df = df.pivot_table(index='date', columns='Company').resample('D').ffill().reset_index()
print(df)
打印:
date Monthly Revenue
Company Store A Store B Store C
0 2019-01-01 200.0 800.0 400.0
1 2019-01-02 200.0 800.0 400.0
2 2019-01-03 200.0 800.0 400.0
3 2019-01-04 200.0 800.0 400.0
4 2019-01-05 200.0 800.0 400.0
.. ... ... ... ...
85 2019-03-27 400.0 400.0 900.0
86 2019-03-28 400.0 400.0 900.0
87 2019-03-29 400.0 400.0 900.0
88 2019-03-30 400.0 400.0 900.0
89 2019-03-31 400.0 400.0 900.0
[90 rows x 4 columns]
如果需要一排,可以另外做:
df = df.melt(id_vars='date')
print(df[['date', 'Company', 'value']])
此打印:
date Company value
0 2019-01-01 Store A 200.0
1 2019-01-02 Store A 200.0
2 2019-01-03 Store A 200.0
3 2019-01-04 Store A 200.0
4 2019-01-05 Store A 200.0
.. ... ... ...
265 2019-03-27 Store C 900.0
266 2019-03-28 Store C 900.0
267 2019-03-29 Store C 900.0
268 2019-03-30 Store C 900.0
269 2019-03-31 Store C 900.0
[270 rows x 3 columns]