我必须对列进行 boolean 运算:
df = pd.DataFrame([[True, True],
[True, False],
[False, True],
[True, True],
[False, False]],
columns=['col1', 'col2'])
我需要生成一个新列来标识它们属于哪个唯一组合:
result = pd.Series([0, 1, 2, 0, 3])
似乎应该有一个非常简单的方法来做到这一点,但它却让我无法理解。也许使用 sklearn.preprocessing 的东西?简单的 Pandas
或 Numpy
解决方案同样受到青睐。
编辑:如果解决方案可以扩展到超过 2 列,那就太好了
最佳答案
最简单的是使用 factorize
创建元组
:
print (pd.Series(pd.factorize(df.apply(tuple, axis=1))[0]))
0 0
1 1
2 2
3 0
4 3
dtype: int64
另一种解决方案,将转换为string
和sum
:
print (pd.Series(pd.factorize(df.astype(str).sum(axis=1))[0]))
0 0
1 1
2 2
3 0
4 3
dtype: int64
关于python - 将两个 boolean 列转换为 Pandas 中的类 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42600222/