【问题标题】:Formatting multiple columns in dataframe pandas格式化数据框熊猫中的多列
【发布时间】:2020-12-01 11:09:07
【问题描述】:

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

以下工作。

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)

【问题讨论】:

  • outputData['col1', 'col2'] = outputData[['col1', 'col2']].apply(shortenlength) 怎么样?
  • 显示相同的错误“传递给 Series.__format__ 的格式字符串不受支持”

标签: python pandas formatting


【解决方案1】:

当您在数据帧上执行apply 时,传递给函数的参数是列,即系列。请改用applymap

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

【讨论】:

  • 谢谢。效果很好。
猜你喜欢
  • 2021-10-04
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
  • 2020-08-03
  • 1970-01-01
  • 2013-06-03
相关资源
最近更新 更多