值的长度与索引的长度不匹配

Length of Values Not Matching Length of Index

我正在使用 Python 的 Pandas 库进行一些加密货币分析。我制作了以下数据框:

        coin    old_price      current_price
0     BNBBTC    0.000949            0.000994
1     BNBETH    0.011472            0.012129
2    BNBUSDT   10.938950            9.358000
3     VENBNB    0.619480            0.635200

然后,我尝试比较 old_price 和 current_price 这两列。

使用下面这行代码后:

comparison['sell'] = np.where((comparison['current_price'] >= comparison['old_price']))

我收到一条错误消息:

"ValueError: Length of values does not match length of index"

据我所知,数据框每一列的数据数量相同。请指教,将不胜感激。

np.where(condition) 没有第二个和第三个可选参数 returns conditionTrue 的行索引数组。该数组通常比原始 DataFrame 短(在您的情况下,它只有一个值):

np.where(comparison['current_price'] >= comparison['old_price'])
#(array([2]),)

你需要的大概是这个:

comparison['sell'] = (comparison['current_price'] >= comparison['old_price'])
#array([False, False,  True, False], dtype=bool)