Hi I have a dateframe of this type:
year month day Date
0 2015 5 20 2015-05-20
1 2016 6 21 2016-06-21
2 2017 7 22 2017-07-22
3 2018 8 23 2018-08-23
4 2019 9 24 2019-09-24
I have created the columns "year" "month" and "day" in this way:
df["day"] = pd.to_datetime(df["Date"]).dt.day
df["month"] = pd.to_datetime(df["Date"]).dt.month
df["year"] = pd.to_datetime(df["Date"]).dt.year
Now I want to create a 5th column with month and day together and turn them into a string
I have tried:
df["daymonth"] = str(df["day"]) " " str(df["month"])
but it seems that I obtain a matrix, have you any suggestions?
CodePudding user response:
If one (or both) of the columns are not string typed, you should convert it (them) first:
df["daymonth"] = df["day"].astype(str) " " df["month"].astype(str)
CodePudding user response:
You can just do dt.strftime
df['d-m'] = df.Date.dt.strftime('%d %m')
To fix your code
df["day"].astype(str) " " df["month"].astype(str)
CodePudding user response:
Also you cat use something like this:
df['d-m'] = df['Date'].apply(lambda x: str(x.day) ' ' str(x.month))
