我试图在numpy中执行多个条件,但得到了错误:cannot compare a dtyped [object] array with a scalar of type [bool]
下面是这行代码:
d7['CAD'] = np.where(d7['Category'] == 'Stack' & d7['Currency'] == fxratetable['from_currency'],d7['CAD'] * fxratetable['fx_rate'], d7['CAD'])除了fx_rate是float64之外,所有的dtypes都是object。
另一个想法是,我用Category = Stack查找一个值,但用我的Currency = from_currency查找多个值。
有人能帮上忙吗?
谢谢。
新错误
ValueError: Can only compare identically-labeled Series objects now. 这是我的新声明
d7['CAD'] = np.where((d7['Category'] == 'Stack') &
(d7['Currency'] == fxratetable['from_currency']),
d7['CAD'] * fxratetable['fx_rate'],
d7['CAD'])d7:
+--------------+----------+----------+
| CAD | Currency | Category |
+--------------+----------+----------+
| -4350242.355 | GBP | Stack |
+--------------+----------+----------+
| 424223.7584 | AUD | Stack |
+--------------+----------+----------+fxratetable:
+---------------+---------+
| from_currency | fx_rate |
+---------------+---------+
| GBP | 1.367 |
+---------------+---------+
| AUD | 0.7706 |
+---------------+---------+需要新的CAD列。
+----------------+
| CAD (expected) |
+----------------+
| -5948957.275 |
+----------------+
| 326991.5663 |
+----------------+发布于 2021-01-30 07:50:27
我个人更喜欢在处理条件时使用DataFrame.apply。
d7['CAD'] = d7.apply(lambda row: row.CAD * fxratetable[fxratetable.from_currency == row.Currency].fx_rate.item() \
if row.Category == 'Stack' else row.CAD, axis=1)fxratetable[fxratetable.from_currency == row.Currency]在fxratetable中选择与正确货币对应的行,.fx_rate选择rate列,.item()提供数字,而不是系列。
您可以看到,只有row.Category == 'Stack'条件仍然存在,有问题的系列比较现在是选择的一部分。
最后,使用axis=1将该函数应用于DataFrame行(docu)。
我还没有进行过广泛的测试,所以请让我知道它是否有效。
发布于 2021-01-29 23:14:39
问题出在布尔表达式的第二部分。假设d7不只是两行,否则就不会有这个问题。d7['Currency'] == fxratetable['from_currency']逐行比较两个序列,当行耗尽fxratetable时,它不再知道要将d7与什么进行比较。
我不知道您是否设置了使用NumPy,或者您可以做的事情是否有限制,但merge语句将非常容易地处理这些问题:
# Merge the exchange rate
d7 = pd.merge(d7, fxratetable, left_on='Currency', right_on='from_currency', how='left')
# Find the rows which have a non-NaN exchange rate and multiply
d7['CAD'] = np.where(~np.isnan(d7['fx_rate']), d7['CAD']*d7['fx_rate'], d7['CAD'])发布于 2021-02-02 20:09:58
我认为这将是您所期望的。我已经用一种容易理解的方式写了它。
d7 = pd.DataFrame({'CAD':[-4350242.355,424223.7584],'Currency':['GBP','AUD'],'Category':['Stack','Stack']})
fxratetable = pd.DataFrame({'from_currency':['GBP','AUD'],'fx_rate':[1.367,0.7706 ]})
_condition1 = d7['Category'] == 'Stack'
_condition2 = d7['Currency'] == fxratetable['from_currency']
d7['CAD (expected)'] = np.where(_condition1 & _condition2,d7['CAD'] * fxratetable['fx_rate'],d7['CAD'])
d7输出

https://stackoverflow.com/questions/65905132
复制相似问题