在python中将月-年格式更改为年-月-日期格式
我有一个CSV文件作为输入,其中一列的日期格式为年-月。我需要将列格式更改为年-月-日期格式,这意味着月末日期。我正在使用Python3。此外,我还在聚合函数和group by函数中使用修改后的列 例如: 2020-01 2020-02 2020-03 2020-04 预期结果: 2020-01-31 2020-02-29(考虑闰年) 2020-03-31 2020-04-30 等等在python中将月-年格式更改为年-月-日期格式,python,Python,我有一个CSV文件作为输入,其中一列的日期格式为年-月。我需要将列格式更改为年-月-日期格式,这意味着月末日期。我正在使用Python3。此外,我还在聚合函数和group by函数中使用修改后的列 例如: 2020-01 2020-02 2020-03 2020-04 预期结果: 2020-01-31 2020-02-29(考虑闰年) 2020-03-31 2020-04-30 等等 from calendar import monthrange from datetime import dat
from calendar import monthrange
from datetime import date
def month_end(year, month):
return date(year=year, month=month, day=monthrange(year, month)[1]).isoformat()
到目前为止你尝试了什么?这是否回答了你的问题@苏珊特。。不,因为我使用的是CSV文件。。Am在aggregations函数和Group by函数中使用修改后的列。我面临一个问题。您的问题陈述不正确&没有提及任何有关聚合或groupby的内容。您可能需要使用适当的输入和预期的输出重新定义问题状态。虽然此代码可能会回答此问题,但如何以及为什么解决此问题将有助于提高答案的质量。记住,你也在为将来的读者回答这个问题,而不仅仅是现在的提问者。
>>> month_end(2020, 2)
'2020-02-29'
import pandas as pd
import datetime as dt
import calendar as cal
# making data frame from csv file
df = pd.read_csv("Table.csv")
# (month_year)->Column Name
df['month_last_dates'] = [datetime.datetime(date.year, date.month,
calendar.monthrange(date.year, date.month)[1]) for date in month_year]
# defining aggregation process for each column
aggregations={ 'Metric':sum }
# Group by and aggregate
print( df.groupby(['col1', 'month_last_dates','col2']).agg(aggregations) )