如何使用布尔索引在 Pandas DataFrame 的分类列中设置值?
How to set a value in a categorical column of a Pandas DataFrame with boolean indexing?
我想根据布尔条件更改分类列的值。
我很确定这应该可以使用 .loc 提供的高级索引,如下所示,但是尽管这适用于具有小索引的行,但对于大索引它会默默地失败,因为您可以通过我自己尝试下面的例子。我做错了什么?
import pandas as pd
df = pd.DataFrame(dict(A=np.array(range(0, 200)), B=pd.Categorical(['a']*200, categories=['a', 'b'])))
# Setting a categorical with boolean indexing works fine for small indices
print df.loc[df.A == 5]
df.loc[df.A == 5, 'B'] = 'b'
print df.loc[df.A == 5]
print ""
# ... but fails for large indices
print df.loc[df.A == 150]
df.loc[df.A == 150, 'B'] = 'b'
print df.loc[df.A == 150]
我的 pandas 0.15.1.dev 安装的输出(请注意,A==5 的值已正确更新,但 A==150 的值未正确更新):
A B
5 5 a
A B
5 5 b
A B
150 150 a
A B
150 150 a
感谢您提供有关问题的任何提示。对我来说这看起来像是一个错误,但我只是从 pandas 开始,可能是错误的。
这是 Categorical
的 setitem impl 中的错误,已由此 PR here 修复。这将在即将发布的 0.16.0 版本中出现(可能在 2 周左右)。
我想根据布尔条件更改分类列的值。
我很确定这应该可以使用 .loc 提供的高级索引,如下所示,但是尽管这适用于具有小索引的行,但对于大索引它会默默地失败,因为您可以通过我自己尝试下面的例子。我做错了什么?
import pandas as pd
df = pd.DataFrame(dict(A=np.array(range(0, 200)), B=pd.Categorical(['a']*200, categories=['a', 'b'])))
# Setting a categorical with boolean indexing works fine for small indices
print df.loc[df.A == 5]
df.loc[df.A == 5, 'B'] = 'b'
print df.loc[df.A == 5]
print ""
# ... but fails for large indices
print df.loc[df.A == 150]
df.loc[df.A == 150, 'B'] = 'b'
print df.loc[df.A == 150]
我的 pandas 0.15.1.dev 安装的输出(请注意,A==5 的值已正确更新,但 A==150 的值未正确更新):
A B
5 5 a
A B
5 5 b
A B
150 150 a
A B
150 150 a
感谢您提供有关问题的任何提示。对我来说这看起来像是一个错误,但我只是从 pandas 开始,可能是错误的。
这是 Categorical
的 setitem impl 中的错误,已由此 PR here 修复。这将在即将发布的 0.16.0 版本中出现(可能在 2 周左右)。