简体   繁体   English

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

[英]How to convert datatype of all columns in a pandas dataframe

I have pandas dataframe with 200+ columns.我有 200 多列的熊猫数据框。 All the columns are of type int.所有列都是 int 类型。 And I need to convert them to float type.我需要将它们转换为浮点型。 I could not find a way to do it.我找不到办法做到这一点。 I tried我试过

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

But after the for loop, when I print X_data.dtypes , all columns show as int only.但是在 for 循环之后,当我打印X_data.dtypes ,所有列仅显示为 int。 I also tried X_data = X_data.apply(pd.to_numeric) but it did not convert to float.我也试过X_data = X_data.apply(pd.to_numeric)但它没有转换为浮点数。

The dataframe is constructed from a csv file load.数据框是从 csv 文件加载构建的。

If you want to convert specific columns to specific types you can use:如果要将特定列转换为特定类型,可以使用:

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

df = df.astype(new_type_dict) 

It will now convert the selected columns to new types它现在会将选定的列转换为新类型

I found it from here我从这里找到的

The values aren't being saved in place.这些值没有保存到位。 Try the following:请尝试以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 转换数据类型 Pandas Dataframe - Convert datatype Pandas Dataframe 如何在Pandas数据框中将所有memoryview列转换为bytes列? - How to convert all the memoryview columns to bytes columns in a Pandas dataframe? 如何在Python中将具有对象/类别数据类型的多列熊猫数据框转换为int64? - how to convert multiple columns of pandas dataframe with object/categorical datatype to int64 in python? 如何在忽略 NaN 的同时将 Pandas DataFrame 中的所有列转换为“对象”? - How to convert all columns in Pandas DataFrame to 'object' while ignoring NaN? 将 arrays 数据类型转换为 pandas dataframe - Convert arrays datatype in pandas dataframe 将 pandas dataframe 中的所有列转换为嵌套列表 - Convert all columns in pandas dataframe into a nested list 如何获取Pandas中Dataframe的列的数据类型和数据长度 - How to get datatype and data length of the columns of Dataframe in Pandas Pandas - 如何将 dataframe 转换为新数据类型,但忽略标题/第一行 - Pandas - How to convert a dataframe to a new datatype but ignore the header/first row 如何将具有多个索引的 pandas.core.series.Series object 转换为 pandas ZC699575A5E8AFD9EZFBCA1A 填充的所有列? - How to convert pandas.core.series.Series object with Multiple index to a pandas Dataframe with all columns filled? 如果所有列均已分配对象,如何区分熊猫中的列数据类型 - How to distinguish column datatype in pandas if all columns are assigned object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM