我有一个像这样的 pandas 数据框,有一个 ID 列和一堆指示列(真/假):
df_have:
ID Male Special_Need Teeanger
1 T F T
2 F T F
我想转置它,但仅限于 attributes = True。即
df_want:
ID Attribute
1 Male
1 Teenager
2 Special_Need
最佳答案
使用堆栈
df.set_index('ID').rename_axis('Attribute',1).stack().loc[lambda x : x=='T'].reset_index().drop(0,1)
Out[268]:
ID Attribute
0 1 Male
1 1 Teeanger
2 2 Special_Need
关于python - Pandas 宽格式转换为长格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54990231/