Pandas - CSV file , how to take Month date from list of int32 column

Viewed 102

Hey Guys im trying to create a new col , from a dates col which like : "1/20/21 , 5/30/21 .. 11/5/21" , so i have 2 options here: 1 char , or 2 char till get "/" char.

all_data['Month'] = all_data['Order Date'].str[0:1]
all_data['Month'] = all_data['Month'].astype('int32')
all_data.head()

This option is takes only 1-9 months .. without 10,11,12 . i tried to make :

index = all_data['Order Date'].find('\') # return the index of "/"
all_data['Month'] = all_data['Order Date'].str[0:index]

But its also not working... got error of type value. how can i make it works ?

1 Answers

I think here is simplier convert values to datetimes and then use Series.dt.month:

all_data['Month'] = pd.to_datetime(all_data['Order Date']).dt.month

Or split by / and get first value:

all_data['Month'] = all_data['Order Date'].str.split('/').str[0].astype(int)

Or get numeric before start of string and first / in Series.str.extract:

all_data['Month'] = all_data['Order Date'].str.extract('^(\d+)/').astype(int)
Related