Home > Net >  Editing dataframe column values
Editing dataframe column values

Time:06-13

My values in the totalGross column of the dataframe are as follows. I need to fix the values with ['x'] expression because I need to find the equations.

df['totalNet'] = df['totalNet'].map(str)   

didn't work for me. Thanks.

input:

'totalNet': ["['385.88']",'385.88',"['188.93']",'188.93',"['342.66']",'342.66',"['178.52']",'178.52',"['1947.60']",'1947.60']

Output :

0           385.88
1           385.88
2           188.93
3           188.93
4           342.66

183         422.42
184         200.00
185         200.00
186        2461.77
187        2461.77

CodePudding user response:

IIUC, you can use:

df['totalNet'] = pd.to_numeric(df['totalNet'].str.strip("'[]"), errors='coerce')

output:

0     385.88
1     385.88
2     188.93
3     188.93
4     342.66
5     342.66
6     178.52
7     178.52
8    1947.60
9    1947.60
Name: totalNet, dtype: float64

CodePudding user response:

You can use ast.literal_eval to convert str of list into list. In your case:

import ast
df['totalNet'] = ["['385.88']",'385.88',"['188.93']",'188.93', "['342.66']",'342.66',"['178.52']",'178.52',"['1947.60']",'1947.60']
df['totalNet'] = df['totalNet'].apply(lambda x: x if not x.startswith("[") else ast.literal_eval(x)[0])
df

Output

totalNet
0   385.88
1   385.88
2   188.93
3   188.93
4   342.66
5   342.66
6   178.52
7   178.52
8   1947.60
9   1947.60
  • Related