2

I am trying to have a comma thousands separator for easier viewing in several columns of my pandas df.

My question builds upon this question+answer. But I want to apply it to several columns and I fail.

A minimal example:

# A random df
df = pd.DataFrame({'a' : np.random.normal(200000, 10000, 6),
                 'c' : np.random.normal(200000, 100000, 6)})

# This works:
df['a'] = df.a.apply(lambda x : "{:,}".format(x))

# But this doesn't
df = df.apply(lambda x : "{:,}".format(x) if x.name in ['a', 'c'] else x)

Would greatly appreciate if somebody could show me the way. Note that I want to apply this function to several dozen columns, so manually repeating the code for every column is not the solution.

BeSeLuFri
  • 623
  • 1
  • 5
  • 21

1 Answers1

1

Use DataFrame.applymap with list of columns names for processing:

np.random.seed(2020)
df = pd.DataFrame({'a' : np.random.normal(200000, 10000, 6),
                 'c' : np.random.normal(200000, 100000, 6)})

cols = ['a', 'c'] 
df[cols] = df[cols].applymap("{:,}".format)
print (df)
                     a                    c
0   182,311.5429442405  193,884.55680466516
1   200,755.5227120811  206,451.38441186142
2  188,693.70297194656  241,011.29497994468
3  193,485.69833095264   142,711.7509918912
4    191,068.843736801  119,866.63751387625
5   187,258.9902320009   331,203.5192212922
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252