python - 在多列上应用 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
但是,当我一一转换给定的列时,顺便说一句。我希望能够同时转换给定的数据。谢谢你。
解决方案
您需要分配转换为数字的后列:
cols = ['temp', 'feels', 'wind', 'gust', 'rain', 'humidity', 'cloud', 'pressure']
df_weather[cols] = df_weather[cols].apply(lambda x: pd.to_numeric(x, errors='coerce'))
推荐阅读
- javascript - 更改动态创建的 iframe 的 src
- javascript - 检查对象是否等于某种类型的良好实践方法是什么?
- regex - REGEX - 如何递归地捕获一个组?
- php - 可变长度数据
- javascript - Vue.js 错误:命名槽必须使用 '' on a custom element
I am trying to pass information through slots and I keep getting an error,
'Named slots must use '' on a custom element.'
See below for my code.<
- python - 接收字母字符时如何防止python程序崩溃
- jquery - 如何从包含另一个元素的 jQuery Datatable 列中过滤
- matlab - ADAM(阿姆斯特丹)工具箱试验掩蔽稳健去趋势在 Matlab 中引发错误
- python - tkinter iconbipmap 找不到文件
- javascript - 获取窗口高度到小数点