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
--> 字典的数组对象列表?
任何帮助都非常感谢!!提前致谢
答案 0 :(得分: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 数组中,并在最后返回该数组。
答案 1 :(得分:1)
您可以遍历搜索字符串列表。
这里的一个最低工作示例。
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 ]
我以为你与大熊猫工作创建表,字符串'usasge_factor'
意在'factor'
,而longitudnal_usage_factor
是要已返回的比赛之一你的函数。
建议的片段使用列表解析来遍历你列出搜索字符串的searches
。注意,我首先提取从表/数据帧列df['factor']
,然后布尔索引数组传递。这减少了索引操作被施加到列的数量,极大地提高了代码起来。
的几点建议WRT到您的代码:我建议你通过你作为参数传递给函数操作表/数据帧。你也应该不使用*args
**kwargs
,如果它们是未使用。