我们现在都如何找到数据帧列的最大值。
但是,如何在列中找到下一个更高的值呢?例如,我有以下数据帧:
d = {'col1': [1, 4, 2], 'col2': [3, 4, 3]}
df = pd.DataFrame(data=d)
col1 col2
0 3 3
1 5 4
2 2 3
基本问题:当我想找到col1
到 0 的下一个更高值时,结果将是:2
。有没有类似于:df.loc[df['col1'].idxmax()]
,这将导致:
col1 col2
5 4
我的结果应该是:
col1 col2
2 3
背景:我正在使用 if 条件来过滤此数据帧,因为我需要为进一步过滤做好准备,并且并非所有值都存在,我将放入:
v= 0
if len(df[(df['col1'] == v)]) == 0:
df2 = df[(df['col1'] == v+1)]
else:
df2 = df[(df['col1'] == v)]
这将导致数据帧为空。
但是我想去下一个条目而不是v+1=1
,在这种情况下,我想插入2
,因为它是下一个更高的值,它的条目在 0 之后。所以条件是:
v= 0
if len(df[(df['col1'] == v)]) == 0:
df2 = df[(df['col1'] == 2)] #the 2 has to be find automatic, as the next value does not have a fixed distance
else:
df2 = df[(df['col1'] == v)]
我怎样才能自动实现这一点?
所以我想要的结果是:
当我输入 v=0 时:
df2
col1 col2
2 3
当我输入 v=2 时,它会跳到 v=3:
df2
col1 col2
3 3
如果我输入 v=3,它会保持(其他条件(:
df2
col1 col2
3 3
检查numpy
的searchsorted
df=df.sort_values('col1')
df.iloc[np.searchsorted(df.col1.values,[0])]
col1 col2
2 2 3
df.iloc[np.searchsorted(df.col1.values,[3,5])]
col1 col2
0 3 3
1 5 4
附加组件(来自提问者(:这也跳过了 if 条件