本文介绍了按行条件将两列或更多列合并为新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将两列或更多列合并为一个新列,根据行条件(即1,一个整数),新列应为包含连接字符串的列.
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.
我尝试使用非零值将我们的行过滤为零但失败.
I tried using nonzero to filter our row with zero but fail.
index LAWSUIT BOARD-MEETING
A 1 0
B 0 0
C 1 1
D 0 1
对此进行了尝试,但它只是结合了所有索引:
Tried this, but it just combined all index:
rdf['NEW'] = rdf.apply(lambda x: ','.join(x.index) if x.nonzero() else 0, axis=1)
预期"NEW"列应如下所示:
Expected the "NEW" columns should look like this:
index LAWSUIT BOARD-MEETING NEW
A 1 0 LAWSUIT
B 0 0
C 1 1 LAWSUIT,BOARD-MEETING
D 0 1 BOARD-MEETING
任何帮助将不胜感激!
推荐答案
使用:
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
这篇关于按行条件将两列或更多列合并为新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!