PANDAS:从另一列中选择两个指定值之间的最高和最低值



我的原始dataframe看起来像这样:

 macd_histogram  direct    event
1.675475e-07    up  crossing up
2.299171e-07    up  0
2.246809e-07    up  0
1.760860e-07    up  0
1.899371e-07    up  0
1.543226e-07    up  0
1.394901e-07    up  0
-3.461691e-08  down crossing down
1.212740e-06    up  0
6.448285e-07    up  0
2.227792e-07    up  0
-8.738289e-08  down crossing up
-3.109205e-07  down 0

列事件充满了crossing upcrossing down!我需要的是在crossing upcrossing down之间从macd_histogram列(在相同索引之间)提取最高值,并从最低点提取它,并将其添加到crossing up旁边的新列中!

我尝试使用for循环进行操作,但是我在如何选择每个 crossing upcrossing down之间的范围有点丢失...有什么帮助吗?谢谢!

我所期望的事实(遵循上述数据框):

 macd_histogram  direct    event magnitude
1.675475e-07    up  crossing up (0.851908-07)
2.299171e-07    up  0
2.246809e-07    up  0
1.760860e-07    up  0
1.899371e-07    up  0
1.543226e-07    up  0
1.394901e-07    up  0
-3.461691e-08  down crossing down (2.651908-06)
1.212740e-06    up  0
6.448285e-07    up  0
2.227792e-07    up  0
-8.738289e-08  down crossing up etc..
-3.109205e-07  down 0

这是我到目前为止尝试的:

index_up = df[df.event == 'crossing up'].index.values
index_down = df[df.event == 'crossing down'].index.values

df['magnitude'] = 0
array = np.array([])
for i in index_up:
    for idx in index_down:
        values = df.loc[i:idx, 'macd_histogram'].tolist()
        max = np.max(values)
        min = np.min(values)
        magnitutde = max-min
        print(magnitude)
       df.at[i,'magnitude'] = magnitude

但是我有以下错误消息: ValueError: zero-size array to reduction operation maximum which has no identity

我想我理解您的要求,但是我的结果数字与您的示例不符,所以也许我不完全理解。希望这个很多答案对您有所帮助。

首先创建一个列放置结果。

df['result'] = np.nan

创建一个只有行索引的变量,然后向上/向下。

event_range = df[df['event'] != '0'].index

制作一个循环以循环循环穿过索引阵列。为每个部分创建一个开始和结束索引编号,获取每个开始/结束索引号的最大值和最小范围,然后将其减去并放在右列中。

for x in range(len(event_range)-1):    
    start = event_range[x]
    end = event_range[x+1] +1 # I'm not sure if this is the range you want
    max = df.iloc[start:end, 0].max()
    min = df.iloc[start:end, 0].min()
    diff = max - min
    df.iloc[start, 3] = diff
df

    macd_histogram  direct  event             result
0   1.675480e-07    up      crossing up       2.645339e-07
1   2.299170e-07    up      0                 NaN
2   2.246810e-07    up      0                 NaN
3   1.760860e-07    up      0                 NaN
4   1.899370e-07    up      0                 NaN
5   1.543230e-07    up      0                 NaN
6   1.394900e-07    up      0                 NaN
7  -3.461690e-08    down    crossing down     1.300123e-06
8   1.212740e-06    up      0                 NaN
9   6.448290e-07    up      0                 NaN
10  2.227790e-07    up      0                 NaN
11 -8.738290e-08    down    crossing up       NaN
12 -3.109210e-07    down    0                 NaN

最新更新