从系列中删除分钟和小时

亚历山德罗·塞卡雷利(Alessandro Ceccarelli):

早上好,

我有以下数据框(年,月,日,小时,秒):

print(df)

     Date               Price
2018-01-02 09:42:00       2
2018-01-02 09:46:00       4
2018-01-02 10:22:00       6
...

我想得到,没有分钟和几秒钟:

print(final_df)

     Date               Price
2018-01-02                2
2018-01-02                4
2018-01-02                6
...

我试过了:

df['Date'] = datetime.datetime.strptime(df['Date'], '%Y-%m-%d').date()

但是它报告“ strptime()参数1必须是str,而不是Series”

耶斯雷尔:

如果不是datetime列,则需要to_datetime使用dt.date

print (df.dtypes)
Date     object
Price     int64
dtype: object

df['Date'] = pd.to_datetime(df['Date']).dt.date

print (df.dtypes)
Date     object
Price     int64
dtype: object

print (df['Date'].head().apply(type))
0    <class 'datetime.date'>
1    <class 'datetime.date'>
2    <class 'datetime.date'>
Name: Date, dtype: object

或者,如果需要不带hours,minutes和seconds的日期时间,请使用dt.floor

df['Date'] = pd.to_datetime(df['Date']).dt.floor('d')

print (df.dtypes)
Date     datetime64[ns]
Price             int64
dtype: object

print (df['Date'].head().apply(type))
0    <class 'pandas._libs.tslibs.timestamps.Timesta...
1    <class 'pandas._libs.tslibs.timestamps.Timesta...
2    <class 'pandas._libs.tslibs.timestamps.Timesta...
Name: Date, dtype: object

如果datetime列:

print (df.dtypes)
Date     datetime64[ns]
Price             int64
dtype: object


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

df['Date'] = df['Date'].dt.floor('d')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章