Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 切片数据帧以显示特定日期的所有记录_Python_Python 3.x_Pandas - Fatal编程技术网

Python 切片数据帧以显示特定日期的所有记录

Python 切片数据帧以显示特定日期的所有记录,python,python-3.x,pandas,Python,Python 3.x,Pandas,我想返回一个数据帧,它只包含给定日期时间值的特定日期的记录 以下代码正在运行: def dataframeByDay(datetimeValue): cYear = datetimeValue.year cMonth = datetimeValue.month cDay = datetimeValue.day crit = (df.index.year == cYear) & (df.index.month == cMonth) & (df.ind

我想返回一个数据帧,它只包含给定日期时间值的特定日期的记录

以下代码正在运行:

def dataframeByDay(datetimeValue):
    cYear = datetimeValue.year
    cMonth = datetimeValue.month
    cDay = datetimeValue.day
    crit = (df.index.year == cYear) & (df.index.month == cMonth) & (df.index.day == cDay)
    return df.loc[crit]

有没有更好(更快)的方法来实现这一点?

因为索引是一个
DatetimeIndex
您可以使用字符串对其进行切片

考虑数据帧
df

np.random.seed([3,1415])
df = pd.DataFrame(np.random.randint(10, size=(10, 3)),
                  pd.date_range('2016-03-31', periods=10, freq='12H'),
                  list('ABC'))

df

                     A  B  C
2016-03-31 00:00:00  0  2  7
2016-03-31 12:00:00  3  8  7
2016-04-01 00:00:00  0  6  8
2016-04-01 12:00:00  6  0  2
2016-04-02 00:00:00  0  4  9
2016-04-02 12:00:00  7  3  2
2016-04-03 00:00:00  4  3  3
2016-04-03 12:00:00  6  7  7
2016-04-04 00:00:00  4  5  3
2016-04-04 12:00:00  7  5  9
不是你想要的
您不想使用
时间戳

df.loc[pd.to_datetime('2016-04-01')]

A    0
B    6
C    8
Name: 2016-04-01 00:00:00, dtype: int64
相反
您可以使用以下技术:

df.loc['{:%Y-%m-%d}'.format(pd.to_datetime('2016-04-01'))]

                     A  B  C
2016-04-01 00:00:00  7  3  1
2016-04-01 12:00:00  0  6  6
您的职能

def dataframeByDay(datetimeValue):
    return df.loc['{:%Y-%m-%d}'.format(datetimeValue)]

dataframeByDay(pd.to_datetime('2016-04-01'))

                     A  B  C
2016-04-01 00:00:00  7  3  1
2016-04-01 12:00:00  0  6  6

这里有一些替代方法

def dataframeByDay2(datetimeValue):
    dtype = 'datetime64[D]'
    d = np.array('{:%Y-%m-%d}'.format(datetimeValue), dtype)
    return df[df.index.values.astype(dtype) == d]

def dataframeByDay3(datetimeValue):
    return df[df.index.floor('D') == datetimeValue.floor('D')]

首先,非常感谢你的回答。我从互联网上得到的所有支持中得到了幸福。我只是想告诉你,我的代码比你在这里更新的代码(约8秒)运行得快得多(约2秒),并检查你是否有关于如何实现它的其他建议。我用一些替代方法更新了我的帖子。然而,我用10000行长的数据帧测试了代码,我的方法快了一个数量级。如果你看到的是你所声称的结果,那么你所运行的东西一定有某种独特的东西使它如此。