replace string if length is less than x

2024/10/7 12:25:40

I have a dataframe below.

a = {'Id': ['ants', 'bees', 'cows', 'snakes', 'horses'], '2nd Attempts': [10, 12, 15, 14, 0],'3rd Attempts': [10, 10, 9, 11, 10]}
a = pd.DataFrame(a)
print (a)

I want to able add text ('-s') to anything which is equal to 4 characters. i have unsuccessfully tried the below. as it produces the error, ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

if a['Id'].str.len() == 3:a['Id'] = a['Id'].str.replace('s', '-s')
else:pass
Answer

I think you need loc, if need replace last s is necessary add $:

mask = a['Id'].str.len() == 4
a.loc[mask, 'Id'] = a.loc[mask, 'Id'].str.replace('s$', '-s')
print (a)2nd Attempts  3rd Attempts      Id
0            10            10   ant-s
1            12            10   bee-s
2            15             9   cow-s
3            14            11  snakes
4             0            10  horses

Solution with mask:

mask = a['Id'].str.len() == 4
a.Id = a.Id.mask(mask, a.Id.str.replace('s$', '-s'))
print (a)2nd Attempts  3rd Attempts      Id
0            10            10   ant-s
1            12            10   bee-s
2            15             9   cow-s
3            14            11  snakes
4             0            10  horses
https://en.xdnf.cn/q/70244.html

Related Q&A

Convert ast node into python object

Given an ast node that can be evaluated by itself, but is not literal enough for ast.literal_eval e.g. a list comprehensionsrc = [i**2 for i in range(10)] a = ast.parse(src)Now a.body[0] is an ast.Expr…

Keras custom loss function (elastic net)

Im try to code Elastic-Net. Its look likes:And I want to use this loss function into Keras:def nn_weather_model():ip_weather = Input(shape = (30, 38, 5))x_weather = BatchNormalization(name=weather1)(ip…

Django Models / SQLAlchemy are bloated! Any truly Pythonic DB models out there?

"Make things as simple as possible, but no simpler."Can we find the solution/s that fix the Python database world?Update: A lustdb prototype has been written by Alex Martelli - if you know a…

Fabric Sudo No Password Solution

This question is about best practices. Im running a deployment script with Fabric. My deployment user deploy needs sudo to restart services. So I am using the sudo function from fabric to run these com…

cartopy: higher resolution for great circle distance line

I am trying to plot a great circle distance between two points. I have found an in the cartopy docs (introductory_examples/01.great_circle.html):import matplotlib.pyplot as plt import cartopy.crs as cc…

Python Flask date update real-time

I am building a web app with Python Flask with JavaScript. I am a beginner of Javascript.The process I do now:In Flask Python code, 1. I get data by scrapping the web (numeric data that updates every m…

How do I force pip to install from the last commit of a branch in a repo?

I want pip to install from the latest commit on a master branch of my github repository. I tried many options mentioned here on StackOverflow, none helped. For instance, that does not work:pip install …

Emacs: pass arguments to inferior Python shell during buffer evaluation

recently I started using Emacs as a Python IDE, and it not quite intuitive... The problem I am struggling with right now is how to pass command line arguments to the inferior python shell when the buff…

How to edit a wheel package (.whl)?

I have a python wheel package, when extracted I find some python code, Id like to edit this code and re-generate the same .whl package again and test it to see the edits .. How do I do that?

Choosing order of bars in Bokeh bar chart

As part of trying to learn to use Bokeh I am trying to make a simple bar chart. I am passing the labels in a certain order (days of the week) and Bokeh seems to be sorting them alphabetically. How ca…