pandas 字符串到数字 [英] pandas string to numeric
本文介绍了 pandas 字符串到数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组数据,例如
a b
0 type 1 True
1 type 2 False
如何保持列a
的数字部分并将ture转换为1,同时将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
推荐答案
您可以按以下方式将布尔值转换为整数:
You can convert Booleans to integers as follows:
df['b'] = df.b.astype(int)
根据列A
中文本的性质,您可以执行以下操作:
Depending on the nature of your text in Column A
, you can do a few things:
a)在空格上分割并占第二部分(根据您的需要为字符串或整数).
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)使用正则表达式从字符串末尾提取任何数字(\d*
).
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)`
这篇关于 pandas 字符串到数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文