Python:在多列中查找字符串并将其返回到新列中

标签 python excel string pandas if-statement

嗨,我有一个包含多列的 excel 数据,我需要对特定单词进行罚款并将其返回到新列中
表格如下所示:

ID   col0  col1  col2  col3  col4  col5
1    jack  a/h   t/m   w/n   y/h    56
2    sam   z/n   b/w   null  null   93
3    john  b/i   y/d   p/d   null   33

我想在 col1、col2、col3 和 col4 列中查找“b”并创建一个名为“b”的新列,其中返回单元格值的值

结果看起来像这样
ID   col0  col1  col2  col3  col4  col5  b
1    jack  a/h   t/m   w/n   y/h    56   -
2    sam   z/n   b/w   null  null   93   b/w
3    john  b/i   y/d   p/d   null   33   b/i

我需要一种有效的方法来做到这一点我尝试在这样的地方使用
df1 = df[['col1', 'col2', 'col3', 'col4']]

df1['b']==[x for x in df1.values[0] if any(b for b in lst if b in str(x))]

我从这个答案中得到了这个 https://stackoverflow.com/a/50250103/3105140

但它对我不起作用,因为我有空值和条件不起作用的行

最佳答案

这是使用 stack 的方法和 str.contains df.where :

cols = ['col1', 'col2', 'col3', 'col4']
df['b'] = (df[cols].where(df[cols].stack().str.contains('b')
         .unstack(fill_value=False)).ffill(1).iloc[:,-1])
print(df)

   ID  col0 col1 col2 col3 col4  col5    b
0   1  jack  a/h  t/m  w/n  y/h    56  NaN
1   2   sam  z/n  b/w  NaN  NaN    93  b/w
2   3  john  b/i  y/d  p/d  NaN    33  b/i

关于Python:在多列中查找字符串并将其返回到新列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59879678/

相关文章:

python - 计算 Pandas 中单词出现次数的最快方法

sql - 不支持 Excel VBA SQL JOIN 表达式

.net - 单元格注释的字符串格式 EPPLUS 库

java - Java中将所有字符大写并在每个字符之间添加空格的递归方法

c - 函数 shmdt() 有什么问题?

python - Django SMTPAuthenticationError

python - Cython,纯 Python 模式 : . pxd 和 @locals

python - AppRegistryNotReady : The translation infrastructure cannot be initialized

excel - 将数字作为文本导入到 Power Pivot 中

c# - 从 C# 中的两个字符串变量转换为 DateTime