如何加快 pandas 数据框列类型的转换速度?
How can I speed up my conversion of pandas dataframe column types?
我正在开发一个 python 模块,允许用户从 parquet 文件中读取超过 100 万行 x 372 列到内存中,供人们像这样执行分析:
data = pandas.read_parquet(url1 + str(year) + url2, columns=columns, engine='fastparquet')
我试图通过转换一些数据类型来主动减少数据大小,例如对象到类别,int64 到 int32 等,通过执行以下操作:
for column in test.select_dtypes(include=['object']):
if len(test[column].unique()) < 100:
test[column] = test[column].astype('category')
for column in test.select_dtypes(include=['int64']):
test[column] = test[column].astype('int32')
for column in test.select_dtypes(include=['float64']):
test[column] = test[column].astype('float32')
这有效并将数据大小减少了约 50%,但速度很慢(完全转换需要约 3 分钟,而初始数据导入仅需 1 分钟)。是否有另一种方法可以使 运行 更快? TIA.
不要使用 pandas 方法进行转换,而是尝试使用速度更快的 numpy 数组。例如:
test[column] = np.array(test[column], dtype=np.float32)
从 numpy 文档中检查不同的数据类型:
https://numpy.org/doc/stable/reference/arrays.dtypes.html
我正在开发一个 python 模块,允许用户从 parquet 文件中读取超过 100 万行 x 372 列到内存中,供人们像这样执行分析:
data = pandas.read_parquet(url1 + str(year) + url2, columns=columns, engine='fastparquet')
我试图通过转换一些数据类型来主动减少数据大小,例如对象到类别,int64 到 int32 等,通过执行以下操作:
for column in test.select_dtypes(include=['object']):
if len(test[column].unique()) < 100:
test[column] = test[column].astype('category')
for column in test.select_dtypes(include=['int64']):
test[column] = test[column].astype('int32')
for column in test.select_dtypes(include=['float64']):
test[column] = test[column].astype('float32')
这有效并将数据大小减少了约 50%,但速度很慢(完全转换需要约 3 分钟,而初始数据导入仅需 1 分钟)。是否有另一种方法可以使 运行 更快? TIA.
不要使用 pandas 方法进行转换,而是尝试使用速度更快的 numpy 数组。例如:
test[column] = np.array(test[column], dtype=np.float32)
从 numpy 文档中检查不同的数据类型: https://numpy.org/doc/stable/reference/arrays.dtypes.html