首页 > 解决方案 > 在多列上应用 pd.to_numeric 后,列 Dtype 没有变化

问题描述

我想知道在数据框中的多个列上应用 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

pd.to_numeric但是,当我一一转换给定的列时,顺便说一句。我希望能够同时转换给定的数据。谢谢你。

标签: pythonpandasdataframe

解决方案


您需要分配转换为数字的后列:

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

推荐阅读