柳奈奈 2021-03-29 17:06 采纳率: 100%
浏览 174
已采纳

python数据集异常符号的处理和缺失值填补的问题

大家好!我在尝试使用df.replace函数进行数据集中异常符号的替换和,但是出现了以下几个问题。

首先我创建一个简单的数据集如下:

example_data = {'A':  ['1', '-', '<0.9'],
        'B': ['3', '19/20','$25']
        }

example_df = pd.DataFrame (example_data, columns = ['A','B'])

接下来使用replace函数进行特殊符号的去除。即把 - / < $ 等特殊符号去除只保留数字。

example_df = example_df.replace('/','', regex=True)
example_df = example_df.replace('$','', regex=True)#只有符号$无法去除?
example_df = example_df.replace('<','', regex=True)
example_df = example_df.replace('-','', regex=True)
example_df

问题1:使用replace函数无法去除符号“$”。请问这种情况应该怎么解决?

 

而且这种办法只适合知道异常符号是什么且异常符号种类很少的情况,如果想一次性替换掉所有特殊符号呢?我查询了很多方法,以下这种方法最接近,但是它一次性去掉了包含特殊符号的单元格的值。

for col in example_df.columns:
    example_df[col].replace(regex=True, inplace=True, to_replace=r'[-@#&$%+/\*<>=]', value=np.nan)


问题2: 请问如何一次性将所有特殊符号去除,并保留其所在单元格内的其他内容?

 

经过处理得到如下数据集:

我想把缺失值使用列中位数进行填补,但是却报错“could not convert string to float: '' ”。好像是因为我把特殊符号替换成了空字符串?

for col in example_df.columns[0:]:
    fill_val = example_df[col].dropna().astype(float).median()
    example_df[col].fillna(fill_val,inplace=True)

问题3: 请问大家这种没有办法转换成数值型的情况下应该怎么用中位数或者平均数填补缺失值?是不是我替换特殊符号的方法还是有问题的?

 

还有一个小问题~我发现如果一个单元格内只有特殊符号,那么使用None进行替换后,他们不会变成空,反而会自动填补上一行的值。请问这个是为什么呢?

#如果一个变量中只有一个特殊符号,填补成为空白之后会自动填补上一行的值?
example_df = example_df.replace('-',None, regex=True)

多谢各位大神!感激不尽!

 

 

 

 

  • 写回答

4条回答 默认 最新

  • 关注

    这个是正则表达式,$在正则表达式中表示一行或整个文本的结尾。

    要替换 $  应该写成 r'\$'

    example_df = example_df.replace(r'\$','', regex=True)#只有符号$无法去除?

    如果想一次性替换掉所有特殊符号

    example_df = example_df.replace(r'[\-@#&\$%+/\\*<>=]','', regex=True)

     

    # 第3个问题要把空字符串替换成pd.NA

    example_df = example_df.replace(r'^\s*$',pd.NA, regex=True)

     

    import pandas as pd
    
    example_data = {'A':  ['1', '-', '<0.9'],
            'B': ['3', '19/20','$25']
            }
    example_df = pd.DataFrame (example_data, columns = ['A','B'])
    
    example_df = example_df.replace(r'[\-@#&\$%+/\\*<>=]','', regex=True)
    
    example_df = example_df.replace(r'^\s*$',pd.NA, regex=True)
    
    print(example_df)
    
    for col in example_df.columns[0:]:
        fill_val = example_df[col].dropna().astype(float).median()
        example_df[col].fillna(fill_val,inplace=True)
    
    print(example_df)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂