gpt4 book ai didi

python - 将两个 boolean 列转换为 Pandas 中的类 ID

转载 作者:太空宇宙 更新时间:2023-11-03 15:35:00 24 4
gpt4 key购买 nike

我必须对列进行 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 的东西?简单的 PandasNumpy 解决方案同样受到青睐。

编辑:如果解决方案可以扩展到超过 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

另一种解决方案,将转换为stringsum:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com