21

我有一个熊猫数据框:

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 知道这个标签的整数值是多少?

4

3 回答 3

46

您正在寻找索引方法get_loc

In [11]: df.index.get_loc(ds)
Out[11]: 1
于 2013-06-21T20:49:15.180 回答
3

给定日期键获取数据帧整数索引:

>>> 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

于 2016-12-09T22:54:43.570 回答
1

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
于 2018-10-08T09:22:07.733 回答