'I have multiple columns in a dataframe and i want to apply a function to all of them

the .apply() method does not seem to work on my exampl. i want to format specific columns with a thousand separator for my numbers

my function:

def thousand_separator(df, column):
    df.loc\[:, column\] = df\[column\].map("{:,.4f}".format)
    return df

**the below is not working **

portfolios_moc_tab_export\[\["Equity Active Risk", "NAV (USD)"\]\] = portfolios_moc_tab_export\[\["Equity Active Risk", "NAV (USD)"\]\].apply(thousand_separator, axis = 1)

Below is working but i do not want to create so many rows in my code:

thousand_separator(portfolios_moc_tab_export, "NAV (USD)")

i expect many columns to take in my function which also use my dataframe



Solution 1:[1]

You can simply use applymap() once on all the columns of your choice, instead of map() on each of them.

For example:

np.random.seed(0)
df = pd.DataFrame(np.random.randint(0, 1e9, (5, 5)), columns=list('abcde'))

colsel = list('acde')

>>> df[colsel].applymap('{:,.2f}'.format)

                a               c               d               e
0  209,652,396.00  924,231,285.00  404,868,288.00  441,365,315.00
1  463,622,907.00  417,693,031.00  745,841,673.00  530,702,035.00
2  626,610,453.00  805,680,932.00  204,159,575.00  608,910,406.00
3  243,580,376.00   97,308,044.00  573,126,970.00  977,814,209.00
4  179,207,654.00  124,102,743.00  987,744,430.00  292,249,176.00

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1