Home > Software engineering >  In pandas, how to convert the result of dividing two columns from a decimal to a percentage?
In pandas, how to convert the result of dividing two columns from a decimal to a percentage?

Time:12-15

When using pandas, how do I convert a decimal to a percentage when the result obtained by dividing two columns as another column?

for example :

df_income_structure['C'] = (df_income_structure['A']/df_income_structure['B'])

If the value of df_income_structure['C'] is a decimal, how to convert it to a percentage ?

CodePudding user response:

Format it like this:

df_income_structure.style.format({'C': '{:,.2%}'.format})

Change the number depending on how many decimal places you'd like.

CodePudding user response:

Use basic pandas operators For example if we have a dataframe with columns name like column1, column2,column3 , ... so we can :

Columns = [column1, column2,column3, ....] .

df[Columns] = df[Columns].div(df[Columns].sum(axis=1), axis=0).multiply(100)
  1. (df[Columns].sum(axis=1). axis=1 makes the summation for rows.
  2. Divide the dataframe by (df[Columns].div(df[Columns].sum(axis=1), axis=0). axis=0 is for devision of columns.
  3. multiply the results by 100 for percentages of 100.

I hope this answer has solved your problem.

Good luck

  • Related