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 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')
Post a Comment for "Applying Function To Pandas Dataframe By Column"