简体   繁体   English

如何遍历 pandas dataframe 列并检查每列的数据类型并在需要时将其更改为另一种数据类型

[英]How to iterate through a pandas dataframe column and check the datatype of each column and change it another datatype if needed

I have a dataframe "df".我有一个 dataframe “df”。 I'm trying to access all the columns of the dataframe and check the datatype of each column and if the datatype is "object" i want to change it to float.我正在尝试访问 dataframe 的所有列并检查每列的数据类型,如果数据类型是“对象”,我想将其更改为浮动。

I'm trying with the below code, but it is not working:我正在尝试使用以下代码,但它不起作用:

for colname, coltype in df.dtypes.iteritems():
    if coltype == object:
         df[colname] = df[colname].astype(np.float32)

I don't understand what is wrong here.我不明白这里有什么问题。 Can anyone help me out please?谁能帮帮我?

you can try this code你可以试试这段代码

types={}
for col in df.columns:
    if df[col].dtype == object:
        types[col] = float
    else:
        types[col] = df[col].dtype
df = df.astype(types)

暂无
暂无

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

相关问题 更改 Pandas 数据框列中的数据类型 - Change Datatype in Pandas Dataframe Column 无法更改 pandas dataframe 列中的数据类型 - Cannot change datatype in pandas dataframe column 如何更改dask数据框中列的数据类型? - How to change the datatype of column in dask dataframe? 根据列的原始数据类型更改 Pandas Dataframe 中列的数据类型 - Change datatype of columns in Pandas Dataframe depending on the original data type of the column 遍历pandas数据框,使用if语句检查每个列值,并将该列值传递到空df的首选列 - Iterate through a pandas dataframe, check each column value with an if statement and pass the column values to the prefered column of an empty df 如何在Pandas DATAFRAME中查找具有特定数据类型的列值的行 - How to find rows with column values having a particular datatype in a Pandas DATAFRAME 如何创建一个熊猫数据框,其中列的数据类型将是字典? - How to create a pandas dataframe where the datatype of a column will be a dictionary? 如何将 pandas dataframe 'unnamed 0' 列数据类型从 int64 更改为字符串或 object - How to change the pandas dataframe 'unnamed 0' column datatype from int64 to string or object 如何在每列的熊猫数据框中找到不合适的数据类型? - How to find inappropriate datatype in pandas data frame for each column? 无法将数据框列的数据类型更改为 int - Can't change datatype of dataframe column to int
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM