Py学习  »  Python

Python:将列标题转换为单个列值

user2293224 • 5 年前 • 1356 次点击  

我有一个数据框,看起来像

  Fever   Chill   Cough   Headache  Respiratory   Nasal   Joint Pain    Back pain   Stomach pain        
0   Y       Y        Y     NaN           NaN         NaN    NaN          NaN        NaN 
1   Y       NaN      NaN    NaN          Y           NaN    NaN          NaN        NaN 
2   Y       NaN       Y     NaN          NaN         NaN    NaN          NaN        NaN 
3   Y       NaN      NaN    NaN          NaN         NaN    Y            NaN        NaN 
4   Y       NaN      NaN    NaN          NaN         NaN    NaN          NaN        NaN 

我想将列标题转换为单个列(比如说症状),这样当新列具有值Y时,它将包含列标题名称。所需的列应如下所示:

      Symptom
0     Fever, Chill, Cough
1     Fever, Respiratory
2     Fever, Cough
3     Fever, Joint Pain
4     Fever

我使用了stack的概念,但它没有生成所需的输出。这是我的代码:

df[['Fever','Chill','Cough','Headache','Respiratory symptom','Nasal Symptoms','Joint Pain','Back pain','Stomach pain','Diarrhoea','Vomiting','Fatigue','Pneumonia shadow']].stack().reset_index()

有谁能指导我怎样取得理想的结果吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55865
 
1356 次点击  
文章 [ 1 ]  |  最新文章 5 年前
YOBEN_S
Reply   •   1 楼
YOBEN_S    5 年前

让我们来吧 dot

df.eq('Y').dot(df.columns+',').str[:-1]
#df['symptom'] = df.eq('Y').dot(df.columns+',').str[:-1]