2

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 and then call the function e.g.

How to implement something like:

for column in dataframe:
    if column.name != 'manager':
       apply function():

2 Answers 2

3

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

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')
Sign up to request clarification or add additional context in comments.

Comments

1

use drop() and apply():

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

demo:

In [115]: df
Out[115]:
   a  b  c
0  4  5  3
1  6  6  6
2  3  4  1
3  2  1  6
4  8  8  1

In [116]: df.drop('b', axis=1)
Out[116]:
   a  c
0  4  3
1  6  6
2  3  1
3  2  6
4  8  1

In [117]: def func(i):
   .....:     return i ** 2
   .....:

In [118]: df.drop('b', axis=1).apply(func)
Out[118]:
    a   c
0  16   9
1  36  36
2   9   1
3   4  36
4  64   1

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.