在比较两个系列时,我遇到了大熊猫意想不到的行为。我想知道这是故意还是错误。
假设我:
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
答案 0 :(得分:5)
错误与否。我建议制作一个数据帧并比较数据帧内的系列。
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