Pandas 系列移位和条件返回系列的真值不明确
我有一个熊猫系列Pandas 系列移位和条件返回系列的真值不明确,pandas,iteration,conditional-statements,series,shift,Pandas,Iteration,Conditional Statements,Series,Shift,我有一个熊猫系列df,包含10个值(都是双精度值)。 我的目标是创建一个新系列,如下所示 newSerie = 1 if df > df.shift(1) else 0 换句话说,如果df的当前值大于其先前值,则newSerie输出1(否则应输出0) 然而,我得到: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 此
df
,包含10个值(都是双精度值)。
我的目标是创建一个新系列,如下所示
newSerie = 1 if df > df.shift(1) else 0
换句话说,如果df
的当前值大于其先前值,则newSerie
输出1(否则应输出0)
然而,我得到:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
此外,我的目标是将df
和newSerie
连接为一个数据帧,但是newSerie
输出9个值,因为我们无法将df
的第一个值与shitf(1)进行比较。因此,我需要newSerie
的第一个值为空,以便能够连接
我该怎么做
举一个例子,假设我的输入只是系列df。我的输出应该如下图所示:
您可以使用
shift
或diff
:
# example dataframe:
data = pd.DataFrame({'df':[10,9,12,13,14,15,18,16,20,1]})
df
0 10
1 9
2 12
3 13
4 14
5 15
6 18
7 16
8 20
9 1
使用系列.shift
:
data['NewSerie'] = data['df'].gt(data['df'].shift()).astype(int)
或Series.diff
data['NewSerie'] = data['df'].diff().gt(0).astype(int)
输出
df NewSerie
0 10 0
1 9 0
2 12 1
3 13 1
4 14 1
5 15 1
6 18 1
7 16 0
8 20 1
9 1 0
您的数据帧的名称是什么?