Python-遍历数据框行以从日期时间戳记中删除时间[重复]

问题描述 投票:2回答:2

此问题已经在这里有了答案:

我有一个数据框,其中的一列包含一个日期时间戳记(dtype:datetime64 [ns]):

         Date          Docs
0 2016-06-01 04:48:23  45
1 2016-06-01 07:24:38  56
2 2016-07-01 08:27:26  87
3 2016-07-01 08:27:49  44

我想遍历每一行以删除Date的时间部分,以得到这样的最终结果:

     Date     Docs
0 2016-06-01  45
1 2016-06-01  56
2 2016-07-01  87
3 2016-07-01  44

我将如何去做?

python pandas dataframe datetime
2个回答
0
投票

使用dt.floor

df['Date'].dt.floor('D')

df['Date'].dt.normalize()

0   2016-06-01
1   2016-06-01
2   2016-07-01
3   2016-07-01
Name: Date, dtype: datetime64[ns]

注意:dt.floor返回日期时间dtype[dt.date返回字符串dtype的位置


1
投票

您需要使用dt.date

df['Date'] = df['Date'].dt.date

示例:

import pandas as pd
import numpy as np
rng = pd.date_range('2019-01-01 01:01:00', periods=365, freq='D')
df = pd.DataFrame(rng)
print(df[0])

看起来像:

0     2019-01-01 01:01:00
1     2019-01-02 01:01:00
2     2019-01-03 01:01:00

应用dt.date之后:

df[0] = df[0].dt.date
print(df[0])

看起来像:

0      2019-01-01
1      2019-01-02
2      2019-01-03
© www.soinside.com 2019 - 2024. All rights reserved.