通过列将函数应用于 pandas 数据帧 [英] Applying function to Pandas dataframe by column

查看:126
本文介绍了通过列将函数应用于 pandas 数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想要应用于大熊猫数据框的某些列的功能。
所以我不想明确说明这些列,我想动态地选择我想要的列,然后调用函数,例如



如何实现类似于<数据框中列的

  
如果column.name!='manager':
apply function()


解决方案

我想你可以先找到所有列c $ c> list comprehension 然后 申请 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)
ABCDEF
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如果col!='B']
print(cols)
['A','C','D','E','F']

def func(x):
return x + 1

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

print(df)
ABCDEF
0 2 4 8 2 6 8
1 3 5 9 4 4 5
2 4 6 10 6 7 4

布尔索引的另一个解决方案:

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


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

解决方案

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

这篇关于通过列将函数应用于 pandas 数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆