pandas read_csv 数据类型定义:int、int64、'Int64'

bic*_*cta 7 file-io dataframe pandas

有人可以指出一个好的方向来理解 pandas.read_csv 期间定义 dtype 的方式(看似)不一致吗?

dtype = int # --> 如果空白值会产生错误
dtype = int32、int64 和 Int64 # --> 未定义
dtype = 'Int64' # --> 正确地将 csv 文件读取为整数并包含空白值

  • 为什么 'Int64' 需要引号,而 str、float、int、object 不需要引号?
  • 我没有找到明确定义 pandas.read_csv 的有效数据类型列表的参考。这存在于某处吗?
import pandas as pd; print(pd.__version__)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

MY_DTYPES = {
    'date_string': str,
    'description': str,
#    'ValueError_Integer_column_has_NA_values': int,
#    'int32_is_not_defined': int32,
#    'int64_is_not_defined': int64,
#    'Int_64_is_not_defined': Int64,
    'Int64_with_quote_and_NaN': 'Int64', # !! THIS WORKS !!
    'quantity': float,
    'total': float}

f = 'dataset.csv'
df = pd.read_csv(f, dtype = MY_DTYPES)
Run Code Online (Sandbox Code Playgroud)
df.head(15)
   date_string  description  Int64_with_quote_and_NaN  quantity   total
0       201202   "Lorem ips                       513     186.0     4.0
1       200909     um dolor                       601     502.0    13.0
2       201701          sit                       NaN     462.0    20.0
3       201401        amet,                       513     934.0   206.0
4       201202  consectetur                       513       NaN   194.0
5       200710   adipiscing                       602     570.0   930.0
6       200501        elit,                       513     160.0     NaN
7       200808          sed                       NaN     508.0   461.0
8       201906           do                       513     316.0     3.0
9       201009      eiusmod                       NaN     994.0     1.0
10         NaN          NaN                       513     709.0     0.0
11      201905   incididunt                       513     318.0     6.0
12      201612           ut                       513       NaN     1.0
13      201506       labore                       513     901.0    74.0
14      201002          NaN                       625      33.0   739.0
Run Code Online (Sandbox Code Playgroud)

小智 0

为什么 int64 需要引号?

由于提到的 dtype 不是 python 的内置 dtype,因此'int64', 'Int64', 'int32'是表示需要引号的特定 NumPy dtype 的字符串。

正确方法:dtype={'column_name': 'Int64'}

有效的数据类型选项:

  • 内置 python 数据类型:int, float, str, bool, object
  • NumPy dtypes(作为字符串):'int8', 'int16', 'int32', 'int64', 'float16', 'float32', 'float64', 'string_', 'category', 'datetime64[ns]'