astroboy1
astroboy1

Reputation: 197

add a column to the dataframe using a loop in python pandas

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 

Upvotes: 1

Views: 62

Answers (2)

Edwin Cheong
Edwin Cheong

Reputation: 979

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)

Upvotes: 1

gofvonx
gofvonx

Reputation: 1439

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]

Upvotes: 2

Related Questions