代码之家  ›  专栏  ›  技术社区  ›  Lynn

使用Pandas[重复]对数据帧进行多个特殊字符转换

  •  0
  • Lynn  · 技术社区  · 3 年前

    我希望在一列中保持连字符之前的所有内容,在另一列中使用Pandas保持冒号之前的所有信息。

    数据

    ID            Type               Stat
    
    AA - type2    AAB:AB33:77:000    Y
    CC - type3    CCC:AB33:77:000    N
    

    渴望的

    ID    Type
    
    AA    AAB
    CC    CCC
    

    正在执行

    separator = '-'
    result_1 = my_str.split(separator, 1)[0]
    

    欢迎提出任何建议

    2 回复  |  直到 3 年前
        1
  •  1
  •   Tim Biegeleisen    3 年前

    我们可以尝试使用 str.extract 在这里:

    df["ID"] = df["ID"].str.extract(r'(\w+)')
    df["Type"] = df["Type"].str.extract(r'(\w+)')
    
        2
  •  1
  •   rafidini    3 年前

    我想说

    func1 = lambda _: _['ID'].split('- ')[0]
    func2 = lambda _: _['Type'].split(':')[0]
    
    data\
      .assign(ID=func1)\
      .assign(Type=func2)
    

    工具书类 https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.assign.html