在DataFrame索引中查找标签位置

时间:2013-06-21 20:46:41

标签: python pandas

我有一个pandas数据帧:

import pandas as pnd
d = pnd.Timestamp('2013-01-01 16:00')
dates = pnd.bdate_range(start=d, end = d+pnd.DateOffset(days=10), normalize = False)

df = pnd.DataFrame(index=dates, columns=['a'])
df['a'] = 6

print(df)
                     a
2013-01-01 16:00:00  6
2013-01-02 16:00:00  6
2013-01-03 16:00:00  6
2013-01-04 16:00:00  6
2013-01-07 16:00:00  6
2013-01-08 16:00:00  6
2013-01-09 16:00:00  6
2013-01-10 16:00:00  6
2013-01-11 16:00:00  6

我有兴趣找到其中一个标签的标签位置,比如

ds = pnd.Timestamp('2013-01-02 16:00')

查看索引值,我知道这是此标签的整数位置1.如何让pandas告诉该标签的整数值是什么?

3 个答案:

答案 0 :(得分:32)

您正在寻找索引方法get_loc

In [11]: df.index.get_loc(ds)
Out[11]: 1

答案 1 :(得分:2)

在给定日期键的情况下获取数据帧整数索引:

>>> import pandas as pd

>>> df = pd.DataFrame(
    index=pd.date_range(pd.datetime(2008,1,1), pd.datetime(2008,1,5)),
    columns=("foo", "bar"))

>>> df["foo"] = [10,20,40,15,10]

>>> df["bar"] = [100,200,40,-50,-38]

>>> df
            foo  bar
2008-01-01   10  100
2008-01-02   20  200
2008-01-03   40   40
2008-01-04   15  -50
2008-01-05   10  -38

>>> df.index.get_loc(df["bar"].argmax())
1

>>> df.index.get_loc(df["foo"].argmax())
2

在栏栏中,最大值的索引为1

在列foo中,最大值的索引是2

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html

答案 2 :(得分:0)

get_loc 可以根据以下条件用于

import pandas as pnd
d = pnd.Timestamp('2013-01-01 16:00')
dates = pnd.bdate_range(start=d, end = d+pnd.DateOffset(days=10), normalize = False)

df = pnd.DataFrame(index=dates)
df['a'] = 5
df['b'] = 6
print(df.head())    
                     a  b
2013-01-01 16:00:00  5  6
2013-01-02 16:00:00  5  6
2013-01-03 16:00:00  5  6
2013-01-04 16:00:00  5  6
2013-01-07 16:00:00  5  6

#for rows
print(df.index.get_loc('2013-01-01 16:00:00'))  
 0
#for columns
print(df.columns.get_loc('b'))
 1