Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: convert string array to int array in dataframe

I have a data frame, duration is one of the attributes. The duration's content is like:

            array(['487', '346', ...,  '227', '17']). 

And the df.info(), I get: Data columns (total 22 columns):

             duration        2999 non-null object
             campaign        2999 non-null object
             ...

Now I want to convert duration into int. Is there any solution?

like image 836
zhelyu Avatar asked Dec 10 '25 19:12

zhelyu


2 Answers

Use astype:

df['duration'] = df['duration'].astype(int)

Timings

Using the following setup to produce a large sample dataset:

n = 10**5
data = list(map(str, np.random.randint(10**4, size=n)))
df = pd.DataFrame({'duration': data})

I get the following timings:

%timeit -n 100 df['duration'].astype(int)
100 loops, best of 3: 10.9 ms per loop

%timeit -n 100 df['duration'].apply(int)
100 loops, best of 3: 44.3 ms per loop

%timeit -n 100 df['duration'].apply(lambda x: int(x))
100 loops, best of 3: 60.1 ms per loop
like image 111
root Avatar answered Dec 12 '25 09:12

root


df['duration'] = df['duration'].astype(int)
like image 40
Dennis Golomazov Avatar answered Dec 12 '25 08:12

Dennis Golomazov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!