首页 > 解决方案 > 当我最初不知道数据类型时,如何快速更改 100 多个数据帧的格式?

问题描述

在使用 Pandas 读取数据帧后,我试图格式化很多(>100)数据帧。这些不是大型数据集(最大文件大小约为 50 MB),但具有不同数量的列(10-100)和不同的列名(有些是相同的),可以有整数、浮点数、日期时间或字符串值. 最终目标是将它们合并到一个数据框中,但在此之前,我需要正确设置每一列的格式。我希望加快这个过程。

编辑:列的每个数据类型都作为“对象”返回。我试过 df.infer_objects() 但这只是返回了相同的数据类型。

我目前的格式化功能是

def format_df(df):
    '''
    Formats the dataframe in the way I want. 

    Parameters
    -----------
    df: a pandas.DataFrame - dataframe with unformatted data types

    Returns
    -----------
    df1: a pandas.DataFrame - dataframe with correct data types

    '''
    start = time.time()
    # Copy dataframe to make changes
    df1 = df.copy()

    # Format the correct data type for each column in the dataframe
    for col in df.columns:
        try:
            # Tries to convert column to datetime format
            df1[col] = df[col].map(pd.to_datetime)
            # If entire column is null, then convert to NaN instead of NaT
            if len(df1[df1[col].isnull() == True]) == len(df1[col]):
                df1[col] = df1[col].astype(object).where(df1[col].notnull(), 
               np.nan)
                df1[col] = df1[col].astype(float)
        except:
            # If it can't convert to datetime, try converting to a numeric 
            # format (int or float)
            try:
                df1[col] = df[col].map(pd.to_numeric)
            except:
                # If data is not datetime or numeric (i.e. string of
                # characters), leave as is
                df1[col] = df[col]
    end = time.time()
    print('Time to format dataframe: ', (end-start)/60)
    return df1

在数据集上运行该函数需要 30 秒到 2 分钟,但由于我有超过 100 个数据帧,整个过程大约需要 30 分钟。我怎样才能让它更快?

我还在研究一种在读取文件之前获取列数据类型的方法,但我不确定这会更快。

标签: pythonpandasformatting

解决方案



推荐阅读