繁体   English   中英

如何从字符串中删除所有字符并仅在数据框中保留数字?

[英]how to remove all characters from string and leave numbers only in dataframe?

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

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(values,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'

您可以使用此示例:

我选择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+

EDITED

对于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]])

您应该查看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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM