【问题标题】:unsupported operand type(s) for -: 'str' and 'int' [duplicate]- 不支持的操作数类型:“str”和“int”[重复]
【发布时间】:2018-09-26 20:41:36
【问题描述】:

我知道这篇文章无法复制,因为数据是我在本地读取的 CSV 格式,但如果有用的话,我可以将数据发布到 github 帐户。我试图先找到相关性:

ng = pd.read_csv('C:/Users/me/Desktop/ngDataBaseline.csv', index_col='Date', parse_dates=True)
ng.head()

这将返回两列:

    HDD Therm
Date        
2011-05-01  347 3,506
2011-06-01  74  1,237
2011-07-01  0   139
2011-08-01  0   35
2011-09-01  154 170

但如果我这样做: ng['HDD'].corr(ng['Therm'])

我收到关于 unsupported operand type(s) for /: 'str' and 'int' 的错误

这对我来说没有意义,因为我认为应该都是熊猫系列。

如果我执行print(type(ng['HDD'])),Ipython 将输出<class 'pandas.core.series.Series'>

print(type(ng['Therm'])) 一样,为什么我不能关联数据?

【问题讨论】:

  • 'Therm' 是一个字符串。查看列中的逗号。
  • 'Therm' 列被读取为字符串而不是浮点数(因为它包含逗号)。如果你做过ng.info(),你会看到的。这个有很多重复。

标签: python pandas


【解决方案1】:

问题在于,由于逗号,Therm 列被读取为字符串。幸运的是,read_csv 有一个 decimal 参数来处理这个问题。使用:

ng = pd.read_csv('C:/Users/me/Desktop/ngDataBaseline.csv', decimal=',', index_col='Date', parse_dates=True)

>>> ng
         Date  HDD    Therm
0  2011-05-01  347    3.506
1  2011-06-01   74    1.237
2  2011-07-01    0  139.000
3  2011-08-01    0   35.000
4  2011-09-01  154  170.000

然后,您的corr 工作:

>>> ng['HDD'].corr(ng['Therm'])
-0.275450033528333

如果逗号是千位分隔符,请使用参数thousands

ng = pd.read_csv('C:/Users/me/Desktop/ngDataBaseline.csv', thousands=',', index_col='Date', parse_dates=True)

>>> ng
         Date  HDD  Therm
0  2011-05-01  347   3506
1  2011-06-01   74   1237
2  2011-07-01    0    139
3  2011-08-01    0     35
4  2011-09-01  154    170

>>> ng['HDD'].corr(ng['Therm'])
0.8794452911190037

【讨论】:

  • pray hands emoji,非常感谢。 thousands=',' 正是我所需要的...
  • 请不要回答known to be a duplicate 的问题。它将被关闭,您将无法获得任何代表。
猜你喜欢
  • 2013-12-24
  • 2011-11-29
  • 1970-01-01
  • 2020-05-25
  • 1970-01-01
  • 2013-08-18
  • 2022-07-27
  • 2016-04-15
  • 2012-11-29
相关资源
最近更新 更多