Combine two or more columns into a new column by row condition

后端 未结 3 1922
既然无缘
既然无缘 2021-01-21 18:52

I would like to combine two or more columns into a new columns, based on the row condition ( which is 1, an integer ) the new columns should be a column contains joined string.<

相关标签:
3条回答
  • 2021-01-21 19:11

    Use:

    final=df.assign(NEW=(df.dot(df.columns+',').str[:-1]))
    

           LAWSUIT  BOARD-MEETING                    NEW
    index                                               
    A            1              0                LAWSUIT
    B            0              0                       
    C            1              1  LAWSUIT,BOARD-MEETING
    D            0              1          BOARD-MEETING
    
    0 讨论(0)
  • 2021-01-21 19:26

    This is one of the few things that a for loop would be appropriate for in pandas

    col_names = rdf.columns.tolist()
    rdf["NEW"] = ""
    
    for col in col_names:
        rdf.loc[rdf[col] == 1, "NEW"] = rdf.loc[rdf[col] == 1, "NEW"] + ("," + col)
    
    rdf["NEW"] = rdf["NEW"].str.strip(",")
    
    0 讨论(0)
  • 2021-01-21 19:27

    This could do the job

    rdf['New'] = rdf.replace(1, pd.Series(rdf.columns+',', rdf.columns)).\
                                               replace(0, '').sum(axis = 1).\
                                               str.strip(',')
    
    
    0 讨论(0)
提交回复
热议问题