Jeff Tilton
Jeff Tilton

Reputation: 1296

Pandas apply function to dataframe index series within dataframe

I want to create a function that uses columns of a dataframe as input. Part of this input will be a series.

So it would function like the below

def myFunc(input1, input2, s_input):
    for s in s_input['c':'d'].index:
       print s + str(s_input[s]) +str(input1)
    for s in s_input['e':].index:
        print s + str(s_input[s]) +str(input2)

s = pd.Series({'a':1,'b':4,'c':7,'d':11,'e':15,'f':22})   

input1=' input1'
input2 =' input2'

myFunc(input1,input2,s) 

c7 input1
d11 input1
e15 input2
f22 input2

I want to apply this to a dataframe like

df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6],'c':[7,8,9],'d':[11,12,13], 'e':[11,23,33], 'f':[75,44,55]})    

df.apply(lambda x: myFunc(df.a,df.b, df.loc[x.index,'c':]))

Upvotes: 0

Views: 519

Answers (1)

pansen
pansen

Reputation: 6663

If you want to apply your function row-wise here, use axis = 1 on the apply:

df.apply(lambda x: myFunc(x.a, x.b, x.loc['c':]), axis=1)

# gets printed...
c71
d111
e114
f754
c82
d122
e235
f445
c93
d133
e336
f556

However, you usually employ apply to return values. At the moment, your function does not return anything.

Upvotes: 1

Related Questions