我正在寻找一种有效的方法,从DataFrame列中的字符串中删除不需要的部分。

数据如下所示:

    time    result
1    09:00   +52A
2    10:00   +62B
3    11:00   +44a
4    12:00   +30b
5    13:00   -110a

我需要修剪这些数据:

    time    result
1    09:00   52
2    10:00   62
3    11:00   44
4    12:00   30
5    13:00   110

我尝试了.str.lstrip('+-')和.str.rstrip('aAbBcC'),但得到一个错误:

TypeError: wrapper() takes exactly 1 argument (2 given)

任何建议都将非常感激!


当前回答

在特定的情况下,你知道你想要从dataframe列中删除的位置的数量,你可以在lambda函数中使用字符串索引来摆脱这些部分:

最后一个字符:

data['result'] = data['result'].map(lambda x: str(x)[:-1])

前两个字符:

data['result'] = data['result'].map(lambda x: str(x)[2:])

其他回答

假设你的DF在数字之间也有这些额外的字符。最后一项。

  result   time
0   +52A  09:00
1   +62B  10:00
2   +44a  11:00
3   +30b  12:00
4  -110a  13:00
5   3+b0  14:00

可以尝试str.replace不仅从开头和结尾删除字符,还可以从中间删除字符。

DF['result'] = DF['result'].str.replace('\+|a|b|\-|A|B', '')

输出:

  result   time
0     52  09:00
1     62  10:00
2     44  11:00
3     30  12:00
4    110  13:00
5     30  14:00

在特定的情况下,你知道你想要从dataframe列中删除的位置的数量,你可以在lambda函数中使用字符串索引来摆脱这些部分:

最后一个字符:

data['result'] = data['result'].map(lambda x: str(x)[:-1])

前两个字符:

data['result'] = data['result'].map(lambda x: str(x)[2:])

这里有一个错误:当前不能将参数传递给str.lstrip和str.rstrip:

http://github.com/pydata/pandas/issues/2411

编辑:2012-12-07这工作现在在开发分支:

In [8]: df['result'].str.lstrip('+-').str.rstrip('aAbBcC')
Out[8]: 
1     52
2     62
3     44
4     30
5    110
Name: result

尝试使用正则表达式:

import re
data['result'] = data['result'].map(lambda x: re.sub('[-+A-Za-z]',x)
data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))