【问题标题】:Simplifying pandas data cleaning简化 pandas 数据清理
【发布时间】:2022-01-03 22:01:57
【问题描述】:

我正在清理我的 pandas 数据框中的数据,我希望有比我更好的方法来做到这一点。 我在我的 pandas dateframe 输入中的列 ["count"] 中,就像他的:

~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”,那就太好了。 但是,我的主要目标只是从每一行中获得最低的数字,而其他一切都消失了。

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

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 循环中还是更智能的东西中......

感谢您的宝贵时间。

【问题讨论】:

    标签: python pandas data-cleaning


    【解决方案1】:

    关于从值中去除不需要的符号的解决方案,您可以使用内置的re 模块来收集字符串中的所有数字并从中获取最小的数字:

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

    要仅支持 python 操作,您可以尝试内置的 eval 函数,但是如果您需要支持不同的操作,例如“和”来求和您的数字,您可能需要编写一个解析器来进行更多自定义。 This 是一篇很酷的文章,您可以检查解析器及其组成部分。

    编辑:

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

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

    【讨论】:

    • 感谢您的文章!如果我运行上面的代码,我会收到以下错误:TypeError: expected string or bytes-like object
    • 嘿@Scapegoat,很抱歉我最初的回答只是针对一个值,现在在编辑后它针对整个列。
    • 嗯,它似乎正在工作。然而,它与一些数字有一些奇怪的相互作用。我的计数之一是 800-1000,然后将其减少到零?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 2021-08-14
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    相关资源
    最近更新 更多