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