Warm tip: This article is reproduced from serverfault.com, please click

Formatting multiple columns in dataframe pandas

发布于 2020-12-01 02:30:39

I've multiple columns to format as a float decimal with fixed precision. However, doing with multiple columns at the same time doesn't work. Working on individual columns works. What is the reason and how to resolve the same?

The following works.

def shortenlength(numberToShorten):
    limited_float = "{:.15f}".format(numberToShorten)
    return limited_float


outputData['col1'] = outputData['col1'].apply(shortenlength)
outputData['col2'] = outputData['col2'].apply(shortenlength)

However, the following doesn't work and throws the error TypeError: unsupported format string passed to Series.format

def shortenlength(numberToShorten):
    limited_float = "{:.15f}".format(numberToShorten)
    return limited_float

zfill_cols = ['col1', 'col2']
outputData[zfill_cols] = outputData[zfill_cols].apply(shortenlength)
Questioner
nsivakr
Viewed
0
Quang Hoang 2020-12-01 11:09:07

When you do apply on a dataframe, the argument passed to the function is the columns, i.e. the series. Use applymap instead:

outputData[zfill_cols] = outputData[zfill_cols].applymap(shortenlength)