简体   繁体   English

如何在Python中将具有对象/类别数据类型的多列熊猫数据框转换为int64?

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

相关问题 如何在python中将列数据类型int64转换为分类列数据类型? - How convert column datatype int64 to categorical column datatype in python? Python:将pandas数据框中的系列对象列转换为int64 dtype - Python: convert series object columns in pandas dataframe to int64 dtype 将多个 dataframe 列 int64 dtype 转换为等效于 oracle 的 NUMBER(20,3) 数据类型 - convert multiple dataframe columns int64 dtype to equivalent of NUMBER(20,3) datatype of oracle 如何将数据帧对象转换为 Int64? - How to convert dataframe object into Int64? 如何将 pandas dataframe 'unnamed 0' 列数据类型从 int64 更改为字符串或 object - How to change the pandas dataframe 'unnamed 0' column datatype from int64 to string or object 如何将 int64 转换为分钟? 蟒蛇熊猫 - How convert an int64 to minutes ? Python Pandas 在 python 列中将这些对象转换为 int64 - Convert these Objects to int64 in python columns 如何在 Pandas 中将 int64 转换为日期时间 - How to convert int64 to datetime in pandas python中object数据类型如何转换成int64? - How to convert object data type into int64 in python? 如何将具有 JSON 的 pandas 列中的值数据类型从大数字转换为 int64? - How to convert value datatype in pandas column with JSON from big number to int64?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM