将两个Pandas Series相除

5

我试图将两个序列进行分割,但是我遇到了一个我不理解的行为。

a = 14    0.27
    15    0.11
    16    0.00
    dtype: float64

a.index 返回

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

并且

b = 14    0.150286
    15    0.108026
    16    0.000000
    dtype: float64
b.index 返回:
Index([u'14', u'15', u'16'], dtype='object')

当我执行时

a.divide(b) or a/b

我得到了相同的结果。
14   NaN
15   NaN
16   NaN
14   NaN
15   NaN
16   NaN

这应该很简单,但我不明白为什么它返回了一个系列而不是期望的结果。
   14   1.7965
   15   1.0182
   16   NaN

1
似乎有不同类型的索引,一个是字符串,另一个是整数。 - jezrael
但如果索引相同,您可以使用 a.divide(b.values) - jezrael
两个系列都是 float64 类型的 @jezrael - Daniel
a / b 返回相同的结果 @bernie - Daniel
2
a.indexb.index 是什么? - jezrael
我认为索引是问题所在,b.index 是字符串而 a.index 是整数。我猜想我需要确保两个索引都是相同的数据类型以及系列值。 - Daniel
2个回答

6

我认为不同的dtypes有不同的indexes类型,因此需要相同的类型 - 例如将object(显然是str)转换为int

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

谢谢,我一直很困惑,因为我不明白为什么对于看起来如此简单的东西,我会得到这样的结果。 - Daniel

1
转换为numpy数组,然后再转换回pandas系列也可以实现:
a = pd.Series([0.27, 0.11, 0], index=['14','15','16'])
b = pd.Series([0.150286, 0.108026, 0], index=[14,15,16])

# the index to keep 
my_index = a.index()

c = a.values / b.values
c = pd.Series(c, index=my_index)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接