import bisect
def find_first_greater(sorted_column, constant):
index = bisect.bisect_right(sorted_column, constant)
if index < len(sorted_column):
return sorted_column[index]
else:
return None # No value greater than the constant found
# Example usage
x = [1, 3, 5, 7, 9]
constant = 5
result = find_first_greater(x, constant)
print(result) # Output: 7
import pandas as pd
import numpy as np
# assuming df is your DataFrame and 'column' is your sorted column
df = pd.DataFrame({'column': [1, 2, 3, 4, 5, 6, 7, 8, 9]})
# set the constant
constant = 5
# get the first value in 'column' that is greater than the constant
value = df.loc[np.argmax(df['column'] > constant), 'column']
print(value)
2条答案
按热度按时间scyqe7ek1#
在上面的例子中,bisect.bisect_right(sorted_column,constant)返回一个索引,在该索引处,常量应该被插入到排序列中以保持其顺序。通过访问sorted_column[index],您将获得第一个大于常量的值。如果索引等于列的长度,则意味着没有值大于常量。
bisect模块是用C实现的,它提供了一种在排序列表中查找插入点的有效方法,使其成为您的任务的合适选择。
pgky5nke2#
还有numpy