gpt4 book ai didi

python - 如何使用map检查每个列表元素是否在任何一组范围内? (类型错误: len() of unsized object)

转载 作者:太空宇宙 更新时间:2023-11-03 16:37:56 25 4
gpt4 key购买 nike

我有一个元素列表,我想使用映射函数生成一个按元素列表,确定它们是否在范围列表中的任何范围内。我已经有了一个使用 for 循环的解决方案,但 for 循环太慢了,因为我的元素和范围列表都会大得多。

这是迄今为止我的代码:

import pandas as pd

# check element-wise if [1,0,45,60] within ranges 1-10, 21-30, or 41-50
# expected output: true, false, true, false
s = pd.Series([1,0,45,60])
f = lambda x: any((x >= pd.Series([1,20,40])) & (x <= pd.Series([10,30,50])))
print map(f, s)

错误:

    elif isinstance(other, (np.ndarray, pd.Index)):
--> if len(self) != len(other):
raise ValueError('Lengths must match to compare')
return self._constructor(na_op(self.values, np.asarray(other)),

TypeError: len() of unsized object

最佳答案

想通了。似乎一切正常,并且如果我转换为 numpy 仍然很快。通常我会不赞成引入一个新的库,但 pandas 是建立在 numpy 之上的。

import pandas as pd, numpy as np

s = pd.Series([1,0,45,60])
mins = np.array(pd.Series([1,20,40]))
maxes = np.array(pd.Series([10,30,50]))
f = lambda x: np.any((x >= mins) & (x <= maxes))
print map(f, s)

关于python - 如何使用map检查每个列表元素是否在任何一组范围内? (类型错误: len() of unsized object),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37059171/

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