pandas 分两只熊猫系列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41726308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:49:01  来源:igfitidea点击:

Divide two pandas Series

pandas

提问by Daniel

trying to divide 2 series but im getting a behavior i dont understand

试图划分 2 个系列,但我得到了一个我不明白的行为

a = 14    0.27
    15    0.11
    16    0.00
    dtype: float64

a.indexreturns

a.index回报

Int64Index([14, 15, 16], dtype='int64')

and

b = 14    0.150286
    15    0.108026
    16    0.000000
    dtype: float64

b.indexreturns

b.index回报

Index([u'14', u'15', u'16'], dtype='object')

When i do

当我做

a.divide(b) or a/b

i get the same result

我得到相同的结果

14   NaN
15   NaN
16   NaN
14   NaN
15   NaN
16   NaN

this should be pretty simple but i dont understand why is returning the series instead of returning the expected

这应该很简单,但我不明白为什么返回系列而不是返回预期

   14   1.7965
   15   1.0182
   16   NaN

回答by jezrael

I think there are different dtypesof indexes, so need same type - e.g. cast object(obviously str) to int:

我认为有不同dtypesindexes,所以需要相同的类型 - 例如强制转换object(显然strint

a = pd.Series([0.27, 0.11, 0], index=['14','15','16'])
b = pd.Series([0.150286, 0.108026, 0], index=[14,15,16])
print (a)
14    0.27
15    0.11
16    0.00
dtype: float64

print (b)
14    0.150286
15    0.108026
16    0.000000
dtype: float64

print (a.index.dtype)
object
print (b.index.dtype)
int64

#cast to int
a.index = a.index.astype(int)
print (a.div(b))
14    1.796575
15    1.018273
16         NaN
dtype: float64