【问题标题】:pandas Numerical columns being treated as object and won't coercepandas 数值列被视为对象并且不会强制
【发布时间】:2017-10-22 20:32:51
【问题描述】:

我很难理解我的 sql 到 pandas 数据框数据类型发生了什么:

  • User_ID 应该是一个“对象”。这很好。
  • DATE格式为201612、201701、201702等(年数+月数)
  • INCOME 是所有数值,例如 57.25、50、100.10 等
  • DEDUCTIONS 也是数字
  • COUNT of STORES 自然是整数...

我不明白为什么我的数据集以这些计数和总和字段作为对象返回,因为我不能使用诸如 df.total_deductions.max() 之类的操作。我无法理解可能导致此问题的原因或如何解决它。

query = """ SELECT  
  date, 
   user_id,  
  sum(income) total_spend, 
 sum(deductions) total_deductions ,
  count(distinct stores) number_stores 
   FROM  db_table GROUP BY user_id """

df = pd.read_sql(query, jdbc_connection)

df.dtypes: 
date:  object 
user_id:  object 
total_spend:   float 
total_deductions:  object 
number_stores: object

我查看了数据。我似乎无法表明会导致这些计数或总和成为对象而不是数值。
我尝试使用 pd.to_numeric( each_of_my_columns, error ='coerce') 但这个强制选项强制它们为“NaN”。

有人可以假设这里会发生什么或如何解决这个问题,因为我认为我正在做一些明显错误的事情吗?

【问题讨论】:

  • 我认为这可能是由 pandas 的版本引起的,您可以尝试 df.convert_objects(convert_numeric=True) 或 df['each_column'].convert_objects(convert_numeric=True) 吗?...不是一些sum 返回的对象可能根本不是数字...因此在 0.7.0 版本之前的 pandas 版本中按列转换会引发错误
  • 告诉我们df.head(),将有助于查看实际数据。

标签: python python-2.7 pandas type-conversion pandasql


【解决方案1】:

可能有问题值有开始或结束空格,可以通过strip删除:

df['number_stores']=pd.to_numeric(df['number_stores'].astype(str).str.strip(),error='coerce')

你可以转成list查看:

print (df['number_stores'].tolist()[:20])

【讨论】:

  • 知道了,不明白为什么 sql 中的计数将数值转换为对象,但这解决了它..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-21
  • 2012-01-17
相关资源
最近更新 更多