且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我得到 ValueError: 系列的真值不明确.使用 a.empty、a.bool()、a.item()、a.any() 或 a.all().使用 pandas

更新时间:2021-09-24 18:37:42

好吧,那是因为一个系列的真值不明确.但是,这是什么意思?只需检查 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']