python - 当你比较 2 个 Pandas 系列时会发生什么

标签 python pandas compare series

在比较两个系列时,我遇到了 pandas 的意外行为。我想知道这是故意的还是错误的。

假设我:

import pandas as pd
x = pd.Series([1, 1, 1, 0, 0, 0], index=['a', 'b', 'c', 'd', 'e', 'f'], name='Value')
y = pd.Series([0, 2, 0, 2, 0, 2], index=['c', 'f', 'a', 'e', 'b', 'd'], name='Value')

x > y

产量:

a     True
b    False
c     True
d    False
e    False
f    False
Name: Value, dtype: bool

这不是我想要的。显然,我预计指数会排成一行。但是我必须明确地将它们排列起来才能得到想要的结果。

x > y.reindex_like(x)

产量:

a     True
b     True
c     True
d    False
e    False
f    False
Name: Value, dtype: bool

这是我所期望的。

更糟糕的是,如果我:

x + y

我明白了:

a    1
b    1
c    1
d    2
e    2
f    2
Name: Value, dtype: int64

所以在操作时,索引排成一行。比较时,他们没有。我的观察准确吗?这是出于某种目的吗?

谢谢,

-PiR

最佳答案

Bug 与否。我建议制作一个数据框并比较数据框内的系列。

import pandas as pd
x = pd.Series([1, 1, 1, 0, 0, 0], index=['a', 'b', 'c', 'd', 'e', 'f'], name='Value_x')
y = pd.Series([0, 2, 0, 2, 0, 2], index=['c', 'f', 'a', 'e', 'b', 'd'], name='Value_y')

df = pd.DataFrame({"Value_x":x, "Value_y":y})
df['Value_x'] > df['Value_y']

Out[3]:

a     True
b     True
c     True
d    False
e    False
f    False
dtype: bool

关于python - 当你比较 2 个 Pandas 系列时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25435229/

相关文章:

python - 在 Tensorflow 中实现嵌入 Dropout

python - Matplotlib - 将标签移动到饼图的中间

python - if-else 或只是声明-if 在条件值中

python - 比较 python 中的变量

java - 实现比较方法的规则

numbers - ASM 比较 2 个数字

python - 在装饰器中扩展 Python 中的类

python - 单独线程中的 Pandas pd.concat() 显示没有加速

python - Pandas 数据框每行列平均值

python - 使用正则表达式提取不同格式的日期并对它们进行排序 - pandas