Convert a pandas column with lists of floats to a column with lists of ints

Viewed 304

I have the following pandas dataframe with distance column as a lists of floats.

   event  type    distance
0  5      open    [59235.1953125, 34893.48046875, 35969.94921875]
1  3      open    [67613.8828125, 49029.328125, 85592.8828125]
2  2      close   [2827.9968261719, 1665.8785400391, 1717.271240]

How can I convert the distance column to have lists of ints?

   event  type    distance
0  5      open    [59235, 34893, 359670]
1  3      open    [67614, 49029, 85593]
2  2      close   [2828, 1666, 1717]
3 Answers

Just a loop/apply:

df['distance'] = [[round(y) for y in x] for x in df['distance']]

Use pandas apply -

df['distances'] = df['distances'].apply(lambda x: [round(y) for y in x])

There is another way to do it. Note that solutions using list comprehension are (often) considered to be better practice.

Create a function:

def make_integer(dat):
    return(list(map(int, dat)))

The created function is used in another map function:

df['distance2'] = list(map(make_integer, df['distance']))
Related