pandas string to numeric

不问归期 提交于 2019-12-20 05:57:10

问题


I have a set of data like

        a      b
0  type 1   True
1  type 2  False

How can I keep the numerical part of column a and transfer ture to 1, false to zero at the same time. Below is what I want.

   a  b
0  1  1
1  2  0

回答1:


You can convert Booleans to integers as follows:

df['b'] = df.b.astype(int)

Depending on the nature of your text in Column A, you can do a few things:

a) Split on the space and take the second part (either string or int depending on your needs).

df['a'] = df.a.str.split().str[1]  # Optional `.astype(int)`

b) Use regex to extract any digits (\d*) from the end of the string.

df['a'] = df.a.str.extract(r'(\d*)$')  # Optional `.astype(int)`


来源:https://stackoverflow.com/questions/39239506/pandas-string-to-numeric

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!