简体   繁体   中英

Formatting multiple columns in dataframe pandas

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM