有个问题。我有一个记录列表,还有另一个记录列表,我正在比较第一个列表。 当我写行时(第一个列表的行内阅读:
for index, row in output_merged_po.iterrows():
stock = output_merged_stock[output_merged_stock['PN_STRIPPED']==row['PN_STRIPPED']][['Whs']]
print stock
我得到结果
Whs
11763 VLN
其中 11763 是 output_merged_stock id 号,Whs 是 PN_stripped 匹配的 whs 的名称。
但我无法提取数据进行进一步处理。我只想编写简单的 if 语句,我可以在其中询问是否 whs = VLN。我写道:
if stock[['Whs']] == 'VLN':
print stock
我收到错误:DataFrame 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
我写道:
if stock == 'VLN':
print stock
我又得到了:DataFrame 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
如果我想得到结果 'VLN',我应该如何写 if 语句?例如,有时库存输出有时是 3 whs,其中 2 个是“VLN”,第三个是“XRS”,在这种情况下,我应该看到“if”输出是 VLN 的 2 倍,没有 XRS
请您参考如下方法:
您正在尝试比较这里不需要的 df 和一个不正确的标量值,因为它在测试标量值时变得模棱两可,因为您可能有 1 个或多个匹配项。
我想你想要:
if all(stock['Whs']] == 'VLN'):
或者如果您知道只有一行,那么:
if stock['Whs'].values[0] == 'VLN':
例子:
In [79]:
# create some dummy data
df = pd.DataFrame({'a':np.arange(5), 'b':2})
df
Out[79]:
a b
0 0 2
1 1 2
2 2 2
3 3 2
4 4 2
试试你试过的东西:
if df['a'] == 2:
print("we have 2")
引发:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
所以我们可以从错误中得到提示:
In [82]:
if any(df['a'] == 2):
print("we have 2")
we have 2
我们可以将 all 与 'b' 列一起使用:
In [83]:
if all(df['b'] == 2):
print("all are 2")
all are 2
如果您比较具有单行值的系列,那么您可以这样做:
In [84]:
if df.iloc[2]['a'] == 2:
print("we have 2")
we have 2
但是超过 1 行就变得不明确了:
if df.iloc[1:3]['b'] == 2:
print("we have 2")
再次引发 ValueError 但以下会起作用:
In [87]:
if df.iloc[1:3]['b'].values[0] == 2:
print("we have 2")
we have 2
