Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace value if string ends with certain value pandas dataframe

As titled.

I have written my code but it does not work. I wish I can get a more pythonic way of writing the code (in one single line perhaps).

clean_df :

columnA
 123F
 FVGD
 w999Z
 678Q
 6y6yA

My code :

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"

The postfix are constant. Expected outcome :

columnA
 blah
  D
  Z
 blah
  A
like image 765
user6308605 Avatar asked Apr 22 '26 01:04

user6308605


1 Answers

In one line with a list comprehension:

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

The output is :

columnA
 blah
  D
  Z
 blah
  A
like image 58
ljuk Avatar answered Apr 24 '26 16:04

ljuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!