gpt4 book ai didi

python - 查找 pandas DataFrame 值的索引

转载 作者:太空狗 更新时间:2023-10-30 01:01:25 27 4
gpt4 key购买 nike

我正在尝试使用 pandas 处理一些 .csv 数据,我正在努力解决一些我确信是新手的问题,但在花了很多时间尝试完成这项工作之后,我需要你的帮助。

p>

本质上,我试图在我创建的数据框中找到值的索引。

max = cd_gross_revenue.max()
#max value of the cd_gross_revenue dataframe

print max
#finds max value, no problem!

maxindex = cd_gross_revenue.idxmax()
print maxindex
#finds index of max_value, what I wanted!

print max.index
#ERROR: AttributeError: 'numpy.float64' object has no attribute 'index'

maxindex 变量使用 idxmax() 得到答案,但是如果我不是在寻找最大值的索引怎么办?如果我正在查看的是某个随机值的索引,我将如何处理呢?显然 .index 在这里对我不起作用。

在此先感谢您的帮助!

最佳答案

使用 bool 掩码 获取值等于随机变量的行。然后使用该掩码来索引数据框或系列。然后您将使用 pandas 数据框或系列的 .index 字段。一个例子是:

In [9]: s = pd.Series(range(10,20))

In [10]: s
Out[10]:

0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
dtype: int64

In [11]: val_mask = s == 13

In [12]: val_mask

Out[12]:
0 False
1 False
2 False
3 True
4 False
5 False
6 False
7 False
8 False
9 False
dtype: bool

In [15]: s[val_mask]
Out[15]:
3 13
dtype: int64

In [16]: s[val_mask].index
Out[16]: Int64Index([3], dtype='int64')

关于python - 查找 pandas DataFrame 值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26150171/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com