首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简化pandas数据清理

问简化pandas数据清理
EN

Stack Overflow用户
提问于 2021-11-25 16:15:58
回答 1查看 51关注 0票数 0

我正在清理我的熊猫数据框中的数据,我希望有比我的更好的方法来做到这一点。我在我的pandas dateframe中的“count”一栏中输入了类似于他的:

代码语言:javascript
复制
~186-205
4 and 4 
200
800-1000
550-550[2]
10, 20 or 50
5 (four score and bla bla)
38 or 30
88-80

如果有人能告诉我如何将数字相加,如果他们说"x和x“,那就太好了。然而,我的主要目标只是从每一行中获得最低的数字,而其他所有东西都消失了。

我几乎完全用我的解决方案成功了:

代码语言:javascript
复制
df['Count'] = df['Count'].str.replace(r"\(.*\)","") #all square brackets with content
df['Count'] = df['Count'].str.replace(r"\[.*\]","") #all square brackets with content
df['Count'] = df['Count'].str.replace("(−).*","")  #For one type of hyphens
df['Count'] = df['Count'].str.replace("(-).*","")  #for another type of hyphens
df['Count'] = df['Count'].str.replace("(—).*","")  #for yet another type of hyphens
df['Count'] = df['Count'].str.replace("(\u2013).*","") #because of different formating for hyphens
df['Count'] = df['Count'].str.replace("(or).*","") #for other alternatives, remove
df['Count'] = df['Count'].str.replace("(,).*","") #everything after commas
df['Count'] = df['Count'].replace(r'\D+', "", regex=True) #everything but numbers

有什么建议可以让它更优雅吗?要么是在函数中,要么是for循环,要么就是更聪明的东西...

谢谢您抽时间见我。

EN

回答 1

Stack Overflow用户

发布于 2021-11-25 16:41:40

关于从值中剔除不需要的符号的解决方案,您可以使用内置的re模块来收集字符串中的所有数字,并只获得其中最低的一个:

代码语言:javascript
复制
import re

min(map(int, re.findall(r'[0-9]+', value)))

要只支持python操作,你可以尝试内置的eval函数,但是如果你需要支持不同的操作,比如'and‘来求和,你可能需要编写一个解析器来进行更多的定制。This是一篇很酷的文章,你可以查看解析器以及它们的组成部分。

编辑:

要将其应用于整个列,请提取最小数字的函数,然后应用该函数。

代码语言:javascript
复制
import re

def get_min_number(value):
    return min(map(int, re.findall(r'[0-9]+', value)))

df['Count'].apply(get_min_number)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70114296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档