简体   繁体   中英

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

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM