gpt4 book ai didi

python - 如何在 Pandas 数据框中执行排序搜索?

转载 作者:行者123 更新时间:2023-11-28 18:09:28 25 4
gpt4 key购买 nike

我有一个输入字符串,如下所示:

ms = 'hello stack overflow friends'

以及具有以下结构的 pandas 数据框:

      string  priority  value
0 hi 1 2
1 astronaut 10 3
2 overflow 3 -1
3 varfoo 4 1
4 hello 2 0

然后我尝试执行以下简单算法:

  1. df['priority'] 列对 pandas 数据帧进行升序排序。
  2. 检查 ms 字符串变量是否包含 df['string'] 单词。
  3. 如果是,返回它的df['value']

因此,这是我这样做的方法:

import pandas as pd

ms = 'hello stack overflow friends'

df = pd.DataFrame({'string': ['hi', 'astronaut', 'overflow', 'varfoo', 'hello'],
'priority': [1, 10, 3, 4, 2],
'value': [2, 3, -1, 1, 0]})

final_val = None

for _, row in df.sort_values('priority').iterrows():
# just printing the current row for debug purposes
print (row['string'], row['priority'], row['value'])

if ms.find(row['string']) > -1:
final_val = row['value']
break

print()
print("The final value for '", ms, "' is ", final_val)

返回以下内容:

hi 1 2
hello 2 0

The final value for ' hello stack overflow friends ' is 0

这段代码工作正常,但问题是我的 df 有大约 20K 行,我需要执行这种搜索超过 1K 次。

这大大降低了我的流程的性能。那么有没有比我使用纯 pandas 并避免不必要的循环更好(或更简单)的方法?

最佳答案

编写一个可以应用于数据框的函数,而不是使用 iterrows

match_set = set(ms.split())
def check_matches(row):
return row['value'] if row['string'] in match_set else None

df['matched'] = df.apply(check_matches, axis=1)

这给了你:

   priority     string  value  matched
0 1 hi 2 NaN
1 10 astronaut 3 NaN
2 3 overflow -1 -1.0
3 4 varfoo 1 NaN
4 2 hello 0 0.0

然后您可以对值进行排序,并从 df.matched 中获取第一个非 NaN 值,以获得您所谓的 final_value

df.sort_values('priority').matched.dropna().iloc[0]
0.0

或者,您可以将 df 排序并转换为元组列表:

l = df.sort_values('priority').apply(lambda r: (r['string'], r['value']), axis=1).tolist()

给予:

l
[('hi', 2), ('hello', 0), ('overflow', -1), ('varfoo', 1), ('astronaut', 3)]

然后编写一个在遇到第一个匹配项时停止的函数:

def check_matches(l):
for (k, v) in l:
if k in match_set:
return v
check_matches(l)
0

关于python - 如何在 Pandas 数据框中执行排序搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51621190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com