如何水平折叠Pandas DataFrame 仅保留每行值为True的对应列名
实现代码
你可以直接用以下代码完成转换:
import pandas as pd import numpy as np # 你已有的原始布尔表 df1 = pd.DataFrame(data={'w': [True, False, False], 'x': [False, True, False], 'y': [True, True, True], 'z': [True, False, True]}, index=pd.Series([1, 2, 3], name='index')) # 核心处理逻辑 res = ( # 按行筛选值为True的列名,转成Series结构 df1.apply(lambda row: pd.Series(row[row].index), axis=1) # 补全列数到和原表一致,空位置自动填NaN .reindex(range(len(df1.columns)), axis=1) # 重命名列名为指定格式 .set_axis([f'column{num}' for num in range(1, len(df1.columns)+1)], axis=1) # 空值替换为NA .fillna('NA') # 把行索引转为普通的index列 .reset_index() )
输出结果
执行后res的结构和你要求的完全一致:
| index | column1 | column2 | column3 | column4 |
|---|---|---|---|---|
| 1 | w | y | z | NA |
| 2 | x | y | NA | NA |
| 3 | y | z | NA | NA |
内容的提问来源于stack exchange,提问作者bltSandwich21
相关产品推荐
相关产品推荐

