从CSV读取后,我在将UUID存储在Pandas的数据框中时遇到问题。我的数据大约有100万行,“ ID”字段是16个字符的UUID。
我检查了dtype和memory_usage,这些列是“ Object” dtype,并使用了77MB的RAM。您能指导我如何优化它吗?我搜索了此主题,但结果似乎不够满意。谢谢
最好的问候
PS:我正在使用Python 3.7和Pandas 0.23.4
答案 0 :(得分:0)
在这方面没有太多实际意义:
users_ids = orders_df['user_id'].unique().copy()
print("Total user_ids: ", len(np.unique(users_ids)))
print("Total size: ", sys.getsizeof(users_ids))
print("Total size: ", sys.getsizeof(users_ids[0]))
uuid_to_int = {}
next_uuid_int = 0
for uuid in users_ids:
if uuid not in uuid_to_int:
uuid_to_int[uuid] = next_uuid_int
next_uuid_int += 1
def recode_uuid_to_int (uuid) -> int:
return uuid_to_int[uuid]
print("UUID to int: ", recode_uuid_to_int(UUID('0sb7ff82-4ec5-4c71-9627-ca209e27df5f')))
orders_df['user_id_as_int'] = orders_df['user_id'].apply(lambda x: recode_uuid_to_int(x))
users_ids_recoded = orders_df['user_id_as_int'].unique().copy()
print("After recoding: ", sys.getsizeof(users_ids_recoded))
给出输出:
Total user_ids: [cut]
Total size: 139992
Total size: 56
UUID to int: 1
After recoding: 139992