DevEx
DevEx

Reputation: 4561

Use function to modify pandas dataframe

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

Upvotes: 3

Views: 3810

Answers (1)

jezrael
jezrael

Reputation: 862431

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

Upvotes: 6

Related Questions