我有多个大型数据文件(约3GB的csv文件,每行约1.5亿行),其中包含Unix样式的时间戳和随机生成的观察ids。每个观察可以/将在不同的时间发生多次。它们看起来是这样的:
time_utc obs_id
0 1564617600 aabthssv
1 1564617601 vvvx7ths
2 1564618501 optnhfsa
3 1564619678 aabthssv
4 1564619998 abtzsnwe
...为了分析观测的时间发展,我现在想要得到一个数据框架,其中包含每个观察id的列,以及一个可以更改的时间桶的行,例如1小时,如下所示:
time_bin aabthssv vvvx7ths optnhfsa ...
1 1 1 1
2 1 0 0
...为此,我尝试创建一个时间戳起始点的numpy数组,然后将该bin中的所有行的选择添加value_counts到一个新的空数据have中。这会碰到MemoryError。我已经尝试了更多的预清理,但是即使将原始数据的大小减少三分之一(所以2GB,1亿行)仍然会出现内存错误。
SLICE_SIZE = 3600 # example value of 1h
slice_startpoints = np.arange(START_TIME, END_TIME+1-SLICE_SIZE, SLICE_SIZE)
agg_df = pd.DataFrame()
for timeslice in slice_startpoints:
temp_slice = raw_data[raw_data['time_utc'].between(timeslice, timeslice + SLICE_SIZE)]
temp_counts = temp_slice['obs_id'].value_counts()
agg_df = agg_df.append(temp_counts)
temp_index = raw_data[raw_data['time_utc'].between(timeslice, timeslice + SLICE_SIZE)].index
raw_data.drop(temp_index, inplace=True)有没有办法更有效地做到这一点,或者更确切地说,它是有效的呢?
编辑:根据使用交叉表的建议,我找到了一种高效的方法。不需要缩小文件大小。使用下面的代码可以得到我想要的结果。
df['binned'] = pd.cut(df['time_utc'], bins=slice_startpoints, include_lowest=True, labels=slice_startpoints[1:])
df.groupby('binned')['obs_id'].value_counts().unstack().fillna(0)发布于 2020-02-29 07:22:02
您可以尝试使用cut和crosstab
slice_startpoints = np.arange(START_TIME, END_TIME+SLICE_SIZE, SLICE_SIZE)
print (slice_startpoints)
df['binned'] = pd.cut(df['time_utc'],
bins=slice_startpoints,
include_lowest=True,
labels=slice_startpoints[1:])
df = pd.crosstab(df['binned'], df['obs_id'])发布于 2020-02-29 13:26:47
您可以使用“块”迭代器在大型.csv中读取,然后对块执行计算,而不是对整个.csv文件执行计算。块大小定义单个块中的行数。这样,就有了一个很好的句柄来控制内存使用。缺点将是,您将不得不添加一些逻辑,这将合并的结果块。
import pandas as pd
df_chunk = pd.read_csv('file.csv', chunksize=1000)
for chunk in df_chunk:
print(chunk)https://stackoverflow.com/questions/60462829
复制相似问题