Home > Enterprise >  Formatting Multiple Columns by Name using .loc
Formatting Multiple Columns by Name using .loc

Time:03-26

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)

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

From this thread How to display pandas DataFrame of floats using a format string for columns? we can learn

cols = ['Spend', 'Sales']
stuff=[[3, 2],[5, 6]]
df = pd.DataFrame(stuff, columns = cols)
list1 = ['Spend', 'Sales']
df[list1] = df[list1].applymap('${:,.2f}'.format)
  • Related