如何根据其他列的条件分配新列



我正在尝试添加一列,"flag_ column";基于A、B、C、D中的值。

即,如果a/B/C/D中有值,我想创建一个新列,"flag"表示包含值的列名。

A B C D counts flag
0 1 0 0 0  1     A
1 0 1 0 0  1     B
2 1 0 0 0  1     A
3 0 0 1 0  1     C
4 0 1 0 0  1     B

注意:只有一列(A到D(包含一个值,因此计数将始终为1。

我试过:

if [df['A'] == 1] == True:
df['flag'] = 'A'
elif [df['B'] == 1] == True:
df['flag'] = 'B'
elif [df['C'] == 1] == True:
df['flag'] = 'C'  
else:
df['flag'] = 'D'    

我也试过:

df['flag'] = np.where(df['A'] == 1, 'A', False)
df['flag'] = np.where(df['B'] == 1, 'B', False)
df['flag'] = np.where(df['C'] == 1, 'C', False)
df['flag'] = np.where(df['D'] == 1, 'D', False)

我还尝试过通过每个";类别";以及指定一个标志值,但是在这些情况下它也会覆盖。

如果有一种方法可以让我反复地做这件事,那将是理想的。但是,如果您对这个(简单的(问题有任何帮助,我们将不胜感激!

我们可以在这里使用idxmax而不是axis=1

df['flag'] = df.loc[:, 'A':'D'].idxmax(axis=1)
A  B  C  D flag
0  1  0  0  0    A
1  0  1  0  0    B
2  1  0  0  0    A
3  0  0  1  0    C
4  0  1  0  0    B

试用dot

df['flag'] = df.loc[:,'A':'D'].dot(df.columns[:4])
Out[108]: 
0    A
1    B
2    A
3    C
4    B
dtype: object

对多种条件使用np.select

df['flag'] = np.select([df['A'] == 1, df['B'] == 1, df['C'] == 1, df['D'] == 1],
['A','B','C','D'],
False)
df
Out[1]:
A   B   C   D   counts  flag
0   1   0   0   0   1       A
1   0   1   0   0   1       B
2   1   0   0   0   1       A
3   0   0   1   0   1       C
4   0   1   0   0   1       B

但对于np.where来说,这就是你出错的地方。您应该只在第一次写入False,然后将列的值作为所有剩余np.where语句的替代值:

df['flag'] = np.where(df['A'] == 1, 'A', False)
df['flag'] = np.where(df['B'] == 1, 'B', df['flag'])
df['flag'] = np.where(df['C'] == 1, 'C', df['flag'])
df['flag'] = np.where(df['D'] == 1, 'D', df['flag'])
Out[2]:
A   B   C   D   counts  flag
0   1   0   0   0   1       A
1   0   1   0   0   1       B
2   1   0   0   0   1       A
3   0   0   1   0   1       C
4   0   1   0   0   1       B

正如您所看到的,尽管np.select要简洁得多。

df['flag'] = np.where(df['A'] == 1, 'A', 
np.where(df['B'] == 1, 'B',
np.where(df['C'] == 1, 'C',
np.where(df['D'] == 1, 'D', '?'))))

最新更新