查找pandas数据帧值的索引

2024-09-26 17:42:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用pandas处理一些.csv数据,我正在努力处理一些我确信是新手的举动,但在花了很多时间尝试使之生效后,我需要你的帮助。

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

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()得到答案,但是如果我不寻找最大值的索引呢?如果我看到的是某个随机值的索引,我该怎么做呢?显然,索引在这里对我不起作用。

提前感谢您的帮助!


Tags: ofcsv数据nopandasindexvaluecd
3条回答

使用boolean mask获取值等于随机变量的行。 然后使用该掩码索引数据帧或序列。 然后使用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')

s[s==13]

例如

from pandas import Series

s = Series(range(10,20))
s[s==13]

3    13
dtype: int64

当您调用idxmax时,它返回索引中与最大值对应的键。您需要将该键传递给dataframe以获取该值。

max_key = cd_gross_revenue.idxmax()
max_value = cd_gross_revenue.loc[max_key]

相关问题 更多 >

    热门问题