3

This is a follow up of the question here: How to modify a dataframe using function? Lets say I want to make call .upper() on values in a

df = pd.DataFrame({'a':['london','newyork','berlin'],
                   'b':['uk','usa','germany'],
                   'c':[7,8,9]})

df1 = df[['a', 'b']]

def doSomething(x):
    return x.a

print (df1.apply(doSomething, axis=1))
0     london
1    newyork
2     berlin
dtype: object

call `.upper()` on values in `a`:
return 
0     LONDON
1     NEWYORK
2     BERLIN
dtype: object

1 Answer 1

6

You can call function for column a:

def doSomething(x):
    return x.upper()

print (df1.a.apply(doSomething))
0     LONDON
1    NEWYORK
2     BERLIN
Name: a, dtype: object

print (df1.a.apply(lambda x: x.upper()))
0     LONDON
1    NEWYORK
2     BERLIN
Name: a, dtype: object

Also it works with:

def doSomething(x):
    return x.a.upper()

print (df1.apply(doSomething, axis=1))
0     LONDON
1    NEWYORK
2     BERLIN
dtype: object

but better is use str.upper which works perfectly with NaN values:

print (df1.a.str.upper())
0     LONDON
1    NEWYORK
2     BERLIN
Name: a, dtype: object

If need add new column:

df['c'] = df1.a.str.upper()
print (df)
         a        b        c
0   london       uk   LONDON
1  newyork      usa  NEWYORK
2   berlin  germany   BERLIN
Sign up to request clarification or add additional context in comments.

3 Comments

How to add column c to this newly modified dataframe ?
thank you. Is it possible to add c in the apply solution?
Yes, same way like df1['c'] = df1.a.apply(doSomething) or df1['c'] = df1.apply(doSomething, axis=1)...

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.