【问题标题】:Convert to numeric colums of a dataframe with apply = AttributeError: 'list' object has no attribute 'apply' [duplicate]使用 apply = AttributeError 转换为数据框的数字列:“list”对象没有属性“apply”[重复]
【发布时间】:2021-05-05 05:49:18
【问题描述】:

我想使用 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'

【问题讨论】:

  • wrong_type_columns 是一个列表。它没有方法apply。你想完成什么?
  • 我正在尝试将 df austin_weather.csv 的那些列更改为数字,因为是对象
  • 你能提供一些虚拟数据吗?为您提供更好的解决方案对我们有好处。
  • 试试df[wrong_type_columns].apply(pd.to_numeric, errors='coerce', axis=1).astype(int)
  • @PaulBrennan 没问题。

标签: python pandas list apply


【解决方案1】:

试试这个

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')

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

【讨论】:

  • 完美运行,谢谢
猜你喜欢
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
  • 2019-11-22
  • 1970-01-01
  • 2017-03-06
  • 2019-11-03
相关资源
最近更新 更多