【问题标题】:How can I speed up my conversion of pandas dataframe column types?如何加快熊猫数据框列类型的转换?
【发布时间】:2021-08-02 00:06:03
【问题描述】:

我正在开发一个 python 模块,它允许用户从 parquet 文件中读取超过 1M 行 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。

【问题讨论】:

    标签: python pandas dataframe type-conversion


    【解决方案1】:

    不要使用 pandas 方法进行转换,而是尝试使用更快的 numpy 数组。例如:

    test[column] = np.array(test[column], dtype=np.float32)
    

    从 numpy 文档中检查不同的数据类型: https://numpy.org/doc/stable/reference/arrays.dtypes.html

    【讨论】:

    • 感谢 Muhammad,将运行时间缩短了 50%!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2019-10-12
    • 2021-05-27
    • 2022-01-06
    • 1970-01-01
    • 2018-12-06
    • 2021-09-17
    相关资源
    最近更新 更多