1

I've a sample dataframe

id      city
1       Florida
2       Atlanta
3       Manhattan
4       Amsterdam
5       Newyork

I've a function

def my_function(x):
    y = x[::-1]
    return y

How can I make a for loop that uses city column and inserts the reversed string in a column one by one which results the below?

id      city       reversed_string
 1      Florida       adirolF
 2      Atlanta       atnaltA
 3      Manhattan     nattahnaM
 4      Amsterdam     madretsmA
 5      Newyork       kroyweN 

2 Answers 2

2

You can use the fact that a string in Python is an iterable. Note that you do not need apply.

df['reversed_string'] = df.city.str[::-1]
Sign up to request clarification or add additional context in comments.

3 Comments

thanks @gofvonx. I'm just looking for how to use a function iteratively. The objective is not to reverse the string, but how to use a function.
@astroboy1 Thanks for clarifying. I'd still make the point that you can very often get away with not using apply at all (which usually is less efficient and not what should be understood when people talk about "vectorizing").
I see i will keep in mind in the future, it's just apply was one of the more common use case when i am using pandas, thanks for the advice
1

Simple just use an apply without a for loop

df['reversed_string'] = df['city'].apply(lambda x: x[::-1])

If you want to use it with a function

def reverse_string(string):
  return string[::-1]

df['revered_string'] = df['city'].apply(reverse_string)

3 Comments

I don't think that apply is necessary here.
Apply might be necessary, we dont know what the actual usecase/how complicated the function is, upvoted both answer..!!
In hindsight, i'm just suggesting the one possible solutions you can take

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.