Python 查找数据帧值的索引
我正在尝试使用pandas处理一些.csv数据,我确信这是一个新手的举动,但在花了很多时间尝试实现这一点后,我需要您的帮助 本质上,我试图在我创建的数据帧中找到一个值的索引Python 查找数据帧值的索引,python,python-2.7,pandas,Python,Python 2.7,Pandas,我正在尝试使用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 maxi
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()获取答案,但是如果我不是在寻找max值的索引,该怎么办?如果我看到的是某个随机值的索引,我会怎么做呢?显然,索引在这里对我不起作用
提前感谢您的帮助 使用
布尔掩码
获取值等于随机变量的行。
然后使用该掩码对数据帧或序列进行索引。
然后使用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')
调用idxmax时,它返回索引中与max值对应的键。您需要将该键传递给数据帧以获得该值
max_key = cd_gross_revenue.idxmax()
max_value = cd_gross_revenue.loc[max_key]
s[s==13]
例如
此数据帧是否只有一列,或者您知道哪一列具有最大值?如果您知道该列,那么
df.loc[df.col==max].index
将返回indexHi EdChum,谢谢您的回答。这样做会导致以下错误Traceback(最近一次调用最后一次):文件“psims2.py”,第81行,在打印cd_gross_revenue.loc[cd_gross_revenue.col==max]中。索引文件“C:\Python27\lib\site packages\pands-0.14.1-py2.7-win32.egg\pandas\core\generic.py”,第18 43行,在u getattr_u(type(type(self)中))AttributeError:“Series”对象没有属性“col”
我想你误解了,col
是你感兴趣的列的通用名称,所以用df中的列名替换列名,我的问题是这个df有多少列,只有1列,或者你知道哪一列有最大值,如果是,则使用该名称的子项col
from pandas import Series
s = Series(range(10,20))
s[s==13]
3 13
dtype: int64