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

标签 python pandas numpy scikit-learn boolean

我必须对列进行 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/

相关文章:

python - 获取收集字节使用情况统计信息的pymongo方法?

python - 如何获取或查看xgboost的梯度统计值?

python - MLP 训练集中的 Scikit 使用列表

python - 删除包含特定日期之间数据的行

python - 基于中值绝对偏差 (MAD) 的异常值检测

python - 两个元组作为Python列表中的一个元素

python-3.x - 仅对DatetimeIndex,TimedeltaIndex或PeriodIndex有效,但获得了 'Int64Index'的实例

python - 如何将 DataFrame 的列式和行式合并为一维数组?

python - 填充 DataFrame Pandas Python

python - 替换np数组的元素