我在使用熊猫时遇到了问题,在处理后设置索引时,从csv加载的数据帧似乎恢复为原始dtype。看这个:
#Both these dicts contain columns and column types. They are the same
# except for two records - dtypesA lists columns ('ga:date', 'ga:minute')
# as dtype('O') and dtypesB lists columns ('ga:date', 'ga:minute') as
# dtype('int64')
dtypesA = {'ga:source': dtype('O'), 'ga:deviceCategory': dtype('O'),
'ga:country': dtype('O'), 'ga:metro': dtype('O'), 'ga:date': dtype('O'),
'ga:minute': dtype('O'), 'ga:channelGrouping': dtype('O'), 'ga:sessions':
dtype('int64'), 'ga:transactions': dtype('int64')}
dtypesB = {'ga:source': dtype('O'), 'ga:deviceCategory': dtype('O'),
'ga:country': dtype('O'), 'ga:metro': dtype('O'), 'ga:date': dtype('int64'),
'ga:minute': dtype('int64'), 'ga:channelGrouping': dtype('O'), 'ga:sessions':
dtype('int64'), 'ga:transactions': dtype('int64')}
dfA = pd.read_csv("my.csv", dtype=dtypesA)
dfB = pd.read_csv("my.csv", dtype=dtypesB)
#So the only difference between dfA and dfB now is that
# dfA has columns ('ga:date', 'ga:minute') typed as strings
# and dfB has columns ('ga:date', 'ga:minute') typed as
# ints.
dfB = dfB.astype(dtypesA)
dfB.dtypes
>ga:source object
>ga:deviceCategory object
>ga:country object
>ga:metro object
>ga:date object
>ga:minute object
>ga:channelGrouping object
>ga:sessions int64
>ga:transactions int64
>dtype: object
dfA.dtypes
>ga:source object
>ga:deviceCategory object
>ga:country object
>ga:metro object
>ga:date object
>ga:minute object
>ga:channelGrouping object
>ga:sessions int64
>ga:transactions int64
>dtype: object
#now both df's have the same dtypes.
indexCols = ['ga:source', 'ga:deviceCategory', 'ga:country', 'ga:metro',
'ga:date', 'ga:minute', 'ga:channelGrouping']
dfA.set_index(indexCols, inplace=True)
dfB.set_index(indexCols, inplace=True)
dfA.reset_index().dtypes
>ga:source object
>ga:deviceCategory object
>ga:country object
>ga:metro object
>ga:date object
>ga:minute object
>ga:channelGrouping object
>ga:sessions int64
>ga:transactions int64
>dtype: object
dfB.reset_index().dtypes
>ga:source object
>ga:deviceCategory object
>ga:country object
>ga:metro object
>ga:date int64
>ga:minute int64
>ga:channelGrouping object
>ga:sessions int64
>ga:transactions int64
>dtype: object
您可以从上面看到,在我重置
索引我的索引列回到其原始位置
数据类型,而不是我设置它们的数据类型。
尤其令人困惑的是DataFrame.astype()
据说会返回一个新的df,所以它不应该记住
上一个df中的旧类型。
有人知道如何解决这个问题吗?
我需要的数据类型为('ga:date','ga:minute') dfB是重置索引(不是int)后的字符串。