Navid
Navid

Reputation: 106

Pandas : Apply function on multiple columns

I'm trying to add a new column calculated from first quartile of all columns. something like this:

df['Q25']=df[col].apply(lambda x: np.percentile(x, 25) ,axis =1)
#col = ['1', '2','3',..'29'] days in one month

and this is the error I receive:

KeyError: "['1' '2' '3' '4' '5' '6' '7' '8' '9' '10' '11' '12' '13' '14' '15' '16'\n '17' '18' '19' '20' '21' '22' '23' '24' '25' '26' '27' '28' '29'] not in index"

I understand that error shows python is trying to find passed list (col) in the index, instead of columns itself but I don't know how should I fix it. I already added axis=1 but with no luck.

PS. I can't add column manually like df['1'], df['2'] since the total number (in this case 29) changes in other cases.

Upvotes: 0

Views: 537

Answers (1)

MMF
MMF

Reputation: 5931

Try this out :

df['Q25']= [np.percentile(df.loc[i,:], 25) for i in df.index]

Upvotes: 1

Related Questions