首页 > 解决方案 > 从 Pandas 的列中删除错误值

问题描述

我有一个数据框 df,我在列中看到重复或不需要的值。我想删除#T ex之前的所有数值。hi 1 1.92T,我希望删除单个“1”来创建:hi 1.92T

数据

type            value
hi 1 1.92T      5
hello 6 6.4T    5
yy16 1 6 12T    6
free 1 1 12T    7
Gal 0 0 0T      7
ex 8 8 8T       8

期望的

 type             value
    hi    1.92T   5
    hello 6.4T    5
    yy16  12T     6
    free  12T     7
    Gal   0T      7
    ex   8T       8

正在做

import re
df.type = re.sub("\d+\.?\d+?", "",  df.type)

我还在研究这个。任何建议表示赞赏。

标签: pythonpandasnumpy

解决方案


替换空格和之间的所有内容怎么样?是不是T永远不在字符串的最后一组字符中?这是定义模式的最佳方式吗?怎么样:

df['type'] = df['type'].str.replace('(\s+.*\s+)', ' ')
df

         type  value
0    hi 1.92T      5
1  hello 6.4T      5
2    yy16 12T      6
3    free 12T      7
4      Gal 0T      7
5       ex 8T      8

推荐阅读