python - 第一个 pandas DataFrame 列索引大于 x

标签 python pandas dataframe

我知道将 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/

相关文章:

python - Google Analytics(分析)Python API调用导致UnboundLocalError

matplotlib - 无法在 Pandas 条形图中调整 x 轴日期格式

scala - 简单随机采样和数据帧 SAMPLE 函数如何在 Apache Spark (Scala) 中工作?

python - Pandas 基于 DataFrame 中找到的字符串的新列

python - 属性错误 : 'MySQLCursor' object has no attribute 'commit'

python - django form.is_valid 返回 false

python - 如何在 Python 中从 OSM 文件中提取和可视化数据

r - R中数据之间的链接

python - word2vec向量[gensim库]的 "size"是什么意思?

python - 将多个项目映射到 pandas 数据框中的一个值