如何加快 pandas 数据框列类型的转换速度?

问题描述 投票:0回答:2

我正在开发一个 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 分钟)。还有其他方法可以让它运行得更快吗?短暂性脑缺血发作。

python pandas dataframe type-conversion
2个回答
1
投票

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

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

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


0
投票

对我来说,在设置之前删除该列可以显着加快时间,例如:

column_names = newShortEntries.select_dtypes(include=[object]).columns
temp =  newShortEntries[column_names].astype(bool) #np.array(newShortEntries[column_names], dtype=np.bool_)
newShortEntries = newShortEntries.drop(columns=column_names)
newShortEntries[column_names] = temp 
© www.soinside.com 2019 - 2024. All rights reserved.