【问题标题】:After applying pd.to_numeric on multiple columns there is no change in columns Dtype在多列上应用 pd.to_numeric 后,列 Dtype 没有变化
【发布时间】:2021-01-19 09:19:43
【问题描述】:

我想知道在数据框中的多个列上应用 pd.to_numeric 时我做错了什么

df_weather = pd.read_csv ('https://raw.githubusercontent.com/MichalLeh/Edinburgh-bikes-project/main/edinburgh_weather.csv')#("J:/edinburgh_weather.csv")

数据框示例:

   time     temp    feels   wind            gust    rain    humidity cloud  pressure  vis       date
0   00:00   11 °c   11 °c   9 km/h from S   19 km/h 0.0 mm  79%      13%    1020 mb   Excellent 2018-09-01

首先我去掉不需要的字符:

df_weather = (df_weather[['time', 'date', 'temp', 'feels', 'wind', 'gust', 'rain', 'humidity', 'cloud', 'pressure']]
       .replace(to_replace ='[^0-9\:\-\.]', value = '', regex = True))

然后我申请to_numeric:

df_weather[['temp', 'feels', 'wind', 'gust', 'rain', 'humidity', 'cloud', 'pressure']].apply(lambda x: pd.to_numeric(x, errors='coerce'))
df_weather.info()

我没有收到任何错误,但结果如下所示:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6336 entries, 0 to 6335
Data columns (total 11 columns):
 #   Column    Non-Null Count  Dtype 
---  ------    --------------  ----- 
 0   time      6336 non-null   object
 1   temp      6336 non-null   object
 2   feels     6336 non-null   object
 3   wind      6336 non-null   object
 4   gust      6336 non-null   object
 5   rain      6336 non-null   object
 6   humidity  6336 non-null   object
 7   cloud     6336 non-null   object
 8   pressure  6336 non-null   object
 9   vis       6336 non-null   object
 10  date      6336 non-null   object
dtypes: object(11)
memory usage: 544.6+ KB

BTW pd.to_numeric 在我一一转换给定列时起作用。我希望能够同时转换给定的数据。谢谢。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您需要将转换为数字的列分配回来:

    cols = ['temp', 'feels', 'wind', 'gust', 'rain', 'humidity', 'cloud', 'pressure']
    df_weather[cols] = df_weather[cols].apply(lambda x: pd.to_numeric(x, errors='coerce'))
    

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 1970-01-01
      • 2016-05-14
      • 2011-06-19
      • 2017-11-17
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多