python - 如果字符串以特定值 Pandas 数据框结尾,则替换值

标签 python regex pandas dataframe

如题。
我已经写了我的代码,但它不起作用。我希望我能得到一种更 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

最佳答案

在一行中使用列表理解:

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

关于python - 如果字符串以特定值 Pandas 数据框结尾,则替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65031781/

相关文章:

python - Python 中的实验设计 (DoE)?

python - 使用Python替换JSON文件中的单词

python - 数据帧中的贝叶斯平均

python - 根据时间戳将 txt 文件数据分割成 24 小时的 block

Python 并且不是 None

python - 正则表达式 : Finding alpha numeirc sub-strings but not strictly alphabetic and might be fully numeric

regex - 使用正则表达式模式会产生编译错误 “Invalid regular expression”

java - 正则表达式查找字符串是否包含给定的 xml 元素

python - 类型错误 : unsupported operand type(s) for -: 'str' and 'str' in python 3. x python

python - Pandas 对列进行四舍五入以获得精确值