程序问答   发布时间:2022-05-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在多列上应用 pd.to_numeric 后,列 Dtype 没有变化大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在多列上应用 pd.to_numeric 后,列 Dtype 没有变化?

开发过程中遇到在多列上应用 pd.to_numeric 后,列 Dtype 没有变化的问题如何解决?下面主要结合日常开发的经验,给出你关于在多列上应用 pd.to_numeric 后,列 Dtype 没有变化的解决方法建议,希望对你解决在多列上应用 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))

然后我申请到_numeric:

df_weather[['temp','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 (@R_598_10586@l 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'))

大佬总结

以上是大佬教程为你收集整理的在多列上应用 pd.to_numeric 后,列 Dtype 没有变化全部内容,希望文章能够帮你解决在多列上应用 pd.to_numeric 后,列 Dtype 没有变化所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。