您没有显示您期望的结果,但您始终可以使用
df[k + ' col'] = df.Desc.map(...) + "," + df.Desc1.map(...)
但这会在空单元格中添加,,并且会重复重复值。
import pandas as pd
df = pd.DataFrame({
'Desc': ['cat is black', 'dog is white'],
'Desc1': ['cat is white', 'dog is white'],
})
kw = ['cat','dog']
for k in kw:
df[k + ' col'] = df.Desc.map(lambda s: s if k in s else '') + ',' + df.Desc1.map(lambda s: s if k in s else '')
print(df.to_string())
结果:
Desc Desc1 cat col dog col
0 cat is black cat is white cat is black,cat is white ,
1 dog is white dog is white , dog is white,dog is white
但是您也可以使用.apply(function, args=[...], axis=1) 将整行发送到函数并在函数中运行更复杂的代码
import pandas as pd
df = pd.DataFrame({
'Desc': ['cat is black', 'dog is white'],
'Desc1': ['cat is white', 'dog is white'],
})
def select(row, word):
result = []
if word in row['Desc']:
result.append(row['Desc'])
if word in row['Desc1']:
result.append(row['Desc1'])
# skip duplicated
if len(result) > 1 and result[0] == result[1]:
result = result[:1]
return ",".join(result)
kw = ['cat','dog']
for word in kw:
df[f'{word} col'] = df.apply(select, args=[word], axis=1)
print(df.to_string())
结果:
Desc Desc1 cat col dog col
0 cat is black cat is white cat is black,cat is white
1 dog is white dog is white dog is white