合并 pandas 中的列以创建新列

Combine columns in pandas to create a new column

您好,我正在处理 pandas 数据框,我想创建一个组合多个列并对其应用条件的列,我正在寻找一种聪明的方法。

假设数据框看起来像

A   B   C   D
1   0   0   0
0   1   0   0
0   0   1   0
1   0   1   0
1   1   1   0
0   0   1   1

我的输出列应该如下所示

A   B   C   D   Output_col
1   0   0   0   A
0   1   0   0   B
0   0   1   0   C
1   0   1   0   A_C
1   1   1   0   A_B_C
0   0   1   1   C_D

我当然可以使用下面的代码实现这一点,但我必须为每一列都这样做。

test['Output_col'] = test.A.apply(lambda x: A if x > 0 else 0)

我想知道如果我有非常多的列,是否有一种方法可以在不应用到每一列的情况下实现这一点。

提前致谢!!

使用 DataFrame.apply + join。 Select 列名称使用 x.index( 注意使用axis = 1) + boolean indexing with Series.eq过滤选中的列:

test['Output_col']=test.apply(lambda x: '_'.join(x.index[x.eq(1)]),axis=1)
print(test)

   A  B  C  D Output_col
0  1  0  0  0          A
1  0  1  0  0          B
2  0  0  1  0          C
3  1  0  1  0        A_C
4  1  1  1  0      A_B_C
5  0  0  1  1        C_D

仅应用列列表:

my_list_columns=['enter element of your list']
test['Output_col']=test[my_list_columns].apply(lambda x: '_'.join(x.index[x.eq(1)]),axis=1)
print(test)

所有列的大小写为 0

my_list_columns=['A','B','C','D']
df['Output_col']=df[my_list_columns].apply(lambda x: '_'.join(x.index[x.eq(1)])  if x.eq(1).any() else 'no_value',axis=1)
print(df)

   A  B  C  D Output_col
0  1  0  0  0          A
1  0  0  0  0   no_value
2  0  0  1  0          C
3  1  0  1  0        A_C
4  1  0  1  0        A_C
5  0  0  1  1        C_D

编辑:对于列的子集(我使用方法2)

cols = ['A', 'B']
df1 = df[cols]
s = df1.columns + '-'
df['Output_col'] = df1.dot(s).str[:-1]

Out[54]:
   A  B  C  D Output_col
0  1  0  0  0          A
1  0  1  0  0          B
2  0  0  1  0
3  1  0  1  0          A
4  1  1  1  0        A-B
5  0  0  1  1

试试 str.replacedot

的这种组合
df['Output_col'] = df.dot(df.columns).str.replace(r'(?<!^)(?!$)','-')

Out[32]:
   A  B  C  D Output_col
0  1  0  0  0          A
1  0  1  0  0          B
2  0  0  1  0          C
3  1  0  1  0        A-C
4  1  1  1  0      A-B-C
5  0  0  1  1        C-D

如果您对正则表达式模式感到不安。您可以在不使用 str.replace

的情况下尝试这种方式
s = df.columns + '-'
df['Output_col'] = df.dot(s).str[:-1]

Out[50]:
   A  B  C  D Output_col
0  1  0  0  0          A
1  0  1  0  0          B
2  0  0  1  0          C
3  1  0  1  0        A-C
4  1  1  1  0      A-B-C
5  0  0  1  1        C-D

这基于@Jezrael 提供的解决方案:

df['Output_col'] = df.dot(df.columns.str.cat(['_']*len(df.columns),sep='')).str.strip('_')



    A   B   C   D   Output_col
0   1   0   0   0   A
1   0   1   0   0   B
2   0   0   1   0   C
3   1   0   1   0   A_C
4   1   1   1   0   A_B_C
5   0   0   1   1   C_D