【问题标题】:How can I strip off all non-numeric characters in a Pandas Series如何去除 Pandas 系列中的所有非数字字符
【发布时间】:2020-06-22 04:55:49
【问题描述】:
我有一个 Pandas 数据框。而且我有兴趣获得只有数字字符的特定列。
例如,列包含如下行:
4'> delay trip
4/
4'>book flight 'trip
34
4"> book flight delay
4"
我怎样才能去掉所有非数字字符,只剩下这样的数字字符:
4
4
4
[3,4]
4
4
【问题讨论】:
标签:
python
string
pandas
split
data-manipulation
【解决方案1】:
这里有两个不同的问题:
- 首先是从列单元格中提取数字
- 第二个是如果你有一个以上的数字就列出来
只需链接两个操作:
df[col].str.findall(r'\d').apply(lambda x: x[0] if len(x) == 1 else '' if len(x) == 0 else x)
以你为例,它给出了:
0 4
1 4
2 4
3 [3, 4]
4 4
5 4