不明确的真值与布尔逻辑 [英] Ambiguous truth value with boolean logic

查看:167
本文介绍了不明确的真值与布尔逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用一些布尔逻辑上的数据帧功能,但得到一个错误:

I am trying to use some boolean logic in a function on a dataframe, but get an error:

在[4]:

data={'level':[20,19,20,21,25,29,30,31,30,29,31]}
frame=DataFrame(data)
frame
Out[4]:
level
0   20
1   19
2   20
3   21
4   25
5   29
6   30
7   31
8   30
9   29
10  31

In [35]:

def calculate(x):
    baseline=max(frame['level'],frame['level'].shift(1))#doesnt work
    #baseline=x['level']+4#works
    difftobase=x['level']-baseline
    return baseline, difftobase
frame['baseline'], frame['difftobase'] = zip(*frame.apply(calculate, axis=1))#works

不过,这引发以下错误的:

However, this throws the following error at:

baseline=max(frame['level'],frame['level'].shift(1))#doesnt work


ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', u'occurred at index 0')

我读<一href="http://stackoverflow.com/questions/14386117/how-to-look-back-at-$p$pvious-rows-from-within-pandas-dataframe-function-call">How从内部熊猫数据框的函数调用回看previous行? 和 http://pandas.pydata.org/pandas-docs/stable/gotchas。 HTML  但无法弄清楚如何将此应用到我的问题?

I read How to look back at previous rows from within Pandas dataframe function call? and http://pandas.pydata.org/pandas-docs/stable/gotchas.html but can't figure out how to apply this to my problem?

推荐答案

不充分的使用功能最大的。 np.maximum(也许np.ma.max以及每个numpy的文档)的作品。显然,普通的最大不能处理数组(容易)。更换

Inadequate use of the function max. np.maximum (perhaps np.ma.max as well as per numpy documentation) works. Apparently regular max can not deal with arrays (easily). Replacing

baseline=max(frame['level'],frame['level'].shift(1))#doesnt work

baseline=np.maximum(frame['level'],frame['level'].shift(1))

的伎俩。我删除了另一部分,使之更易于阅读:

does the trick. I removed the other part to make it easier to read:

In [23]:
#q 1 analysis
def calculate_rowise(x):
    baseline=np.maximum(frame['level'],frame['level'].shift(1))#works
    return baseline
frame.apply(calculate_rowise)

Out[23]:
level
0   NaN
1   20
2   20
3   21
4   25
5   29
6   30
7   31
8   31
9   30
10  31

PS原来的问题是躲在另一个问题取出职能转变的一部分时出现了。返回的形状不匹配,但那是另外一个问题,刚才提到在这里充分披露

PS the original problem is hiding another issue that shows up when taking out the shift portion of the function. The return shape doesn't match, but thats another problem, just mentioning it here for full disclosure

这篇关于不明确的真值与布尔逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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