[英]how to convert multiple columns of pandas dataframe with object/categorical datatype to int64 in python?
I know how to convert one column by one column in pyton, but i have many many col mixed with int64 or object datatype. 我知道如何在pyton中按一列转换一列,但是我有很多col与int64或object数据类型混合在一起。
In R, I can find these col index by test is.factor, then I can apply as.numeric in for loop to convert. 在R中,我可以通过测试is.factor找到这些col索引,然后可以在for循环中将as.numeric应用于转换。
But I don't know how to do in Python. 但是我不知道如何在Python中做。 Please help.
请帮忙。
If there was a way in other library, such as numpy, scipy, it would be great too. 如果其他库中有某种方法,例如numpy,scipy,那也将很棒。
thanks 谢谢
Just like with R you can use a simple for loop to convert column datatypes. 就像使用R一样,您可以使用简单的for循环来转换列数据类型。 First we check to see if the column is an object datatypes.
首先,我们检查列是否为对象数据类型。 If it is why try to convert the column.
如果是这样,请尝试转换列。 We use a try statement since the column may not be convertible to the integer datatype.
我们使用try语句,因为该列可能无法转换为整数数据类型。
for c in df.columns:
if df[c].dtype == 'O':
try:
df[c] = df[c].astype('int')
except:
print('Column',' ',c,' cannot be converted to int.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.