Convert to numeric colums of a dataframe with apply = AttributeError: 'list' object has no attribute 'apply'

Convert to numeric colums of a dataframe with apply = AttributeError: 'list' object has no attribute 'apply'

我想使用 pandas.to_numeric 函数将此列表的列转换为数字,捕获错误并通过提供 errors='coerce' 作为 pandas.to_numeric 的参数强制转换:

wrong_type_columns = ['DewPointHighF', 'DewPointAvgF', 'DewPointLowF', 'HumidityHighPercent', 
                      'HumidityAvgPercent', 'HumidityLowPercent', 'SeaLevelPressureHighInches', 
                      'SeaLevelPressureAvgInches' ,'SeaLevelPressureLowInches', VisibilityHighMiles',
                      'VisibilityAvgMiles', 'VisibilityLowMiles', 'WindHighMPH', 'WindAvgMPH', 
                      'WindGustMPH', 'PrecipitationSumInches']

我会试试这个代码:

wrong_type_columns = wrong_type_columns.apply(pd.to_numeric, errors='coerce', axis=1).astype(int)

但我得到这个错误:

AttributeError: 'list' object has no attribute 'apply'

试试这个

cols = ['DewPointHighF', 'DewPointAvgF', 'DewPointLowF', 'HumidityHighPercent', 
        'HumidityAvgPercent', 'HumidityLowPercent', 'SeaLevelPressureHighInches', 
        'SeaLevelPressureAvgInches' ,'SeaLevelPressureLowInches', 'VisibilityHighMiles',
        'VisibilityAvgMiles', 'VisibilityLowMiles', 'WindHighMPH', 'WindAvgMPH', 
        'WindGustMPH', 'PrecipitationSumInches']
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')

看看这是否能满足您的需求。