首页 > 解决方案 > 使用包含具有特定值的其他列的名称的字符串向数据框添加列

问题描述

这类似于反转 one-hot encoding,但我有多个可能被标记的列。

我有这个:

|col1|col2|
|1   |0   |
|0   |1   |
|1   |1   |

我要这个:

|col1|col2|new        |
|1   |0   |'col1'     |
|0   |1   |'col2'     |
|1   |1   |'col1_col2'|

这是我尝试过的:

df.idxmax(axis=1)

它只返回第一个实例,不会捕获具有多个1s 的行

def get_cat(row):
    temp = []
    for c in df[codes].columns:
        if row[c]==1:
            return c   

这做同样的事情:它只返回第一个列名并错过具有多个列的行1

标签: pythonpandas

解决方案


用这个

def get_cat(row):
    temp = [a for a, b in row.items() if b == 1]

    return '_'.join(temp)

row是一个pandas.Series


推荐阅读