【问题标题】:how to remove all characters from string and leave numbers only in dataframe?如何从字符串中删除所有字符并仅在数据框中保留数字?
【发布时间】:2017-02-03 20:18:20
【问题描述】:

我在数据框中有几列包含数值和字符串
我想删除所有字符,只留下数字

Admit_DX_Description            Primary_DX_Description
510.9 - EMPYEMA W/O FISTULA     510.9 - EMPYEMA W/O FISTULA
681.10 - CELLULITIS, TOE NOS    681.10 - CELLULITIS, TOE NOS
780.2 - SYNCOPE AND COLLAPSE    427.89 - CARDIAC DYSRHYTHMIAS NEC
729.5 - PAIN IN LIMB            998.30 - DISRUPTION OF WOUND, UNSPEC

Admit_DX_Description            Primary_DX_Description
510.9                             510.9 
681.10                            681.10 
780.2                             427.89 
729.5                             998.30 

代码:

  for col in strip_col:
       # # Encoding only categorical variables
       if df[col].dtypes =='object':
           df[col] = df[col].map(lambda x: x.rstrip(r'[a-zA-Z]'))

print df.head()

错误:
Traceback(最近一次调用最后一次):

df[col] = df[col].map(lambda x: x.rstrip(r'[a-zA-Z]'))

文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/series.py”,第 2175 行,在地图中 new_values = map_f(值,arg) 文件“pandas/src/inference.pyx”,第 1217 行,在 pandas.lib.map_infer (pandas/lib.c:63307)

df[col] = df[col].map(lambda x: x.rstrip(r'[a-zA-Z]'))

AttributeError: 'int' 对象没有属性 'rstrip'

【问题讨论】:

    标签: python dataframe


    【解决方案1】:

    你可以使用这个例子:

    我选择re 模块仅提取浮点数。

    import re
    import pandas
    
    df = pandas.DataFrame({'A': ['Hello 199.9', '19.99 Hello'], 'B': ['700.52 Test', 'Test 7.7']})
    
    df
                 A            B
    0  Hello 199.9  700.52 Test
    1  19.99 Hello     Test 7.7
    
    for col in df:
        df[col] = [''.join(re.findall("\d+\.\d+", item)) for item in df[col]]
    
           A       B
    0  199.9  700.52
    1  19.99     7.7
    

    如果您也有整数,请将re pattern 更改为:\d*\.?\d+

    已编辑

    对于TypeError,我建议使用try。在这个例子中,我创建了一个列表errs。此列表将用于except TypeError。你可以print (errs)查看这些值。

    也检查df

    ...
    ...
    errs = []
    for col in df:
        try:
            df[col] = [''.join(re.findall("\d+\.\d+", item)) for item in df[col]]
        except TypeError:
            errs.extend([item for item in df[col]])
    

    【讨论】:

    • 嘿,这是一个很好的答案,但我收到了这个错误 TypeError: expected string or buffer 但我发现有些字符串的值类似于“250.82 - DIABETES, .TYPE II" 你有什么想法我可以处理这个
    • 我运行这个新的数据框:df = pandas.DataFrame({'A': ['250.82 - DIABETES,.TYPE II', '19.99 Hello'], 'B': ['700.52 Test', 'Test 7.7']}),但我没有得到任何TypeError。可能是另一个不同于 250.82 - DIABETES,.TYPE II 的字符串。
    • 我不知道,但可能是这样的 V22.0 - SUPERVIS NORMAL 1ST PREG
    【解决方案2】:

    您应该查看df.applymap 并将其应用于要从中删除文本的列。 [编辑] 或者:

    import pandas as pd 
    test = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}] 
    fun = lambda x: x+10 
    df = pd.DataFrame(test) 
    df['c1'] = df['c1'].apply(fun) 
    print df
    

    【讨论】:

    • 我试过了,但我得到了这个错误 AttributeError: 'Series' object has no attribute 'applymap'
    猜你喜欢
    • 1970-01-01
    • 2011-02-07
    • 2014-04-11
    • 1970-01-01
    • 2011-10-19
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多