Panda Python – dividing a column by 100 (then rounding by 2.dp)

Question:

I have been manipulating some data frames, but unfortunately I have two percentage columns, one in the format ‘61.72’ and the other ‘0.62’.

I want to just divide the column with the percentages in the ‘61.72’ format by 100 then round it to 2.dp so it is consistent with the data frame.

Is there an easy way of doing this?

My data frame has two columns, one called ‘A’ and the other ‘B’, I want to format ‘B’.

Many thanks!

Asked By: Nicholas

||

Answers:

You can use div with round:

df = pd.DataFrame({'A':[61.75, 10.25], 'B':[0.62, 0.45]})
print (df)
       A     B
0  61.75  0.62
1  10.25  0.45

df['A'] = df['A'].div(100).round(2)
#same as
#df['A'] = (df['A'] / 100).round(2)
print (df)
      A     B
0  0.62  0.62
1  0.10  0.45
Answered By: jezrael

This question have already got answered but here is another solution which is significantly faster and standard one.

df = pd.DataFrame({'x':[10, 3.50], 'y':[30.1, 50.8]})
print (df)
>>      x     y
    0  10.0  30.1
    1   3.5  50.8

df = df.loc[:].div(100).round(2)
print (df)
>>        x       y
   0    0.10    0.30
   1    0.03    0.50

why prefer this solution??

well, this warning is enough answer – "A value is trying to be set on a copy of a slice from a DataFrame if you use df[‘A’] so, Try using .loc[row_indexer,col_indexer] = value instead."

Moreover, check this for more understanding https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

Answered By: Mahendra
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.