【问题标题】:How to search list of object through dictionary and return value如何通过字典搜索对象列表并返回值
【发布时间】:2021-01-07 10:06:15
【问题描述】:
Table_3 = 

    safety_class       factor
0          low           0.90
1       medium           0.85
2         high           0.80
3    very_high           0.75

我的代码适用于单行:

def l_factor(safety_class, *args, **kwargs):
    '''This function provides longitudnal usage factor 
        based on the table 3-10'''

    table = tables['Table_3']
    value_search = safety_class
    match_table_value = table[table['safety_class'].str.match(value_search)]    # returns list o
    usage_factor = match_table_value['usasge_factor']
    longitudnal_usage_factor = usage_factor
    
    return l_factor

safety_class = 'medium'

此代码适用于单行,但是如何将其转换为数组的输入?

safety_class = array(['medium', 'medium', 'medium', 'high', 'high'], dtype=object)

如何匹配这些类似于str.contain --> 字典的数组对象列表?

非常感谢任何帮助!提前致谢

【问题讨论】:

  • table3是什么类型的?
  • 您的代码相当混乱,因为很多名称都相当不一致。 match_table_value 没有“usasge_factor”列(除非您的意思是因子?),即使代码中的任何地方都没有使用 l_factor,您最后也会返回 l_factor(除非您的意思是 longitudnal_usage_factor?)

标签: python dictionary object search match


【解决方案1】:

不确定我是否正确理解了您的问题,但是如何

table = tables['Table_3']
l_factor = []
for i in safety_class:
  value_search = i
  match_table_value = table[table['safety_class'].str.match(value_search)]
  something something....
  l_factor.append(longitudnal_usage_factor)
return l_factor

基本上使用 for 循环遍历你的安全类数组,将每个循环的最终值添加到 l_factor 数组中,最后返回该数组。

【讨论】:

  • 感谢您的努力,感谢您的帮助。
【解决方案2】:

您可以只遍历搜索字符串列表。

这是一个最小的工作示例。

import pandas as pd, numpy as np
d         = {'safety_class':['low','medium','high', 'very_high' ],
            'factor':[ 0.90, 0.85, 0.80, 0.75]}
df        = pd.DataFrame(d)
searches  = ['medium','high']
matches   = [ df['factor'][df['safety_class'].str.match(s)] for s in searches]
joined    = np.concatenate(matches)
print(joined)  
> [0.85 0.8 ]

我假设您正在使用 pandas 来创建表格,字符串 'usasge_factor' 应该是 'factor',而 longitudnal_usage_factor 是您希望函数返回的匹配项之一。

建议的 sn-p 使用列表推导来遍历您的搜索字符串列表 searches。请注意,我首先从表/数据框中提取列df['factor'],然后传递布尔索引数组。这减少了应用索引操作的列数,从而加快了代码速度。

对您的代码的一些建议:我建议将您操作的表/数据框作为参数传递给函数。如果*args **kwargs 未使用,您也不应该使用它们。

【讨论】:

  • 感谢您的 Mar,感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-07
  • 2021-09-16
  • 2015-03-29
  • 1970-01-01
相关资源
最近更新 更多