【发布时间】:2019-12-11 16:14:31
【问题描述】:
df1 包含我要搜索的较大的主要字符串。 df2 包含一个子字符串列表,每个子字符串都有一个值。
import pandas as pd
df1 = pd.DataFrame(columns = ['MainString'])
df1 = df1.append({'MainString':'abcdef'}, ignore_index=True)
df1 = df1.append({'MainString':'ghijkl'}, ignore_index=True)
df1 = df1.append({'MainString':'mnopqr'}, ignore_index=True)
df1 = df1.append({'MainString':'stuvwx'}, ignore_index=True)
df2 = pd.DataFrame(columns = ['Substring','Value'])
df2 = df2.append({'Substring':'bcde','Value':0.5}, ignore_index=True)
df2 = df2.append({'Substring':'bcd','Value':0.6}, ignore_index=True)
df2 = df2.append({'Substring':'mno','Value':0.4}, ignore_index=True)
df2 = df2.append({'Substring':'stuv','Value':0.7}, ignore_index=True)
df2 = df2.append({'Substring':'uvwx','Value':0.7}, ignore_index=True)
df2 = df2.append({'Substring':'stu','Value':0.4}, ignore_index=True)
print(df1)
MainString
0 abcdef
1 ghijkl
2 mnopqr
3 stuvwx
print(df2)
Substring Value
0 bcde 0.5
1 bcd 0.6
2 mno 0.4
3 stuv 0.7
4 uvwx 0.7
5 stu 0.4
我想在df1['MainString'] 中搜索df2['Substring'] 中的值,然后只返回最大值。如果有平局(例如 stuv 和 uvwx),则返回第一个。所以决赛看起来像:
MainString Substring Value
0 abcdef bcd 0.6
1 ghijkl NaN NaN
2 mnopqr mno 0.4
3 stuvwx stuv 0.7
不确定我是否需要循环并使用每个子字符串评估每个 MainString。我试过调整this solution,但它只返回第一个匹配的字符串,而不是具有最高值的子字符串:
s_list = list(df2['Substring'])
s_list = '(' + '|'.join(s_list) + ')'
df1['test'] = df1['MainString'].str.extract(s_list, expand=False)
print(df1)
MainString test
0 abcdef bcde
1 ghijkl NaN
2 mnopqr mno
3 stuvwx stuv
【问题讨论】:
-
您的
df2有多久了?如果循环时间不太长,循环可能会有所帮助。 -
不会太长,我可以为此做一个循环。但我可能会将此应用于另一个未来的流程,并且该表会更长(df1 可能有几百万行,df2 几百行)。