- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个 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.2833
的 0
位置:
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/
在 Matlab 中有一个命令来定义一个新的数字类型,例如: numerictype(0,16,8) 参见文档:https://www.mathworks.com/help/fixedpoint/re
我有一个 df: df: a b c date 2012-01-01 0.50 1.2 0.70 2012-01-01 0.45
使用 Python 3.9 和 numpy 1.21.2 的 PyCharm(2021.2.1 专业版)中的奇怪行为。当我使用“运行”运行我的程序时,它会按预期工作。但是当我用“调试”运行它时,会出现
关于Java语法,有一个NumericType,它由IntegralType和FloatingPointType组成。 IntegralType 是 byte、short、int、long 和 cha
我是一名优秀的程序员,十分优秀!