【问题标题】:Replace the pattern in pandas datframe替换熊猫数据框中的模式
【发布时间】:2020-09-07 19:01:39
【问题描述】:

这就是我的数据的样子,

col1,col2,col3,col4
1234,|$||$|,2020|$|2011,|$||$|
5639,|$|,2010|$|2019,|$||$||$|

|$|用作分隔多值列的分隔符。 所以这里出现了多值属性中数据为空的情况。 我需要将其替换为如下所述的空。

col1,col2,col3,col4
1234,,2020|$|2011,
5639,,2010|$|2019,

有人可以在 python 中帮助我吗?

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    假设您已经将数据读入数据框df。试试这个

    df_final = df.replace(r'^(\|\$\|)+$', '', regex=True)
    
    Out[632]:
       col1 col2         col3 col4
    0  1234       2020|$|2011
    1  5639       2010|$|2019
    

    如果要将结果保存到csv 文件,请执行此附加步骤

    df_final.to_csv('t.csv', index=False)
    

    【讨论】:

      【解决方案2】:

      如果您需要删除任何产生空字符串的多余分隔符,您可以试试这个正则表达式(?<=^)(\|\$\|)+|\|\$\|(?=$|\|\$\|),它的作用是匹配位于字符串末尾或后跟另一个分隔符的分隔符:

      (?<=^)(\|\$\|)+|\|\$\|(?=$|\|\$\|)
      ^^^^^^^^^^^^^^^                    match all delimiters from beginning of string
                      ^^^^^^^^^^^^^^^^^  match delimiter if it is at the end of string or followed by 
                                         another delimiter
      

      然后您可以使用.str.replace 删除所有匹配的分隔符:

      print(df)
      #   col1    col2         col3         col4
      #0  1234  |$||$|  2020|$|2011       |$||$|
      #1  5639     |$|  2010|$|2019    |$||$||$|
      #2  5639   |$|33  2010|$|2019  |$||$|22|$|
      #3  5639   22|$|  2010|$|2019  11|$||$||$|
      
      pattern = r"(?<=^)(\|\$\|)+|\|\$\|(?=$|\|\$\|)"
      
      def clean_delim(col):
          if col.dtype == 'object':
              return col.str.replace(pattern, '')
          else:
              return col
              
      print(df.apply(clean_delim))
      
      #   col1 col2         col3 col4
      #0  1234       2020|$|2011     
      #1  5639       2010|$|2019     
      #2  5639   33  2010|$|2019   22
      #3  5639   22  2010|$|2019   11
      

      或者只是将df.replace(pattern, '', regex=True) 当作@Andy

      检查full example here

      【讨论】:

        【解决方案3】:

        将上面的csv转换成dataframe后,可以试试下面吗-

        df.applymap(lambda x: x if all(x.split(r'|$|')) else '')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-02-02
          • 2018-09-29
          • 1970-01-01
          • 2013-02-04
          • 2022-01-11
          • 1970-01-01
          相关资源
          最近更新 更多