语义上的区别在于 dtype
允许你指定如何处理值,例如,将其视为数字或字符串类型。
转换器允许您解析输入数据并使用转换函数将其转换为所需的 dtype,例如,将字符串值解析为日期时间或其他所需的 dtype。
在这里,我们看到 pandas 尝试嗅探类型:
In [2]:
df = pd.read_csv(io.StringIO(t))
t="""int,float,date,str
001,3.31,2015/01/01,005"""
df = pd.read_csv(io.StringIO(t))
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1 entries, 0 to 0
Data columns (total 4 columns):
int 1 non-null int64
float 1 non-null float64
date 1 non-null object
str 1 non-null int64
dtypes: float64(1), int64(2), object(1)
memory usage: 40.0+ bytes
你可以从上面看到,
001
和
005
被视为
int64
,但日期字符串保持为
str
。
如果我们说一切都是
object
,那么本质上一切都是
str
。
In [3]:
df = pd.read_csv(io.StringIO(t), dtype=object).info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1 entries, 0 to 0
Data columns (total 4 columns):
int 1 non-null object
float 1 non-null object
date 1 non-null object
str 1 non-null object
dtypes: object(4)
memory usage: 40.0+ bytes
在这里,我们强制将 int
列转换为 str
,并告诉 parse_dates
使用 date_parser 来解析日期列:
In [6]:
pd.read_csv(io.StringIO(t), dtype={'int':'object'}, parse_dates=['date']).info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1 entries, 0 to 0
Data columns (total 4 columns):
int 1 non-null object
float 1 non-null float64
date 1 non-null datetime64[ns]
str 1 non-null int64
dtypes: datetime64[ns](1), float64(1), int64(1), object(1)
memory usage: 40.0+ bytes
同样地,我们可以传递
to_datetime
函数来转换日期:
In [5]:
pd.read_csv(io.StringIO(t), converters={'date':pd.to_datetime}).info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1 entries, 0 to 0
Data columns (total 4 columns):
int 1 non-null int64
float 1 non-null float64
date 1 non-null datetime64[ns]
str 1 non-null int64
dtypes: datetime64[ns](1), float64(1), int64(2)
memory usage: 40.0 bytes