2
import pandas as pd 
ind = pd.date_range('01/01/2000', periods = 4, freq ='W') 
df = pd.DataFrame({"A":[14, 4, 5, 4]},index = ind) 

df.pct_change()
                    A
2000-01-02        NaN
2000-01-09  -0.714286
2000-01-16   0.250000
2000-01-23  -0.200000

We get df's A column growth rate with pct_change function,if i expect the below result ,how to add % in pct_change's output quickly?

               A
2000-01-02   NaN
2000-01-09  -71%
2000-01-16   25%
2000-01-23  -20%
  • See https://stackoverflow.com/questions/20937538/how-to-display-pandas-dataframe-of-floats-using-a-format-string-for-columns – KPLauritzen Jan 10 '20 at 13:44

3 Answers3

1

You can try this:

import numpy as np
import pandas as pd 
ind = pd.date_range('01/01/2000', periods = 4, freq ='W') 
df = pd.DataFrame({"A":[None, -0.714286, 0.25, -0.2]},index = ind) 

df.loc[~df['A'].isna(), 'A'] = (df.loc[~df['A'].isna(), 'A']*100).astype(int).astype(str) + '%'

df['A']:

2000-01-02     NaN
2000-01-09    -71%
2000-01-16     25%
2000-01-23    -20%
Manualmsdos
  • 1,505
  • 3
  • 11
  • 22
1
df.loc[~df['A'].isna(), 'A'] = round((df.loc[~df['A'].isna(), 'A']*100),2).astype(str) + '%'
1

Here's a simple way using ifelse:

df['A'] = (df['A']
           .apply(lambda x: str(round(x, 2))+'%' if not pd.isna(x) else np.nan)
          )
YOLO
  • 20,181
  • 5
  • 20
  • 40
  • It is no need to import new module such as numpy in Dima First'code. –  Jan 12 '20 at 10:21