我正在尝试将每周数据上采样到每日数据,但是,我在上采样最后一个边缘时遇到了困难。我该怎么做?
import pandas as pd
import datetime
df = pd.DataFrame({'wk start': ['2018-08-12', '2018-08-12', '2018-08-19'],
'car': [ 'tesla model 3', 'tesla model x', 'tesla model 3'],
'sales':[38000,98000, 40000]})
df['wk start'] = df['wk start'].apply(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d'))
df.set_index('wk start').groupby('car').resample('D').pad()
返回:
car sales
car wk start
tesla model 3 2018-08-12 tesla model 3 38000
2018-08-13 tesla model 3 38000
2018-08-14 tesla model 3 38000
2018-08-15 tesla model 3 38000
2018-08-16 tesla model 3 38000
2018-08-17 tesla model 3 38000
2018-08-18 tesla model 3 38000
2018-08-19 tesla model 3 40000
tesla model x 2018-08-12 tesla model x 98000
我想要的输出是:
car sales
car wk start
tesla model 3 2018-08-12 tesla model 3 38000
2018-08-13 tesla model 3 38000
2018-08-14 tesla model 3 38000
2018-08-15 tesla model 3 38000
2018-08-16 tesla model 3 38000
2018-08-17 tesla model 3 38000
2018-08-18 tesla model 3 38000
2018-08-19 tesla model 3 40000
2018-08-20 tesla model 3 40000
2018-08-21 tesla model 3 40000
2018-08-22 tesla model 3 40000
2018-08-23 tesla model 3 40000
2018-08-24 tesla model 3 40000
2018-08-25 tesla model 3 40000
tesla model x 2018-08-12 tesla model x 98000
2018-08-13 tesla model x 98000
2018-08-14 tesla model x 98000
2018-08-15 tesla model x 98000
2018-08-16 tesla model x 98000
2018-08-17 tesla model x 98000
2018-08-18 tesla model x 98000
我看了this ,但他们正在使用句点,而我正在查看日期时间。提前致谢!
最佳答案
是的,你是对的,最后的边缘数据被排除在外。解决方案是将它们添加到输入 DataFrame
- 我的解决方案使用 drop_duplicates
创建了一个助手 Dataframe
, 添加 6
天和 concat
在使用您的解决方案之前将其更改为原始 df
:
df1 = df.sort_values('wk start').drop_duplicates('car', keep='last').copy()
df1['wk start'] = df1['wk start'] + pd.Timedelta(6, unit='d')
df = pd.concat([df, df1], ignore_index=True)
df = df.set_index('wk start').groupby('car').resample('D').pad()
print (df)
car sales
car wk start
tesla model 3 2018-08-12 tesla model 3 38000
2018-08-13 tesla model 3 38000
2018-08-14 tesla model 3 38000
2018-08-15 tesla model 3 38000
2018-08-16 tesla model 3 38000
2018-08-17 tesla model 3 38000
2018-08-18 tesla model 3 38000
2018-08-19 tesla model 3 40000
2018-08-20 tesla model 3 40000
2018-08-21 tesla model 3 40000
2018-08-22 tesla model 3 40000
2018-08-23 tesla model 3 40000
2018-08-24 tesla model 3 40000
2018-08-25 tesla model 3 40000
tesla model x 2018-08-12 tesla model x 98000
2018-08-13 tesla model x 98000
2018-08-14 tesla model x 98000
2018-08-15 tesla model x 98000
2018-08-16 tesla model x 98000
2018-08-17 tesla model x 98000
2018-08-18 tesla model x 98000
关于python - Pandas Resample 上采样数据的最后日期/边缘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51790793/