【问题标题】:Python: pct_change throws TypeError: unsupported operand type(s) for /: 'str' and 'float'Python:pct_change 抛出 TypeError:不支持的操作数类型 /:'str' 和 'float'
【发布时间】:2017-10-08 22:02:10
【问题描述】:

我已从 JSON 导入数据帧:

res = pd.io.json.json_normalize(response['candles'])

    complete    mid.c   mid.h   mid.l   mid.o   time    volume
3000    True    1.48257 1.48902 1.47545 1.48299 2011-05-02T21:00:00.000000000Z  46718
3001    True    1.48271 1.49402 1.47752 1.48254 2011-05-03T21:00:00.000000000Z  49927

重新排序列并创建新的 DataFrame 并设置 DatetimeIndex:

...
newRes = res
newRes = newRes.set_index(pd.DatetimeIndex(newRes['time']))

time                            
2002-05-06 21:00:00 2002-05-06T21:00:00.000000000Z  0.91535 0.91535 0.91535 0.91535 1   True
2002-05-07 21:00:00 2002-05-07T21:00:00.000000000Z  0.90435 0.90435 0.90435 0.90435 1   True

创建另一个 df

df = newRes[['mid.c']].copy()

time                mid.c
2002-05-06 21:00:00 0.91535
2002-05-07 21:00:00 0.90435

现在简单的 pct_change 抛出错误。

df['rtns'] = df['mid.c'].pct_change(1)

TypeError: unsupported operand type(s) for /: 'str' and 'float'

没有括号我得到

df['rtns'] = df['mid.c'].pct_change

time                mid.c   rtns    
2002-05-06 21:00:00 0.91535 <bound method NDFrame.pct_change of time\n2002...
2002-05-07 21:00:00 0.90435 <bound method NDFrame.pct_change of time\n2002...

我尝试按照另一篇文章中的建议设置日期时间索引,但仍然没有帮助(如图所示)

我也尝试通过在 all 上声明 float()s 来手动进行 pct_change 计算,但这也不起作用。

也试过 .dropna

我做错了什么?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您的列是一列字符串,因此pct_change 会抛出错误。在后一种情况下,您所做的只是引用 pct_change 方法,而不是实际调用函数本身。

    您需要将列转换为浮点数,然后计算 pct 变化。

    r = df['mid.c'].astype(float).pct_change(1)
    
    print(r)
    3000         NaN
    3001    0.000094
    Name: mid.c, dtype: float64
    
    df['rtns'] = r
    

    【讨论】:

      猜你喜欢
      • 2017-08-23
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      相关资源
      最近更新 更多