Applying function to Pandas dataframe by column

不羁的心 提交于 2019-12-30 11:14:31

问题


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():

回答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')



回答2:


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


来源:https://stackoverflow.com/questions/38013618/applying-function-to-pandas-dataframe-by-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!