YangDongJae
YangDongJae

Reputation: 105

how convert Object to int only digit in python dataframe?

this is my datafarame with pandas

2020-02-05
2020-03-02

I wanna convert to int for plot to bar histogram chart. So i use regular expression to get only digit. after that i will try to convert int. but my regular expression function get error.

below function is to get digit in string

import re

def split_it(data):
    return re.findall('(\d+)',data)[0]

and this is my error

expected string or bytes-like object

so i try again with another source code.


import re

def split_it(data):
    return re.findall('(\d+)',str(data))

and result it's below.

[2020, 02, 05]

[2020, 03, 02]

[2020, 02, 19]

would you tell me how can i get 20200205 as type int?

and why second function is return list type?

Upvotes: 2

Views: 144

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 114038

that doesnt look like a dataframe and you dont show us how you call it but here is how i would do it

series = pandas.to_datetime(['2020-02-05','2020-03-02'])
#this is actually a datetimeindex, that does not use .dt accessor
new_series = series.strftime("%Y%m%d").astype(int)

if it is a dataframe you would do it slightly different

#assumes a column named datetime exists, use its .dt accessor
int_series = df['datetime'].dt.strftime("%Y%m%d").astype(int)  

Upvotes: 3

BENY
BENY

Reputation: 323326

Try with replace

data['col'].str.replace('-','').astype(int)

Upvotes: 2

Related Questions