【问题标题】:How do I extract data from a DataFrame using regular expressions?如何使用正则表达式从 DataFrame 中提取数据?
【发布时间】:2021-11-17 07:04:17
【问题描述】:

我正在尝试更正 DataFrame 中的数据并且面临值替换问题。原始值采用“31 ^”或“54_”格式,我需要它采用整数格式,例如 31.54

frame = pd.DataFrame({'first': [123, '32^'], 'second': [23,'13_']})
frame['first'] = frame['first'].str.extract(r'([0-9]+)', expand=False)


first   second
0   NaN 23
1   32  13_

【问题讨论】:

    标签: python pandas python-re


    【解决方案1】:

    将Series.str.extract 与fillna 一起使用:

    In [679]: frame['first'] = frame['first'].str.extract('(\d+)').fillna(frame['first'])
    
    In [680]: frame['second'] = frame['second'].str.extract('(\d+)').fillna(frame['second'])
    
    In [681]: frame
    Out[681]: 
      first second
    0   123     23
    1    32     13
    

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多