1

How can I use function with pandas dataframe. For example:

a       | b
london  | uk
newyork | usa
berlin  | germany

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

def doSomething(df1):
    return df1

doSomething() will return both columns a and b, But how do I return say only a?

def doSomething(df1):
    return df1.a 

df1.applymap(doSomething)

AttributeError: ("'str' object has no attribute 'a'", u'occurred at index a')
4
  • 1
    df1['a'] does not work ? Commented Dec 7, 2016 at 11:10
  • applymap calls the function on every element of the dataframe Commented Dec 7, 2016 at 11:11
  • @MMF no it does not. I'm getting TypeError: ('string indices must be integers, not str', u'occurred at index a') Commented Dec 7, 2016 at 11:11
  • @DevEx Check my answer Commented Dec 7, 2016 at 11:24

2 Answers 2

1

You can use:

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

print (df)
df1 = df[['a', 'b']]

def doSomething(x):
    return x.a

#function works with DataFrame 
print (doSomething(df1))
0     london
1    newyork
2     berlin
Name: a, dtype: object

#function works with Series, columns are transformed to index of Series
#return for each row value of Series with index a which is transformed to column in output df
print (df1.apply(doSomething, axis=1))
0     london
1    newyork
2     berlin
dtype: object

If need applymap it works with each element of df:

def doSomething(x):
    return x + '___'

#function works with element
print (df1.applymap(doSomething))
            a           b
0   london___       uk___
1  newyork___      usa___
2   berlin___  germany___
Sign up to request clarification or add additional context in comments.

Comments

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

def doSomething(df):
df2 = df['a']
return df2

df3 = df1.apply(doSomething, axis=1)
df3 = pd.DataFrame(df3).rename(columns={0: 'a'})

Comments

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.