简体   繁体   English

日期时间格式,但我只想要列中的月份/年份

[英]datetime format but i only want the month / year in the columns

I am performing some data cleaning to my dataframe and there are two columns labelled Tranc_Year and Tranc_Month.我正在对我的 dataframe 执行一些数据清理,并且有两列标记为 Tranc_Year 和 Tranc_Month。

The two columns are originally of int64 datatype and I want to convert them to datetime.这两列最初是 int64 数据类型,我想将它们转换为 datetime。 两列显示

However, after converting it to datetime with the following code:但是,使用以下代码将其转换为日期时间后:

df_train.loc[:,'Tranc_Year'] = pd.to_datetime(df_train['Tranc_Year'], format='%Y') df_train.loc[:,'Tranc_Month'] = pd.to_datetime(df_train['Tranc_Month'], format='%m') df_train.loc[:,'Tranc_Year'] = pd.to_datetime(df_train['Tranc_Year'], format='%Y') df_train.loc[:,'Tranc_Month'] = pd.to_datetime(df_train['Tranc_Month'] , 格式='%m')

The display becomes as follows:显示变成如下: 新专栏

How do i convert to date time while maintaining the original display?如何在保持原始显示的同时转换为日期时间?

Use to_datetime with columns year, month, day by rename by dictionary:通过按字典rename ,将to_datetimeyear, month, day列一起使用:

d = {'Tranc_Year':'year','Tranc_Month':'month'}

df1 = df_train[['Tranc_Year', 'Tranc_Month']].rename(columns=f).assign(day=1)
df_train['date'] = pd.to_datetime(df1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在pyspark数据帧中将多列即时间、年、月和日期转换为日期时间格式 - How to convert multiple columns i.e time ,year,month and date into datetime format in pyspark dataframe 熊猫:日期为年,月......分隔列到日期时间 - Pandas : date as year, month … in separated columns to datetime groupby datetime 仅限年月 - groupby datetime year-month only Pandas - 使用仅包含月份和年份的日期时间列进行计算 - Pandas - Calculate with datetime column with month and year only 仅在 Pandas 中将日期时间转换为月份和年份 - Convert datetime to month and year only in Pandas 如何将只有日期和月份列的 dataframe 解析为具有 pd.datetime 格式的新列? - How can I parse a dataframe which has only date and month columns to new column with pd.datetime format? 如何比较 python 中的日期? 我有月份日期年份格式并想与当前日期(7 天内)进行比较 - How to compare date in python? I have a month date year format and want to compare to the current date (within 7 days) 将 Month&Year 列转换为日期时间格式 python - Convert Month&Year column into datetime format python 将日期(月、日、年、时间)转换为 python 中的日期时间格式 - Convert date (month, day, year, time) to Datetime format in python Python 将提取的年月设置为日期时间格式 - Python setting the extracted Year-month in the Datetime format
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM