【问题标题】:1.0 as boolean dtype cause ValueError in pd.read_csv()1.0 作为布尔数据类型导致 pd.read_csv() 中的 ValueError
【发布时间】:2020-06-18 03:20:38
【问题描述】:

我有一个类似于以下文件的 CSV 文件,我想在其中读取“boolean_column”作为带有 pandas 的可为空的布尔 dtype。

boolean_column, string_column
1.0, a
0.0, b
,c

当我使用pd.read_csv() 阅读它而不分配数据类型时,不会引发错误:

import io
import pandas as pd

example_csv = """
boolean_column, string_column
1.0, a
0.0, b
,c"""

csv = io.StringIO(example_csv)
df = pd.read_csv(csv)
df.info()

>>> <class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
 #   Column          Non-Null Count  Dtype  
---  ------          --------------  -----  
 0   boolean_column  2 non-null      float64
 1    string_column  3 non-null      object 
dtypes: float64(1), object(1)
memory usage: 176.0+ bytes

但是,我希望“boolean_column”具有可为空的布尔 dtype 而不是 float64。因此,我在读取数据时分配了一个dtype。

csv = io.StringIO(example_csv)
df = pd.read_csv(csv, dtype={"boolean_column": "boolean"})

>>> ValueError: 1.0 cannot be cast to bool

我认为立即分配正确的 dtype 而不是事后强制转换 float64 更为优雅。我没有得到什么?这应该可行,对吧?

至少是这样:

pd.Series([None, 1.0, 0.0]).astype("boolean")

>>> 0     <NA>
1     True
2    False
dtype: boolean

【问题讨论】:

    标签: python pandas csv


    【解决方案1】:

    我不熟悉解决此问题的 read_csv 的开箱即用功能。但是,您可以构建自己的转换器:

    def foo(x):
        if x == "1.0": 
            return True
        elif x == "":
            return np.NaN
        else:
            return False
    
    pd.read_csv(StringIO(example_csv), converters = {"boolean_column": foo})
    

    结果是:

      boolean_column  string_column
    0           True              a
    1          False              b
    2            NaN              c
    

    【讨论】:

    • 这能回答你的问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 2015-01-26
    • 2023-02-06
    • 2011-06-13
    • 1970-01-01
    • 2019-10-04
    • 2019-10-02
    相关资源
    最近更新 更多