python - 使用包含具有特定值的其他列的名称的字符串向数据框添加列
问题描述
这类似于反转 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)
它只返回第一个实例,不会捕获具有多个1
s 的行
def get_cat(row):
temp = []
for c in df[codes].columns:
if row[c]==1:
return c
这做同样的事情:它只返回第一个列名并错过具有多个列的行1
。
解决方案
用这个
def get_cat(row):
temp = [a for a, b in row.items() if b == 1]
return '_'.join(temp)
row
是一个pandas.Series
。
推荐阅读
- javascript - 将 JSON 文件绑定到 Echarts(JQuery 获取)
- google-bigquery - 通过 CLI 将存储桶中的 AVRO 加载到具有日期分区的 BigQuery 中
- angularjs - 最小和最大的Angular JS指令表单输入验证
- python - 如何训练项目序列分割模型
- django - 在 Django 中一次更新其中一个时,如何反映两个一对多关系实例的更改?
- php - 照亮查询生成器,如何将日期转换为 Carbon 对象
- python - 如何获取 df1 中存在但 df2 中不存在的行,反之亦然,同时忽略列“值”
- python - 我怎样才能正确循环这个乘法?
- production - 将此元素嵌入到另一个 angular9.1.1 项目后,Angular(9.1.1) 元素出现错误
- python-3.x - 熊猫在情节中下降了行