如何转换熊猫数据框中所有列的数据类型

时间:2020-03-16 04:47:22

标签: python pandas

我有200列以上的pandas数据框。所有列均为int类型。我需要将它们转换为浮点型。我找不到办法。 我尝试过

for column in X_data:
    X_data[column].astype('float64')

但是在for循环之后,当我打印X_data.dtypes时,所有列仅显示为int。 我也尝试过X_data = X_data.apply(pd.to_numeric),但是它没有转换为float。

数据帧是通过csv文件加载构建的。

2 个答案:

答案 0 :(得分:2)

如果要将特定的列转换为特定的类型,可以使用:

new_type_dict = {
                 'col1': float, 
                 'col2': float
                 } 

df = df.astype(new_type_dict) 

现在它将把选定的列转换为新的类型

我从here

找到了它

答案 1 :(得分:1)

值未保存到位。请尝试以下操作:

for column in X_data:
    X_data[column] = X_data[column].astype('float64')