Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用DataFrame列中的子字符串替换字符串_Python_Pandas - Fatal编程技术网

Python 用DataFrame列中的子字符串替换字符串

Python 用DataFrame列中的子字符串替换字符串,python,pandas,Python,Pandas,我正在尝试将数据帧中的一列与子字符串列表中的一个匹配 e、 g.使用以下值获取列(字符串): text1C1 text2A text2 text4 text4B text4A3 并创建一个新列,该列已将它们与以下子字符串匹配: vals = ['text1', 'text2', 'text3', 'text4', 'text4B'] 我目前拥有的代码是有效的,但它似乎是解决问题的一种非常低效的方法 df=pd.DataFrame({'strings':['text1C1','text2A',

我正在尝试将数据帧中的一列与子字符串列表中的一个匹配

e、 g.使用以下值获取列(
字符串
):

text1C1
text2A
text2
text4
text4B
text4A3
并创建一个新列,该列已将它们与以下子字符串匹配:

vals = ['text1', 'text2', 'text3', 'text4', 'text4B']
我目前拥有的代码是有效的,但它似乎是解决问题的一种非常低效的方法

df=pd.DataFrame({'strings':['text1C1','text2A','text2','text4','text4B','text4A3']})
对于VAL中的v:
df.loc[df[df['strings'].str.contains(v)].index,“matched strings']=v
这将返回以下数据帧,这正是我所需要的

字符串匹配字符串
0 text1C1 text1
1文本2a文本2
2文本2文本2
3文本4文本4
4文本4B文本4B
5文本4A3文本4
是否有一种更有效的方法,特别是对于较大的数据帧(10k+行)


我想不出如何处理
VAL
的其中一项同时也是另一项的子字符串(
text4
text4B
的子字符串)

使用生成器和
next
匹配第一个值:

s = vals[::-1]
df['matched strings1'] = df['strings'].apply(lambda x: next(y for y in s if y in x))
print (df)
   strings matched strings matched strings1
0  text1C1           text1            text1
1   text2A           text2            text2
2    text2           text2            text2
3    text4           text4            text4
4   text4B          text4B           text4B
5  text4A3           text4            text4
如果可能,更一般的解决方案是没有与
iter
匹配的值和
next
的默认参数:

f = lambda x: next(iter(y for y in s if y in x), 'no match')
df['matched strings1'] = df['strings'].apply(f)
应改进您的解决方案:

for v in vals:
    df.loc[df['strings'].str.contains(v, regex=False), 'matched strings'] = v