python - Replace non-zero values in a pandas dataframe with 1 -
i have pandas dataframe 'result'. 1 of attribute in data frame 'transaction' contain value 0 if it's non cash transaction , real number if transaction cash transaction.this attribute like:
result['transaction'] = [0,0,0,23.2,432,12,0,0,56.4] i want change value of attribute such non-zero values replaced 1. resultant attribute should this:
result['transaction'] = [0,0,0,1,1,1,0,0,1] how can this?
original dataframe:
in [701]: df out[701]: col1 0 0.0 1 0.0 2 0.0 3 23.2 4 432.0 5 12.0 6 0.0 7 0.0 8 56.4 you can use df.where filter , assign:
in [696]: df.col1 = df.where(df.col1 == 0, 1) in [697]: df out[697]: col1 0 0.0 1 0.0 2 0.0 3 1.0 4 1.0 5 1.0 6 0.0 7 0.0 8 1.0 you can use boolean indexing simpler predicate:
in [676]: df[df.col1 != 0] = 1 in [677]: df out[677]: col1 0 0.0 1 0.0 2 0.0 3 1.0 4 1.0 5 1.0 6 0.0 7 0.0 8 1.0 you may use df.map:
in [685]: df[df.col1.map(lambda x: x != 0)] = 1 in [686]: df out[686]: col1 0 0.0 1 0.0 2 0.0 3 1.0 4 1.0 5 1.0 6 0.0 7 0.0 8 1.0 note that, every method, can tack on .astype(int) if want rid of floating point part of output.
Comments
Post a Comment