问题描述
在比较两个系列时,我遇到了 pandas 的意外行为.我想知道这是故意的还是错误的.
I ran up against unexpected behavior in pandas when comparing two series. I wanted to know if this is intended or a bug.
假设我:
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
这不是我想要的.显然,我预计指数会排成一行.但是我必须明确地将它们排列起来才能得到想要的结果.
which isn't what I wanted. Clearly, I expected the indexes to line up. But I have to explicitly line them up to get the desired results.
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
所以在操作时,索引排成一行.比较时,他们没有.我的观察准确吗?这是出于某种目的吗?
So when operating, the indexes line up. When comparing, they do not. Is my observation accurate? Is this intended for some purpose?
谢谢,
-PiR
推荐答案
Bug 与否.我建议制作一个数据框并比较数据框内的系列.
Bug or not. I would suggest to make a dataframe and compare the series inside the dataframe.
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
这篇关于当你比较 2 个 pandas 系列时会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!