【问题标题】:Integer format specification 'd' produces ValueError when applied row by row to numpy.int column in pandas DataFrame将整数格式规范“d”逐行应用于 pandas DataFrame 中的 numpy.int 列时会产生 ValueError
【发布时间】:2020-04-02 01:42:44
【问题描述】:

假设我创建了一个包含 intfloat 类型的 pandas 数据框:

>>> df=pd.DataFrame([[1, 1.3], [2, 2.4]], columns=['a', 'b'])
>>> df
   a    b
0  1  1.3
1  2  2.4

很明显,'a' 列是由numpy.int64 值组成的:

>>> df.a.dtype
dtype('int64')
>>> df.a[0]
1
>>> type(df.a[0])
<class 'numpy.int64'>

...我可以使用d 格式化说明符来格式化这些列'a' 值:

>>> "{a:d}".format(a=df.a[0])
'1'

但是,如果我尝试逐行应用相同的格式,则会收到此错误消息,指出 'a' 列中的值是浮点数而不是整数:

>>> df.apply(lambda s: "{a:d}{b:f}".format(**s), axis=1)
Traceback (most recent call last):
...
ValueError: ("Unknown format code 'd' for object of type 'float'", 'occurred at index 0')

这里发生了什么?

【问题讨论】:

    标签: python pandas formatting number-formatting


    【解决方案1】:

    当列/行中有int和float值时,apply方法将值视为浮动。

    df.apply(lambda x: ( type(x['a']),type(x['b']) ),axis=1)
    0    (<class 'numpy.float64'>, <class 'numpy.float6...
    1    (<class 'numpy.float64'>, <class 'numpy.float6...
    dtype: object
    

    为避免这种情况,您可以使用 DataFrame.astype 将数据框的类型更改为对象

    df.astype(object).apply(lambda s: "{a:d}{b:f}".format(**s.astype(int)), axis=1)
    0    11.000000
    1    22.000000
    dtype: object
    

    df.astype(object).apply(lambda x: ( type(x['a']),type(x['b']) ),axis=1)
    0    (<class 'int'>, <class 'float'>)
    1    (<class 'int'>, <class 'float'>)
    dtype: object
    

    【讨论】:

    • "当列/行中有int和float值时,apply方法将值视为浮动。" -- 文档中是否有解释这种行为的信息...?
    • 真的官方文档没有说清楚,这个问题已经在这里讨论过:github.com/pandas-dev/pandas/issues/23230,这里stackoverflow.com/questions/47143631/…
    • 明白了。好吧,这不清楚这个周末花了我几个小时!发布的问题是一个更大问题的大大简化的摘录。很高兴终于弄明白了,谢谢。
    【解决方案2】:

    让我们修复它

    df.apply(lambda s: "{a:.0f}{b:f}".format(**s), axis=1)
    0    11.300000
    1    22.400000
    dtype: object
    

    【讨论】:

    • 这可能是解决问题的最佳方法!不过,我将选择另一个答案作为正确答案,因为它解释了为什么
    猜你喜欢
    • 2019-12-25
    • 2015-01-25
    • 2021-04-04
    • 1970-01-01
    • 2015-03-16
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    相关资源
    最近更新 更多