![](/img/trans.png)
[英]Python Pandas dataframe: For each month of the year, add the date with last day in the month to an index if month not present, or remove duplicates
[英]Create Dates without days present in month & year columns pandas dataframe
{year = pd.to_datetime(df1.Year, format='%Y').dt.year
df1['Month'] = pd.to_datetime(df1.Month, format='%b').dt.month}
cal = calendar.Calendar()
for i in cal.itermonthdays3(year=year, month=month):
print(i)
/// Error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
{2nd way}`
def date_iter(year, month):
for i in range(1, calendar.monthrange(year, month) + 1):
yield date(year, month, i)
for d in date_iter(year, month):
print(d)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
如何根据月份和年份列创建日期列?
尝试:
df["Month_Year"] = pd.to_datetime(df["Month"] + "-" + df["Year"].astype(str))
print(df)
印刷:
Month Year Month_Year
0 Jan 2020 2020-01-01
1 Feb 2021 2021-02-01
2 Mar 2022 2022-03-01
3 Apr 2020 2020-04-01
4 May 2021 2021-05-01
5 Jun 2022 2022-06-01
6 Jul 2020 2020-07-01
7 Aug 2021 2021-08-01
8 Sep 2022 2022-09-01
9 Oct 2020 2020-10-01
10 Nov 2021 2021-11-01
11 Dec 2022 2022-12-01
输入 dataframe:
Month Year
0 Jan 2020
1 Feb 2021
2 Mar 2022
3 Apr 2020
4 May 2021
5 Jun 2022
6 Jul 2020
7 Aug 2021
8 Sep 2022
9 Oct 2020
10 Nov 2021
11 Dec 2022
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.