Python 熊猫只更改float64的数据类型列
我需要更改多列(超过400列)的数据类型,但数据帧有不同类型的数据类型。有些列的数据类型是Python 熊猫只更改float64的数据类型列,python,pandas,Python,Pandas,我需要更改多列(超过400列)的数据类型,但数据帧有不同类型的数据类型。有些列的数据类型是float64,而有些列的数据类型是int64或object: print my_df.dtypes 输出: x1 int64 x2 int64 x3 object x4 float64 x5
float64
,而有些列的数据类型是int64
或object
:
print my_df.dtypes
输出:
x1 int64
x2 int64
x3 object
x4 float64
x5 float64
x6 float64
x7 float64
...
x400 object
x401 object
x402 object
...
我需要将所有int64
更改为int8
或int16
,并将所有float64
更改为float32
。我尝试了下面的代码片段,但没有成功:
my_df[my_df.dtypes == np.int64].astype(np.int16)
my_df[my_df.dtypes == np.float64].astype(np.float32)
感谢您的帮助
提前谢谢 您可以构建映射字典并使用
astype
new_types = {np.dtype(np.int64): np.int16,
np.dtype(np.float64): np.float32}
df = df.astype(df.dtypes.map(new_types).to_dict())
例如:
df = pd.DataFrame({'col1': [1,2,3], 'col2': [1.0,2.0,3.0]})
col1 col2
0 1 1.0
1 2 2.0
2 3 3.0
>>> df.dtypes
col1 int64
col2 float64
dtype: object
然后
给出了新类型的目录
{'col1': numpy.int16, 'col2': numpy.float32}
然后将astype
与此命令一起使用
>>> df.astype(df.dtypes.map(new_types).to_dict())
col1 int16
col2 float32
dtype: object
设置
用于获取与所需类型匹配的列:
df.select_dtypes(np.float64) # or df.select_dtypes(np.float64).columns to save for casting
b
0 0.0
1 1.0
2 2.0
3 3.0
4 4.0
并根据需要施展。好的,我找到我的方法:)
查找数据类型为float64
cols = my_df.select_dtypes(include=[np.float64]).columns
然后仅更改数据帧的cols
my_df[cols] = my_df[cols].astype(np.float32)
你差点就成功了
my_df.loc[:, my_df.dtypes == 'float64'] = my_df.loc[:, my_df.dtypes == 'float64'].astype('float32')
my_df.loc[:, my_df.dtypes == 'int64'] = my_df.loc[:, my_df.dtypes == 'int64'].astype('int32')
my_df[cols] = my_df[cols].astype(np.float32)
my_df.loc[:, my_df.dtypes == 'float64'] = my_df.loc[:, my_df.dtypes == 'float64'].astype('float32')
my_df.loc[:, my_df.dtypes == 'int64'] = my_df.loc[:, my_df.dtypes == 'int64'].astype('int32')