我得到 ValueError: 系列的真值不明确.使用 a.empty、a.bool()、a.item()、a.any() 或 a.all().使用 pandas [英] i get ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). using pandas

查看:92
本文介绍了我得到 ValueError: 系列的真值不明确.使用 a.empty、a.bool()、a.item()、a.any() 或 a.all().使用 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此代码时出错该怎么办?我收到错误 ValueError: 系列的真值不明确.使用 a.empty、a.bool()、a.item()、a.any() 或 a.all().

i get error while running this code what to do? i get error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

unrealized = [0, 0.50, 0.90, 0.20, 3, 6, 7, 2]
    def stoploss():
        df = pd.DataFrame({"price": unrealized})
        df['high'] = df.cummax()
        if df['high'] <= 0.10:
            df['trailingstop'] = -0.50
            df['signalstop'] = df['price'] < df['trailingstop']
        if df['high'] >= 0.10:
            df['trailingstop'] = df['high'] - 0.10
            df['signalstop'] = df['price'] < df['trailingstop']
        return df['signalstop'].iloc[-1]
    
    print(stoploss())

推荐答案

好吧,那是因为一个系列的真值不明确.但是,这是什么意思?只需检查 df['high']<=0.1 的输出,您将看到一系列 True/False 值,具体取决于条件是否满足.并且您正在使用 if 语句询问本系列的真值.那应该是什么?这正是错误告诉你的.我应该使用任何一个还是全部,或者我应该如何处理这个系列?"

Well, it is because the truth value of a series is ambiguous. But what does that mean? Just check the output of df['high']<=0.1 and you'll see a series of True/False values depending on if the condition is met or not. And you are asking the truth value of this series by using the if statement. And what should that be? That is exactly what the error is telling you. "Should I use any or all or what should I do with this series?"

但我假设您想做其他事情:您想根据 high 列中的值设置这两个额外的列.使用带有条件的 .loc 为与条件匹配的所有项目设置值,如下所述:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html

But I assume you want to do something else: You want to set these two extra columns depending on the value in the high column. Use the .loc with a condition to set a value for all items matching the condition as described here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html

所以代码可能看起来像这样(如果我猜对了你的意图):

So the code might look like this (if I guessed your intention correctly):

df['high'] = df.cummax()
df.loc[df['high']<=0.1,'trailingstop'] = -0.50
df.loc[df['high']<=0.1,'signalstop'] = df['price'] < df['trailingstop']
df.loc[df['high']>=0.1,'trailingstop'] = df['high']-0.10
df.loc[df['high']>=0.1,'signalstop'] = df['price'] < df['trailingstop']

这篇关于我得到 ValueError: 系列的真值不明确.使用 a.empty、a.bool()、a.item()、a.any() 或 a.all().使用 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆