gpt4 book ai didi

python - NumericType 错误 - 转换为 float 进行计算?

转载 作者:太空宇宙 更新时间:2023-11-03 19:05:51 27 4
gpt4 key购买 nike

我有一个 df:

df:
a b c
date
2012-01-01 0.50 1.2 0.70
2012-01-01 0.45 1.2 0.65
2012-01-01 0.65 1.2 0.63
2012-01-01 0.75 1.2 0.29
2012-01-01 -0.25 1.2 -0.68

我想计算:a/b - c

我跑:

new = df['a']/df['b'] - df['c']

这会返回 新:

date
2012-01-01 -0.2833
2012-01-01 -0.2750
2012-01-01 -0.0883
2012-01-01 0.3350
2012-01-01 0.4717

第一个错误:如果我去:

new.ix[0][0]
TypeError: 'NumericType' object is unsubscriptable

所以我认为这是一个系列。

所以我将其更改为:

new = pd.DataFrame(new)
type(new.ix[0][0])

<type 'NumericType'>

这是奇怪的部分:

new.ix[0][0]
-0.2833
new.ix[0][0]/2
-0.141650
new.ix[0][0]/2.0
0

数字类型怎么了?我怎样才能将其更改为 float ?这里的最佳实践是什么?

谢谢。

最佳答案

行为差异的原因是当 new 是 Series 与 DataFrame 时。

您创建的第一个是一个系列:

In [11]: s = new = df['a'] / df['b'] - df['c']

In [12]: type(s)
Out[12]: pandas.core.series.Series

其值位于 -0.28330 位置:

In [13]: s.ix[0]
Out[13]: -0.28333333333333327

(您不能在浮点上 __getitem__ ,例如 2.0[0] 会出现类似的错误。)

但是,当您将其强制为 DataFrame 时:

In [14]: df_new = new = pd.DataFrame(s)

In [15]: df_new
Out[15]:
0
0 -0.283333
1 -0.275000
2 -0.088333
3 0.335000
4 0.471667

In [16]: type(df_new)
Out[16]: pandas.core.frame.DataFrame

这次第 0 个索引是一个 Series(行):

In [17]: df_new.ix[0]
Out[17]:
0 -0.283333
Name: 0

In [18]: df_new.ix[0][0]
Out[18]: -0.28333333333333327

更新:

要确保所有 DataFrame 值都是 float (numpy.float64),您可以 applymap (这里起作用,因为每一列都被转换为 float ):

df = df.applymap(float)

我不知道你是如何获得 NumericType 对象的,我假设除以 2 与 2.0 是由此得出的。

关于python - NumericType 错误 - 转换为 float 进行计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14729082/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com