将对象转换为没有时间的日期时间

我有如下所示的数据框:


         Date      Region     Data

   0   200201        A        8.8

   1   200201        B        14.3

                    ...     

1545   202005        C        7.3

1546   202005        D        131

我想在没有时间的情况下将 Date 列(数据类型:对象)转换为 DateTime 索引。yyyymm 或 yyyymmdd 或 yyyy-mm-dd 所有这些都无关紧要,只要我可以删除时间部分。


我搜索了 stackoverflow 并尝试了这些代码


# (1) 

df["Date"] = pd.to_datetime(df["Date"], format = "%Y%m", errors = "coerce", uts = False)

# (2)

df["Date"] = pd.to_datetime(df["Date"], format = "%Y%m")

df["Date"] = df["Date"].dt.normalize()

# (3)

df["Date"] = pd.to_datetime(df["Date"], format = "%Y%m")

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

对于 (1) 和 (2),我得到 ["Date"],时间为 yyyy-mm-dd 00:00:00。


对于 (3),我确实得到 ["Date"] 作为 yyyymm 但 dtype 是对象。


我不能使用日期范围,因为同一日期会重复一段时间。


有什么方法可以在 python 中将 yyyymm[object] 转换为 yyyymmdd[datetime] 吗?


提前致谢。


翻过高山走不出你
浏览 131回答 2
2回答

茅侃侃

这可能是关于您的 DataFrame 在编辑器中的显示方式的显示配置问题。以正确格式获取数据的最简单方法是:df['Date'] = pd.to_datetime(df['Date'], format = '%Y%m')以下是repl.it使用您的 DataFrame 和此代码的结果。日期格式正确,没有时间部分,并且具有正确的 dtype。&nbsp; &nbsp; &nbsp; &nbsp; Date Region&nbsp; Data0 2002-01-01&nbsp; &nbsp; &nbsp; A&nbsp; &nbsp;8.8<class 'pandas.core.frame.DataFrame'>RangeIndex: 1 entries, 0 to 0Data columns (total 3 columns):&nbsp;#&nbsp; &nbsp;Column&nbsp; Non-Null Count&nbsp; Dtype&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;---&nbsp; ------&nbsp; --------------&nbsp; -----&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;0&nbsp; &nbsp;Date&nbsp; &nbsp; 1 non-null&nbsp; &nbsp; &nbsp; datetime64[ns]&nbsp;1&nbsp; &nbsp;Region&nbsp; 1 non-null&nbsp; &nbsp; &nbsp; object&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;2&nbsp; &nbsp;Data&nbsp; &nbsp; 1 non-null&nbsp; &nbsp; &nbsp; float64&nbsp; &nbsp; &nbsp; &nbsp;dtypes: datetime64[ns](1), float64(1), object(1)memory usage: 152.0+ bytes您还可以尝试一种更复杂的方法,从日期时间到日期字符串再回到日期时间。df['Date'] = pd.to_datetime(df['Date'], format = '%Y%m').dt.datedf['Date'] = df['Date'].astype('datetime64[ns]')最终显示和 dtype 是相同的。&nbsp; &nbsp; &nbsp; &nbsp; Date Region&nbsp; Data0 2002-01-01&nbsp; &nbsp; &nbsp; A&nbsp; &nbsp;8.8<class 'pandas.core.frame.DataFrame'>RangeIndex: 1 entries, 0 to 0Data columns (total 3 columns):&nbsp;#&nbsp; &nbsp;Column&nbsp; Non-Null Count&nbsp; Dtype&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;---&nbsp; ------&nbsp; --------------&nbsp; -----&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;0&nbsp; &nbsp;Date&nbsp; &nbsp; 1 non-null&nbsp; &nbsp; &nbsp; datetime64[ns]&nbsp;1&nbsp; &nbsp;Region&nbsp; 1 non-null&nbsp; &nbsp; &nbsp; object&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;2&nbsp; &nbsp;Data&nbsp; &nbsp; 1 non-null&nbsp; &nbsp; &nbsp; float64&nbsp; &nbsp; &nbsp; &nbsp;dtypes: datetime64[ns](1), float64(1), object(1)memory usage: 152.0+ bytes

RISEBY

问题中的日期列的格式为 YYYYMM(但没有天数)。该函数pd.to_datetime()隐式地将日设置为 1。该函数pd.Period()将 YYYYMM 格式的日期转换为 pandas 句点。请注意,df['Date'] 可以是字符串或 6 位整数。df['Date'].apply(lambda x: pd.Period(x, freq='M'))0&nbsp; &nbsp; 2002-011&nbsp; &nbsp; 2002-012&nbsp; &nbsp; 2020-053&nbsp; &nbsp; 2020-05Name: Date, dtype: period[M]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python