寻找 pandas DataFrame 值的索引

9
我正在使用pandas处理一些.csv数据,我遇到了一些麻烦。我想找到已创建的dataframe中一个值的索引,但我不确定自己做的对不对。在花费了很多时间尝试让它工作之后,现在需要你的帮助。
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在这里不能正常工作。

提前感谢您的任何帮助!


1
这个数据框只有一个列吗?或者你知道哪一列具有最大值?如果你知道那一列,那么 df.loc[df.col == max].index 将会返回该列的索引。 - EdChum
嗨,EdChum,感谢您的回答。这样做会给我带来以下错误 “Traceback(最近的调用最先): File“psims2.py”,第81行,在<module>中 print cd_gross_revenue.loc [cd_gross_revenue.col == max] .index File“C:\ Python27 \ lib \ site-packages \ pandas-0.14.1-py2.7-win32.egg \ pandas \ core \ generic.py”,第18 43,__getattr__, (type(self).__name__,name)) AttributeError:“Series”对象没有属性“col”` - ploo
我认为你误解了,“col”是你感兴趣的列的通用名称,因此请使用你的数据框中的列名替换它。我的问题是这个数据框有多少列?只有一个吗?或者你知道哪一列具有最大值?如果是这样,请用那个列名替换“col”。 - EdChum
3个回答

4

使用布尔掩码以获取值等于随机变量的行,然后使用该掩码索引数据帧或系列。然后,您将使用 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')

4

s[s==13]

Eg,

from pandas import Series

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

3    13
dtype: int64

1
当您调用 idxmax 时,它会返回与最大值对应的索引键。您需要将该键传递给数据框以获取该值。
max_key = cd_gross_revenue.idxmax()
max_value = cd_gross_revenue.loc[max_key]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接