我知道将 pandas DataFrame 列转换为列表(使用 .tolist()
或 list()
)然后做你想做的事慢,所以我不想使用 these methods .
我想找到 pandas DataFrame 列的第一个元素的索引,它等于或大于值 x
,换句话说 >=x
。如果什么都没有,则返回 None
。
例如,如果列是这个并且我们的函数被称为first_greater()
:
0
0 1
1 -5
2 6
3 4
4 -7
5 12
6 -2
7 0
8 -3
然后我们有:
first_greater(-5) = 0
first_greater(7) = 5
first_greater(4) = 2
first_greater(6) = 2
first_greater(22) = None
我是 Pandas 的新手,我不知道该怎么做。任何帮助将不胜感激。
最佳答案
您想要检查数据框中的任何值是否大于给定值,并返回满足条件的第一个值。你有 idxmax
:
def first_greater(df, n, col):
m = df.col.ge(n)
return m.any() and m.idxmax()
注意在return语句中,and
右边的部分只有在满足第一个条件m.any()
时才会被求值,否则为False
返回。
让我们检查一下建议的示例:
first_greater(df, 5, 'col1')
# 0
first_greater(df, 7, 'col1')
# 5
first_greater(df, 4, 'col1')
# 2
first_greater(df, 6, 'col1')
# 2
first_greater(df, 22, 'col1')
# False
输入数据-
col1
0 1
1 -5
2 6
3 4
4 -7
5 12
6 -2
7 0
8 -3
关于python - 第一个 pandas DataFrame 列索引大于 x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57823323/