python - 对 Pandas DataFrame 进行切片以显示特定日期的所有记录

标签 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.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')]

关于python - 对 Pandas DataFrame 进行切片以显示特定日期的所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47208431/

相关文章:

python - Pandas :从具有特定值的行下面的行开始读取Excel文件

Python 3.7 anaconda 环境-import _ssl DLL 加载失败错误

带有可变十进制数说明符的 Python f 字符串

python - 列表中 pandas 系列中的字符串

python - Pandas:包含元组的熔化列

python - 对于维度 1 的数组,轴 1 超出范围

python - 如何压缩整个文件夹(带有子文件夹)并通过 Flask 提供它而不将任何内容保存到磁盘

python-3.x - 如何在 pandas 数据框中用用户定义的值填充 NaN

python - Pandas:concat 函数删除了数据帧的先前排序

python - 使用 pandas DataFrame 在箱线图上绘制线条