【问题标题】:replace value if string ends with certain value pandas dataframe如果字符串以某个值熊猫数据框结尾,则替换值
【发布时间】:2021-03-09 21:48:11
【问题描述】:

如标题。

我已经编写了我的代码,但它不起作用。我希望我能获得一种更 Pythonic 的方式来编写代码(也许在一行中)。

clean_df:

columnA
 123F
 FVGD
 w999Z
 678Q
 6y6yA

我的代码:

postfix = ["A", "D", "Z", "P"]

for value in postfix:
    if cleaned_data['columnA'].str.endswith(value) is True:
        cleaned_data['columnA'] = value
    else:
        cleaned_data['columnA'] = "blah"

postfix 是不变的。预期结果:

columnA
 blah
  D
  Z
 blah
  A

【问题讨论】:

    标签: python regex pandas dataframe


    【解决方案1】:

    您可以在此处使用pd.Series.str.extract 尝试此操作。

    pat = "|".join(postfix)
    pat = f"({pat}$"
    df['columnA'] = df['columnA'].str.extract(pat, expand=False).fillna('blah')
    df
      columnA
    0    blah
    1       D
    2       Z
    3    blah
    4       A
    

    【讨论】:

      【解决方案2】:

      一个简单的单行将是

      df['columnA'] = np.where(df.columnA.str[-1].isin(postfix), df.columnA.str[-1], 'blah')
      

      np.where 接受一个条件,如果条件为真则取值,如果条件为假则取值。

      或

      在纯熊猫中,不使用 numpy,它会是

      df['columnA'] = df.columnA.str[-1].where(df.columnA.str[-1].isin(postfix), 'blah')
      

      【讨论】:

        【解决方案3】:

        你可以使用numpy.where:

        注意:str.endswith 也接受 tuple。

        In [3933]: import numpy as np
        
        In [3934]: df.columnA = np.where(df.columnA.str.endswith(tuple(postfix)), df.columnA.str[-1], 'blah')
        
        In [3935]: df
        Out[3935]: 
          columnA
        0    blah
        1       D
        2       Z
        3    blah
        4       A
        

        【讨论】:

          【解决方案4】:

          在一行中包含列表理解:

          postfix = ["A", "D", "Z", "P"]
          cleaned_data['columnA'] = [value[-1] if value[-1] in postfix else "blah" for value in cleaned_data['columnA']]
          

          输出是:

          columnA
           blah
            D
            Z
           blah
            A
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-11-09
            • 1970-01-01
            • 2019-05-09
            • 1970-01-01
            • 1970-01-01
            • 2015-10-29
            • 2021-09-07
            相关资源
            最近更新 更多