pandas data change based on condition

Viewed 57

I have data which has special characters, I want to change the conditional cell values.

Data is below first few lines df_orig:

idx A   B   C   D
0   0.5 2   5   #
1   3   5   8   %
2   6   8   10  $
3   9   10  15  $
4   11  15  18  #

I want to change cell values where $ in D, A = 0 and B = C

THE OUTPUT SHOULD BE change:

idx   A   B   C   D
0     0.5 2   5   #
1     3   5   8   %
2     0   10  10  $
3     0   15  15  $
4     11  15  18  #

I tried at my end with

change = df_orig.loc[(df.orig['D'] == '$'), df_orig['A'] == '0'& df_orig['B'] = df_orig['c']

but it didn't work.

2 Answers

Use DataFrame.copy if need new DataFrame and then set new values separately:

df = df_orig.copy()
m = df['D'].eq('$')
#alternative
#m = df['D'] == '$'

df.loc[m, 'A'] = 0
df.loc[m, 'B'] = df.C
print (df)
        A   B   C  D
idx                 
0     0.5   2   5  #
1     3.0   5   8  %
2     0.0  10  10  $
3     0.0  15  15  $
4    11.0  15  18  #

Also is possible together:

m = df['D'].eq('$')
df.loc[m, ['A','B']] = df.assign(E=0).loc[m, ['E','C']].values

You need two separate statements for changing A and B columns

# make a copy of df_orig
change = df_orig.copy()
# when D == "$", replace A by 0
change.loc[change['D'] == "$", "A"] = 0
# when D == "$", replace B by C
change.loc[change['D'] == "$", "B"] = change.loc[change['D'] == "$", "C"]
Related