我想创建一个具有新的可为null标量类型的DataFrame。我使用的是pandas 1.0.3。
给定进口:
import numpy as np
import pandas as pd
from collections import OrderedDict
如果我有列名:
headers = ['field',
'yr_code',
'start_col',
'end_col',
'year',
'variable_name',
'characteristics',
'source',
'date_on']
和数据类型:
dt = [pd.StringDtype(),
pd.Int64Dtype(),
np.int16,
np.numpy.int16,
pd.Int64Dtype(),
pd.StringDtype(),
pd.StringDtype(),
pd.StringDtype(),
pd.StringDtype()]
我尝试创建列规范为:
columns = OrderedDict((h, dt[i]) for i, h in enumerate(headers))
和一个数据帧作为(带示例数据(:
data = [['F00001', pd.NA, 1, 1, '', 'Blank', '', pd.NA, pd.NA]]
f = pd.DataFrame(data, columns = columns)
不幸的是,这似乎不起作用:
>>> f.dtypes
field object
yr_code object
start_col int64
end_col int64
year object
variable_name object
characteristics object
source object
date_on object
dtype: object
我知道dtypes
可能返回底层类型,但作为对象的yr_code
肯定是错误的。如何为这些类型正确创建DataFrame?
您可以执行f.convert_dtypes()
以获得:
>>> f.convert_dtypes().dtypes
field string
yr_code object
start_col Int64
end_col Int64
year string
variable_name string
characteristics string
source object
date_on object