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

Time:10-29

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 "-".

CodePudding user response:

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

CodePudding user response:

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
  • Related