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 -->字典的数组对象列表?
任何帮助都是非常有用的!提前感谢
发布于 2021-01-07 18:17:30
我不确定我是否正确理解了你的问题,但是
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循环遍历safety_class数组,将每个循环的最终值添加到l_factor数组中,并在最后返回该数组。
发布于 2021-01-07 18:25:33
您可以只遍历搜索字符串的列表。
下面是一个最小的工作示例。
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是您的函数希望返回的匹配项之一。
建议的代码片段使用列表理解来遍历搜索字符串searches的列表。注意,我首先从表/数据帧中提取列df['factor'],然后传递布尔索引数组。这减少了应用索引操作的列数,从而加快了代码速度。
对您的代码的一些建议:我建议将您操作的表/数据帧作为参数传递给函数。如果*args **kwargs未使用,您也不应使用它们。
https://stackoverflow.com/questions/65610277
复制相似问题