Python 使用for循环更改多列的类别类型
我从kaggle()中获得了这个数据集,我正在尝试使用以下代码一次性将这些列的数据类型从integer更改为category:Python 使用for循环更改多列的类别类型,python,pandas,Python,Pandas,我从kaggle()中获得了这个数据集,我正在尝试使用以下代码一次性将这些列的数据类型从integer更改为category: cols = (df['systemic_crisis'], df['independence'], df['currency_crises'], df['inflation_crises']) for col in cols: col = col.astype('category') df.info() 但显然它不起作用,数据类
cols = (df['systemic_crisis'], df['independence'], df['currency_crises'], df['inflation_crises'])
for col in cols:
col = col.astype('category')
df.info()
但显然它不起作用,数据类型仍然是int64而不是category。我的代码哪里做错了?谢谢。您不是在更改实际数据帧的数据类型,而是在更改使用创建的元组的数据类型
(系统性危机、独立性危机、货币危机、通货膨胀危机)
你需要:
cols = ['systemic_crisis','independence','currency_crises','inflation_crises']
for col in cols:
df[col] = df[col].astype('category')
编辑
正如@Jon Clements所说,您也可以使用
df.update(df[cols].astype('category'))
你能澄清完整的代码吗?我使用了您的代码,它将表中的所有列改为category,而不是我想要的列。您也可以这样做:
df.update(df[cols].astype('category'))
。。。