lunbox
lunbox

Reputation: 363

convert dataframe column into int so can sort and do calulations on the column values

I have a dataframe row as such like below

a     |  b                 | c     |  d
1     |-700.5;-1000.0;200.0|  yes  | blue

I want to change column b to be numeric so I can do data work like sorting on it but when I try the below code

df= pd.to_numeric(df["b"])
print(df)

Get error ValueError: Unable to parse string or issue with "-".

Upvotes: 0

Views: 214

Answers (2)

Naveed
Naveed

Reputation: 11650

if you need that in the same column?

here is one way to do it

# split, and sort then join back

df['b'].str.split(';').apply(lambda x:  sorted([(float(i)) for i in x], reverse=True)) 
df['b']=df['b'].str.split(';').apply(lambda x:  sorted([(float(i)) for i in x], reverse=True)) 
df
    a   b                           c       d
0   1   [200.0, -700.5, -1000.0]    yes     blue

Upvotes: 1

PaulS
PaulS

Reputation: 25353

Maybe you are looking for something like this:

df.assign(b = df.b.str.split(';')).explode('b')

Output:

   a        b    c     d
0  1   -700.5  yes  blue
0  1  -1000.0  yes  blue
0  1    200.0  yes  blue

Upvotes: 1

Related Questions