如何通过datetime列中的单个日期来子集pandas数据框架列?

问题描述 投票:0回答:1

所以我想这应该是一个比较简单的任务,但是我找不到。我有一个pandas数据框,如下所示。

Company Id      DateTime               col1  col2       col3    col4   col5     col6
0   25502921    2018-08-16 10:23:36     0   175.000     0.0     0.0     0.0     0
1   25502921    2018-08-16 10:33:55     0   155.557     0.0     0.0     0.0     0
2   25502921    2018-08-16 10:43:55     0   153.615     0.0     0.0     0.0     0

type(df['DateTime'][0]) 产出 pandas._libs.tslibs.timestamps.Timestamp

我怎样才能根据日期对数据框进行子集?

df_tmp = df[df['DateTime'].dt.date=='16-08-2018'] 似乎没有工作,也没有 df_tmp = df[df['DateTime']=='16-08-2018']

还有哪些直观的方法我可以尝试?

python-3.x pandas datetime timestamp subset
1个回答
1
投票

使用 .dt.normalize() 它将时间转换为 00:00:00 但返回一个日期时间对象。

df['DateTime'].dt.normalize().apply(type)
pandas._libs.tslibs.timestamps.Timestamp

print(df['DateTime'].dt.normalize())

0   2018-08-16
1   2018-08-16
2   2018-08-16
Name: DateTime, dtype: datetime64[ns]

df[df['DateTime'].dt.normalize() == '2018-08-16']

   Company_Id            DateTime  col1     col2  col3  col4  col5  col6
0    25502921 2018-08-16 10:23:36     0  175.000   0.0   0.0   0.0     0
1    25502921 2018-08-16 10:33:55     0  155.557   0.0   0.0   0.0     0
2    25502921 2018-08-16 10:43:55     0  153.615   0.0   0.0   0.0     0

1
投票

我相信当你把DateTime设置为索引时,你会得到更好的性能和更容易处理。

df = pd.read_clipboard(sep = '\s{2,}',parse_dates=['DateTime'])
df.set_index("DateTime").loc["2018-08-16"]
© www.soinside.com 2019 - 2024. All rights reserved.