Skip to content Skip to sidebar Skip to footer

Applying Function To Pandas Dataframe By Column

I have a function which I want to apply to certain columns of a pandas dataframe. So rather than explicitly stating the columns, I want to dynamically select the columns I want an

Solution 1:

I think you can first find all columns by list comprehension and then applyfunc:

import pandas as pd

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

cols = [col for col in  df.columns if col != 'B']
print (cols)
['A', 'C', 'D', 'E', 'F']

def func(x):
    return x + 1

df[cols] = df[cols].apply(func)

print (df)
   A  B   C  D  E  F
0  2  4   8  2  6  8
1  3  5   9  4  4  5
2  4  6  10  6  7  4

Another solution with boolean indexing:

cols = df.columns[df.columns != 'B']
print (cols)
Index(['A', 'C', 'D', 'E', 'F'], dtype='object')

Solution 2:

use drop() and apply():

df.drop('manager', axis=1).apply(func)

demo:

In[115]: dfOut[115]:
   abc04531666234132164881In[116]: df.drop('b', axis=1)
Out[116]:
   ac043166231326481In[117]: deffunc(i):
   .....:     returni ** 2
   .....:

In[118]: df.drop('b', axis=1).apply(func)
Out[118]:
    ac01691363629134364641

Post a Comment for "Applying Function To Pandas Dataframe By Column"