我正在寻找一种有效的方法来删除数据帧列中字符串中不需要的部分。
数据如下:
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)
任何指点都将不胜感激!
我会使用熊猫替换功能,非常简单和强大,因为你可以使用正则表达式。下面我将使用regex\D来删除任何非数字字符,但很明显,您可以使用regex获得相当多的创造性。
在最初的问题发布6年后,pandas现在拥有大量的“矢量化”字符串函数,可以简洁地执行这些字符串操作。
这个答案将探索其中一些字符串函数,提出更快的替代方案,并在最后进行计时比较。
^{}
指定要匹配的子字符串/模式,以及要用其替换的子字符串。
如果需要将结果转换为整数,可以使用^{}
如果不想就地修改} :
df
,请使用^{^{}
用于提取要保留的子字符串。
对于
extract
,需要指定至少一个捕获组。expand=False
将返回一个系列,其中包含从第一个捕获组捕获的项。^{} 和^{}
拆分工作假设所有字符串都遵循这种一致的结构。
如果你正在寻找一般的解决方案,不要推荐。
优化:列表理解
在某些情况下,列表理解应该优先于pandas字符串函数。原因是字符串函数本身就很难矢量化(在单词的真正意义上),所以大多数字符串和正则表达式函数只是循环的包装器,开销更大。
我写的For loops with pandas - When should I care?更详细。
可以使用
re.sub
重新编写str.replace
选项这个
str.extract
示例可以使用re.search
的列表理解重新编写如果不匹配或不匹配是可能的,您将需要重新编写上述内容以包括一些错误检查。我是用函数来做的。
我们还可以使用列表理解重新编写@eumiro和@MonkeyButter的答案:
而且
同样的规则也适用于处理NaNs等。
性能比较
使用perfplot生成的图。Full code listing, for your reference.下面列出了相关函数。
有些比较是不公平的,因为它们利用了OP的数据结构,但你可以从中得到你想要的。需要注意的一点是,每个列表理解函数都比其等价的pandas变体更快或更具可比性。
函数
相关问题 更多 >
编程相关推荐