我想将应用与两列一起使用并添加其他参数。我的用例是对一列执行搜索并将正则表达式返回到另一列,而不会覆盖另一列中的现有值。也许迭代是:)更好的选择。
import random
import re
import pandas as pd
import numpy as np
#create the dataframe
df = pd.DataFrame({
'a':np.random.choice( ['the_panda','it_python','my_shark'], 6),
})
df["b"] = ""
收益 率:
a b
0 the_panda
1 my_shark
2 my_shark
3 the_panda
4 it_python
5 the_panda
每次我应用我的函数时,如果值出现在"a"列中,那么我想将搜索字符串写入"b"列。因此,如果我使用"熊猫"然后使用"鲨鱼"进行搜索,它将如下所示:
a b
0 the_panda panda
1 my_shark shark
2 my_shark shark
3 the_panda panda
4 it_python
5 the_panda panda
我创建了一个简单的函数:
def search_log(b,a,search_sting):
so = re.search(search_string,a)
if so:
return search_string
else:
return b
但是,我不确定在这种情况下是否有办法向 apply 函数添加其他参数?这是我正在尝试的:
search_string = 'panda'
df['b'] = df.apply(lambda x: search_log(x['b'],x['a']),args=(search_string,),axis=1)
这会产生:
TypeError: ('<lambda>() takes 1 positional argument but 2 were given', 'occurred at index 0')
。或
df['b'] = df.apply(lambda x: search_log(x['b'],x['a'],args=(search_string,),axis=1))
这会产生:
KeyError: ('b', 'occurred at index a')
string = ["panda","shark","python"]
df["b"] = df["a"].apply(lambda y:[x for x in string if x in y][0] if len([x for x in string if x in y])==1 else "")
输出:
a b
0 it_python
1 my_shark
2 my_shark
3 the_panda
4 my_shark
5 my_shark
a b
0 it_python python
1 my_shark shark
2 my_shark shark
3 the_panda panda
4 my_shark shark
5 my_shark shark