检查同一行中另一列的字符串中是否包含一个列中的字符串,并添加具有匹配列名的新列

时间:2019-06-15 06:19:07

标签: python-3.x pandas dataframe

除了我之前的问题Search for value in all DataFrame columns (except first column !) and add new column with matching column name(我在其中使用静态关键字)

我想检查第一列中的字符串是否包含在同一行的其他列中,然后添加具有匹配列名称的新列。所有匹配值的所有列名称!

现在,我将其与静态关键字一起使用:

keyword='123'
f = lambda row: row.apply(str).str.replace(".","").str.contains(keyword ,na=False, flags=re.IGNORECASE)
df1 = df.iloc[:,1:].apply(f, axis=1)

df.insert(loc=1, column='Matching_Columns', value=df1.dot(df.columns[1:] + ', ').str.strip(', '))

示例:

输入:

key | col_B | col_C | col_D | col_E
------------------------------------
123 | abcd  | 12345 | fght  | 7890
567 | tdfe  | 6353  | 0567  | 56789

输出:

key | match       | col_B | col_C | col_D | col_E
-------------------------------------------------
123 | col_C       | abcd  | 12345 | fght  | 7890
567 | col_D,col_E | tdfe  | 6353  | 0567  | 56789

任何帮助,不胜感激!

3 个答案:

答案 0 :(得分:2)

涉及df.dot()

的另一种方法
m=df.astype(str).apply(lambda x: x.str.contains(x['key']),axis=1).iloc[:,1:]
df['match']=m.dot(m.columns+',').str[:-1]
print(df)

   key    col_B  col_C    col_D  col_E        match
0  123   abcd    12345   fght     7890        col_C
1  567   tdfe     6353   0567    56789  col_D,col_E

答案 1 :(得分:2)

首先,apply获取布尔数据框。接下来,使用mask将列名分配给True值,将False替换为NaN,并在agg系列上加入dropna联接:

df1 = df.astype(str).apply(lambda x: x[1:].str.contains(x.key), axis=1)
df['match'] = df1.mask(df1, df1.columns[None,:]).replace(False,np.nan) \
                 .agg(lambda x: ','.join(x.dropna()), axis=1)


Out[41]:
   key col_B  col_C col_D  col_E        match
0  123  abcd  12345  fght   7890        col_C
1  567  tdfe   6353  0567  56789  col_D,col_E

答案 2 :(得分:1)

>>> df
  to_find col1 col2
0       a   ab   ac
1       b   aa   ba
2       c   bc   ee
>>> df['found_in'] = df.apply(lambda x: ' '.join(x.iloc[1:][x.iloc[1:].str.contains(str(x['to_find']))].index), axis=1)
>>> df
  to_find col1 col2   found_in
0       a   ab   ac  col1 col2
1       b   aa   ba       col2
2       c   bc   ee       col1

为了提高可读性,

>>> def get_columns(x):
...     y = x.iloc[1:]
...     return y.index[y.str.contains(str(x['to_find']))]
... 
>>> df['found_in'] = df.apply(lambda x: ' '.join(get_columns(x)), axis=1)