在所有DataFrame列中搜索值(第一列除外!),并添加具有匹配列名的新列 [英] Search for value in all DataFrame columns (except first column !) and add new column with matching column name

查看:238
本文介绍了在所有DataFrame列中搜索值(第一列除外!),并添加具有匹配列名的新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对DataFrame的所有列(第一列除外!)进行搜索,并添加一个新列(例如'Column_Match'),其名称为匹配列.

I'd like to do a search on all columns (except the first column !) of a DataFrame and add a new column (like 'Column_Match') with the name of the matching column.

我尝试过这样的事情:

df.apply(lambda row: row.astype(str).str.contains('my_keyword').any(), axis=1)

但是它不排除第一列,我也不知道如何返回并添加列名.

But it's not excluding the first column and I don't know how to return and add the column name.

任何帮助,不胜感激!

推荐答案

如果希望每行第一个匹配值的列名,则通过

If want columns name of first matched value per rows add new column for match not exist values by DataFrame.assign and DataFrame.idxmax for column name:

df = pd.DataFrame({
         'B':[4,5,4,5,5,4],
         'A':list('abcdef'),
         'C':list('akabbe'),
         'F':list('eakbbb')
})


f = lambda row: row.astype(str).str.contains('e')
df['new'] = df.iloc[:,1:].apply(f, axis=1).assign(missing=True).idxmax(axis=1)
print (df)
   B  A  C  F      new
0  4  a  a  e        F
1  5  b  k  a  missing
2  4  c  a  k  missing
3  5  d  b  b  missing
4  5  e  b  b        A
5  4  f  e  b        C

如果需要所有匹配值的所有列名称,则创建boolean DataFrame并使用点乘积,其列名称应使用

If need all columns names of all matched values create boolean DataFrame and use dot product with columns names by DataFrame.dot and Series.str.rstrip:

f = lambda row: row.astype(str).str.contains('a')
df1 = df.iloc[:,1:].apply(f, axis=1)
df['new'] = df1.dot(df.columns[1:] + ', ').str.rstrip(', ').replace('', 'missing')
print (df)
   B  A  C  F      new
0  4  a  a  e     A, C
1  5  b  k  a        F
2  4  c  a  k        C
3  5  d  b  b  missing
4  5  e  b  b  missing
5  4  f  e  b  missing

这篇关于在所有DataFrame列中搜索值(第一列除外!),并添加具有匹配列名的新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆