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

python-格式化DataFrame Pandas中的多列

(python - Formatting multiple columns in dataframe pandas)

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

我有多列要格式化为具有固定精度的浮点小数。但是,不能同时处理多个列。在单个列上工作。原因是什么,如何解决?

以下作品。

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


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

但是,以下内容不起作用,并引发错误 TypeError:传递给Series的不受支持的格式字符串。格式

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

apply数据框上执行操作时,传递给函数的参数是列,即序列。使用applymap来代替:

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