vendredi 14 mai 2021

How to convert letter symbols with their values in Python [duplicate]

I have multiple columns where the values are aggregated at billion or million, and would like to convert them all to numeric values of the same scale. Below is my unsuccessful attempt:

df = pd.DataFrame({'a' : ['1.2B', '300M', 'NaN'],
                'b' : ['NaN', '2.01B', '90000']})

def symbolToNum(x):
  x.astype('string')
  if x.str.strip().str[-1] = 'T' : return x.str[:-1].astype('float')*10^12
  elif x.str.strip().str[-1]  = 'B' : return x.str[:-1].astype('float')*10^9
  elif x.str.strip().str[-1] = 'M' : return x.str[:-1].astype('float')*10^6
  elif x.str.strip().str[-1] ='K' : return x.str[:-1].astype('float')*10^3
  else : return x.astype('float')

dollarcols =['a', 'b']
df[dollarcols] = df[dollarcols].apply(lambda x: symbolToNum(x))

Aucun commentaire:

Enregistrer un commentaire