在计算上高效地将多个数据帧列的数据类型转换为单个数据类型

2024-06-25 23:16:00 发布

您现在位置:Python中文网/ 问答频道 /正文

功能如下:

def func1(df):
    df = df.loc[:,['code',
                  'currentPrice',
                  'hedgingValue',
                  'exercisePrice',
                  'outstanding(%)',
                  'expiryDate'
                  ]].dropna()

    df['code'] = df['code'].str[:5]
    df['currentPrice'] = df['currentPrice'].astype(float)
    df['hedgingValue'] = df['hedgingValue'].astype(float)
    df['exercisePrice'] = (df['exercisePrice'].str.replace(',','')).astype(int)
    df['outstanding(%)'] = (df['outstanding(%)'].str[:-1]).astype(float)
    df['expiryDate'] = df['expiryDate'].astype(int)

    return df

将df['currentPrice']和df['hedgingValue']从string转换为float的两行非常无效,如果有100列而不是两列呢?因此,必须有一种方法可以将多列(假设有100列)转换成只使用一行代码的float。我的问题是什么是神奇的一行代码,做的把戏?提前谢谢你们

请注意,df.apply()在处理大型数据帧时是出了名的缓慢和低效的,因此它肯定不是解决这种情况的方法


Tags: 方法代码功能dfdefcodefloatint