slickspidey
slickspidey

Reputation: 69

How to convert a column in a dataframe from decimals to percentages with python

I've tried for so long but no matter what I do I can't convert this column from decimal to percentage. Here's my data frame

                          Groups and Classes  Booked  Arrived  No Show (n)  No Show (%)
6            Supervised Exercise Program     121       57           64        5e-01
0                      Active Living 101       4        2            2        5e-01
2      Eating Well the Mediterranean Way      38       24           14        4e-01
5                                   MBCT     101       66           35        3e-01
4                  Healthy Meal Planning      33       22           11        3e-01
3                                  Grief      56       46           10        2e-01
1                         Craving Change     115       95           20        2e-01
Total                                NaN     468      312          156        3e-01

I want to convert my "No Show (%)" column so it outputs percentages like so:

                          Groups and Classes  Booked  Arrived  No Show (n)  No Show (%)
6            Supervised Exercise Program     121       57           64        53%
0                      Active Living 101       4        2            2        50%
2      Eating Well the Mediterranean Way      38       24           14        37%
5                                   MBCT     101       66           35        35%
4                  Healthy Meal Planning      33       22           11        33%
3                                  Grief      56       46           10        18%
1                         Craving Change     115       95           20        17%
Total                                NaN     468      312          156        33%

I've tried the following and it runs but it won't convert my column to a percentage:

mergedgc = mergedgc.sort_values('No Show (%)', ascending=False)
mergedgc.loc['Total'] = mergedgc.sum(numeric_only=True)
pd.set_option('precision', 0)
mergedgc['No Show (%)'] = round((mergedgc['No Show (n)'] / mergedgc['Booked']),2)
mergedgc.style.format({"No Show (%)": "{:.2%}"})

Can someone please show and tell me what I'm doing wrong? I didn't think it'd be this much headache to convert a column to percentages.

Upvotes: 0

Views: 5232

Answers (4)

Utsav
Utsav

Reputation: 5918

Toy example:

df=DataFrame({
    'No Show (%)':[5e-01, 4e-01]
})
df

Input

No Show (%)
0   0.5
1   0.4

Code

mergedgc.style.format({"No Show (%)": "{:.2%}"})

can be replaced by

df['No Show (%)'] = df['No Show (%)'].transform(lambda x: '{:,.2%}'.format(x))

Output

No Show (%)
0   50.00%
1   40.00%

Edit

Plot

df['No Show (%)'].replace('\%','', regex=True).astype(float).plot()

enter image description here

Upvotes: 2

Laurent
Laurent

Reputation: 13458

You could try this:

df["No Show (%)"] = pd.Series(
    [f"{value}%" for value in round(df["No show (%)"] * 100, 0)]
)

print(df["No show"])
#Outputs
       No Show (%)
6      53.0%
0      50.0%
2      37.0%

Upvotes: 0

SeaBean
SeaBean

Reputation: 23217

You can use .map() together with lambda function outputting f-string for formatting, as follows:

df['No Show (%)'] = df['No Show (%)'].map(lambda x: f'{x:,.0%}', na_action='ignore')

Parameter na_action='ignore' is used to avoid conversion of NaN values (if any).

Demo

df['No Show (%)'] = df['No Show (n)'] / df['Booked']
df['No Show (%)'] = df['No Show (%)'].map(lambda x: f'{x:,.0%}', na_action='ignore')



print(df)


                      Groups and Classes  Booked  Arrived  No Show (n) No Show (%)
6            Supervised Exercise Program     121       57           64         53%
0                      Active Living 101       4        2            2         50%
2      Eating Well the Mediterranean Way      38       24           14         37%
5                                   MBCT     101       66           35         35%
4                  Healthy Meal Planning      33       22           11         33%
3                                  Grief      56       46           10         18%
1                         Craving Change     115       95           20         17%
Total                                NaN     468      312          156         33%

If you want to have 2 decimal points for the percentage (as seen from your tried code which is different from your sample expected output), you can change the f-string to: f'{x:,.2%}'

Upvotes: 0

Fahad Vadakkumpadatah
Fahad Vadakkumpadatah

Reputation: 71

Try this :

df["No_show_percentage"] = ((df["NoShow"]/df["Booked"])*100).round(2)
df```

Result:

    Booked  NoShow  No_show_percentage
0   121 64  52.89
1   4   2   50.00

Upvotes: 0

Related Questions