JSowa
JSowa

Reputation: 10572

Date concatenating in new column in dataframe

I have dataframe with column date with type datetime64[ns].

When I try to create new column day with format MM-DD based on date column only first method works from below. Why second method doesn't work in pandas?

df['day'] = df['date'].dt.strftime('%m-%d')
df['day2'] = str(df['date'].dt.month) + '-' + str(df['date'].dt.day)

Result for one row:

day                                                  01-04
day2     0       1\n1       1\n2       1\n3       1\n4 ...

Types of columns

day              object
day2             object

Upvotes: 1

Views: 22

Answers (1)

jezrael
jezrael

Reputation: 862441

Problem of solution is if use str with df['date'].dt.month it return Series, correct way is use Series.astype:

df['day2'] = df['date'].dt.month.astype(str) + '-' + df['date'].dt.day.astype(str)

Upvotes: 2

Related Questions