Formatting Multiple Columns by Name using .loc

Viewed 79

My goal is to state a list of columns by name that I want to apply the formatting to.

The section that is commented out is ideally what I am after (which would mean removing the line of code directly above what is commented), but I get the following error:

'DataFrame' object has no attribute 'map'` error.

Is there a way/better way to achieve what I am attempting?

import pandas as pd

cols = ['Spend', 'Sales']
stuff=[[3, 2],[5, 6]]
df = pd.DataFrame(stuff, columns = cols)


df.loc[:, 'Spend'] ='$'+ df['Spend'].map('{:,.0f}'.format)

# list1=['Spend', 'Sales']
# df.loc[:, list1] ='$'+ df[list1].map('{:,.0f}'.format)

print(df)
3 Answers

Your code almost gets there, you just need to call map inside a call to apply (which will do it for each column):

list1 = ['Spend', 'Sales']
df.loc[:, list1] = '$'+ df[list1].apply(lambda col: col.map('{:,.0f}'.format))

Output:

>>> df
  Spend Sales
0    $3    $2
1    $5    $6

Are you looking for something along the lines of:

df[list1] =['$']*2 + df[list1].astype(str)

or (as suggested by @richardec):

df[list1] = '$' + df[list1].astype(str)

Output:

  Spend Sales
0    $3    $2
1    $5    $6
Related