[英]How to iterate through the inputs to a function
如何使用 Pandas 将数据正确输入到函数中? 下面的代码目前导致错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
我想要做的就是创建一个输出矩阵,其中包含受函数中条件语句约束的字符串。
def mixtapeFire(timesPlayed, rating):
if timesPlayed >=1000 & rating >=3:
print('Your mixtape is fire!')
if rating >5:
print('Invalid Input. Play Again.')
else:
print('You should quit the rap game.')
input1 = pd.DataFrame([900,2000,1001,500,4000])
input2 = pd.DataFrame([3,4,3,1,2])
for x in range(1,5):
output = pd.DataFrame(mixtapeFire(input1.iloc[x,:],input2.iloc[x,:]))
a = pd.DataFrame([900,2000,1001,500,4000])
b = pd.DataFrame([3,4,3,1,2])
对 Series 进行比较会产生多个值。
In [12]: a >= 1000
Out[12]:
0
0 False
1 True
2 True
3 False
4 True
In [13]: b >= 3
Out[13]:
0
0 True
1 True
2 True
3 False
4 False
In [14]: q = (a >= 1000) & (b >= 3)
In [15]: q
Out[15]:
0
0 False
1 True
2 True
3 False
4 False
使用.any()
或.all()
取决于你想要什么。
In [16]: q.any()
Out[16]:
0 True
dtype: bool
In [17]: q.all()
Out[17]:
0 False
dtype: bool
因为结果中有多个True/False
值,所以它无法判断整个系列是True
还是False
。
In [18]: bool(q)
Traceback (most recent call last):
File "<ipython-input-18-6fd0a485fec6>", line 1, in <module>
bool(q)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py", line 955, in __nonzero__
.format(self.__class__.__name__))
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
根据您的需要,您可以将任何“a”方法应用于您的参数 input1.iloc[x,:],input2.iloc[x,:]。 例如:
output = pd.DataFrame(mixtapeFire(input1.iloc[x,:].all(),input2.iloc[x,:].all()))
您可以从官方文档https://pandas.pydata.org/pandas-docs/stable/reference/series.html 中阅读有关 Pandas 访问方法的更多信息
但简而言之:您需要更具体地说明要解析哪些值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.