[英]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.