Python 使用Numpy datetime64对象索引/切片数据帧

Python 使用Numpy datetime64对象索引/切片数据帧,python,pandas,numpy,datetime,indexing,Python,Pandas,Numpy,Datetime,Indexing,我希望能够弄清楚我是否能够使以下各项发挥作用(Pandas 0.23.4)。任何帮助都将不胜感激 import numpy as np import pandas as pd rows = 12 rng = pd.date_range('2011-01', periods=rows, freq='M') df = pd.DataFrame(np.arange(rows), index=rng) print(df.loc['2011-01']) print(df.loc[np.datetim

我希望能够弄清楚我是否能够使以下各项发挥作用(Pandas 0.23.4)。任何帮助都将不胜感激

import numpy as np
import pandas as pd

rows = 12
rng = pd.date_range('2011-01', periods=rows, freq='M')

df = pd.DataFrame(np.arange(rows), index=rng)

print(df.loc['2011-01'])
print(df.loc[np.datetime64('2011-01')])
第一个
print
实现了我所期望的:显示2011年1月的所有行。但是,第二个会抛出一个
KeyError
,因为该值不在索引中。我希望它能提供相同的输出,但经过一些测试后,我意识到它正在寻找一个完全匹配的2011-01-01,它不在数据帧中。我希望第二个可以使用,这样我就可以使用
numpy.arange
pandas.date\u range
轻松生成可以循环使用的日期数组。有人用这个吗? (似乎是这样,但前提是日期完全匹配。)

使用&

输出:

# loc: [0] == 2011-01-31 00:00:00
由于df索引包含月末日期,因此可以使用此技巧使用
df.loc
获取行:

>>>> df.loc[df.index == np.datetime64('2011-03', 'D') -1]
            0
2011-02-28  1

>>>> df.loc[df.index == np.datetime64('2011-04', 'D') -1]
            0
2011-03-31  2

>>>> df[df.index == np.datetime64('2011-12', 'D') -1]
             0
2011-11-30  10

# use 2012 January 1st minus one day to get 2011 Dec 31st
>>>> df[df.index == np.datetime64('2012-01', 'D') -1]
             0
2011-12-31  11

您可以编写一个函数,将
np.datetime64
转换为兼容的字符串:

def stringify(x):
    year = x.astype('datetime64[Y]').astype(int) + 1970
    month = x.astype('datetime64[M]').astype(int) % 12 + 1
    return f'{year}-{month:02}'

a = df.loc['2011-01']
b = df.loc[stringify(np.datetime64('2011-01'))]

assert a.equals(b)

谢谢@cryptonome。to_周期法很有趣;我得考虑一下。然而,如果可能的话,我希望有一种不添加另一个显式循环的方法来实现这一点。Numpy/Pandas中的隐式循环效率更高……因为您的索引总是在月底&您的
np.datetime64
year-month
格式,所以有一个技巧可以用于此。让我编辑我的答案。再次感谢,@cryptonome。不幸的是,您的新代码只适用于精确匹配。我希望能搜索整个月。谢谢你的帮助。没关系@Ryan,也许我误解了你的问题谢谢cryptonome和jpp的帮助。不幸的是,这个特定版本的Pandas的答案似乎是“不,你不能完全这样做。”我将jpp答案标记为正确,因为它不需要另一个循环。
def stringify(x):
    year = x.astype('datetime64[Y]').astype(int) + 1970
    month = x.astype('datetime64[M]').astype(int) % 12 + 1
    return f'{year}-{month:02}'

a = df.loc['2011-01']
b = df.loc[stringify(np.datetime64('2011-01'))]

assert a.equals(b)