gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:42:44 26 4
gpt4 key购买 nike

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

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()

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

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 行,在 map 中 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]'))

属性错误:“int”对象没有属性“rstrip”

最佳答案

您可以使用这个示例:

我选择了re模块来仅提取 float 。

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

如果您还有整数,请将重新模式更改为:\d*\.?\d+

已编辑

对于TypeError,我建议使用try。在此示例中,我创建了一个错误列表。该列表将在 TypeError 除外 中使用。您可以打印(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]])

关于python - 如何从字符串中删除所有字符并仅在数据框中保留数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42032383/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com