我遇到以下问题:我的数据框看起来像这样:
ID Date Value
1 2016-06-12 2
1 2016-06-13 2.5
1 2016-06-16 4
2 2016-06-12 3
2 2016-06-15 1.5
如您所见,我的数据中有缺失的日子。所以我更想要这样的东西:
ID Date Value
1 2016-06-12 2
1 2016-06-13 2.5
1 2016-06-14 NaN
1 2016-06-15 NaN
1 2016-06-16 4
2 2016-06-12 3
2 2016-06-13 NaN
2 2016-06-14 NaN
2 2016-06-15 1.5
为了解决这个问题,我做了以下操作:
df_new = df.groupby('ID').apply(lambda x: x.set_index('Date').resample('1D').first())
此解决方案有效,但处理大型数据集大约需要半小时。所以我想知道是否有更好的解决方案?
最佳答案
第一个想法是创建 ID
和 Date
值的所有可能组合,然后与左连接合并:
from itertools import product
df['Date'] = pd.to_datetime(df['Date'])
L = list(product(df['ID'].unique(), pd.date_range(df['Date'].min(), df['Date'].max())))
df = pd.DataFrame(L, columns=['ID','Date']).merge(df, how='left')
print (df)
ID Date Value
0 1 2016-06-12 2.0
1 1 2016-06-13 2.5
2 1 2016-06-14 NaN
3 1 2016-06-15 NaN
4 1 2016-06-16 4.0
5 2 2016-06-12 3.0
6 2 2016-06-13 NaN
7 2 2016-06-14 NaN
8 2 2016-06-15 1.5
9 2 2016-06-16 NaN
或者使用DataFrame.reindex
,但性能应该更差,取决于数据:
df['Date'] = pd.to_datetime(df['Date'])
mux = pd.MultiIndex.from_product([df['ID'].unique(),
pd.date_range(df['Date'].min(), df['Date'].max())],
names=['ID','Date'])
df = df.set_index(['ID','Date']).reindex(mux).reset_index()
print (df)
ID Date Value
0 1 2016-06-12 2.0
1 1 2016-06-13 2.5
2 1 2016-06-14 NaN
3 1 2016-06-15 NaN
4 1 2016-06-16 4.0
5 2 2016-06-12 3.0
6 2 2016-06-13 NaN
7 2 2016-06-14 NaN
8 2 2016-06-15 1.5
9 2 2016-06-16 NaN
关于python - 在数据框中添加每个实体缺失天数的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59322018/