问题
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