Skip to main content
 首页 » 编程设计

python之大型数据集的零值完整 Pandas 数据框

2024年12月31日9EasonJim

我有一个如下所示的数据框:

>> df 
index  week  day  hour  count 
5      10    2    10    70 
5      10    3    11    80 
7      10    2    18    15 
7      10    2    19    12 

其中 week 是一年中的第几周,day 是星期几(0-6),hour 是一天中的小时 (0-23)。但是,由于我计划稍后将其转换为 3D 数组(周 x 天 x 小时),因此我必须在 count 列中包含没有项目的小时数。示例:

>> target_df 
index  week  day  hour  count 
5      10    0    0     0 
5      10    0    1     0 
... 
5      10    2    10    70 
5      10    2    11    0 
... 
7      10    0    0     0 
... 
... 

等等。我所做的是生成一个虚拟数据框,其中包含所有可能的索引-周-日-小时组合(基本上是 target_df,没有 count 列):

>> dummy_df 
 
index  week  day  hour 
5      10    0    0    
5      10    0    1    
... 
5      10    2    10   
5      10    2    11 
... 
7      10    0    0  
... 
... 

然后使用

target_df = pd.merge(df, dummy_df, on=['index','week','day','hour'], how='outer').fillna(0) 

这适用于小型数据集,但我要处理很多行。对于我现在正在处理的案例,我为 dummy_df 和 target_df 获得了 8200 万行,而且速度非常慢。

编辑:最慢的部分实际上是构建dummy_df!!!我可以生成单独的列表,但将它们组合成一个 pandas 数据框是最慢的部分。

num_weeks = len(week_list) 
num_idxs = len(df['index'].unique()) 
print('creating dummies') 
_dummy_idxs = list(itertools.chain.from_iterable( 
                   itertools.repeat(x, 24*7*num_weeks) for x in df['index'].unique())) 
print('\t_dummy_idxs') 
_dummy_weeks = list(itertools.chain.from_iterable( 
                   itertools.repeat(x, 24*7) for x in week_list)) * num_idxs 
print('\t_dummy_weeks') 
_dummy_days = list(itertools.chain.from_iterable( 
                   itertools.repeat(x, 24) for x in range(0,7))) * num_weeks * num_idxs 
print('\t_dummy_days') 
_dummy_hours = list(range(0,24)) * 7 * num_weeks * num_idxs 
print('\t_dummy_hours') 
print('Creating dummy_hour_df with {0} rows...'.format(len(_dummy_hours))) 
# the part below takes the longest time 
dummy_hour_df = pd.DataFrame({'index': _dummy_idxs, 'week': _dummy_weeks, 'day': _dummy_days, 'hour': _dummy_hours}) 
print('dummy_hour_df completed') 

有没有更快的方法来做到这一点?

请您参考如下方法:

作为替代方案,您可以使用 itertools.product 创建 dummy_df 作为列表的产品:

import itertools 
index = range(100) 
weeks = range(53) 
days = range(7) 
hours = range(24) 
 
dummy_df = pd.DataFrame(list(itertools.product(index, weeks, days, hours)), columns=['index','week','day','hour']) 
 
dummy_df.head() 
 
    0   1   2   3 
0   0   0   0   0 
1   0   0   0   1 
2   0   0   0   2 
3   0   0   0   3 
4   0   0   0   4