Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas: pass a large number of columns to a function using a list containing the column names

Is it possible to store the names of certain columns in a list? Then use that list to pass those columns’ values into a function using apply().

Suppose I was passing 10 columns to a function (df.A to df.J) and I had a list containing the names of the columns A through J.

df['H'] = df.apply(lambda x: myfunction(x.A, x.B, x.C, x.D ... ), axis=1)

How could I write that using the list instead of having to type out each column?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can pass columns names in list cols and then * for unpacking:

np.random.seed(26)

df = pd.DataFrame(np.random.randint(10, size=(3,3)), columns=list('ABC'))
print (df)
   A  B  C
0  5  6  0
1  1  6  3
2  0  4  2

def myfunction(a,b,c):
    return (a,b,c)

cols = ['A','B','C']
df['out'] = df[cols].apply(lambda x: myfunction(*x), axis=1)
print (df)
   A  B  C        out
0  5  6  0  (5, 6, 0)
1  1  6  3  (1, 6, 3)
2  0  4  2  (0, 4, 2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading