简体   繁体   English

将 dtype 从 object 转换为 int

[英]Convert dtype from object to int

I have我有

df = df['enrolment'].astype(str).astype(int)

changing from str to int but it doesn't work.str更改为int但它不起作用。 Instead, it says:相反,它说:

invalid literal for int() with base 10: '5,424'

I want to change from objec t to int .我想从objec t 更改为int How do I solve this?我该如何解决这个问题?

df=pd.read_csv('C:/data/intake-enrolment-and-graduates-by-course.csv',sep=',')
print(df['enrolment'].dtypes)

Given the invalid literal error, the conversion from str to int fails as you have decimal commas in your numbers.鉴于invalid literal错误,从strint的转换失败,因为您的数字中有十进制逗号。 These are nice for readability but throw a wrench into the conversion to integer.这些对可读性很好,但在转换为 integer 时会遇到麻烦。 Deleting the commas does the trick.删除逗号就可以了。

In particular, use特别是,使用

df['enrollment'] = df['enrollment'].str.replace(',', '').astype(int)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM