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

后端 未结 3 1949
既然无缘
既然无缘 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: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(",")
    

提交回复
热议问题