pandas DataFrame,如何将功能应用于特定列? [英] pandas DataFrame, how to apply function to a specific column?

查看:65
本文介绍了pandas DataFrame,如何将功能应用于特定列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读 DataFrame.apply

DataFrame.apply(func,axis = 0,广播= False,raw = False,reduce = None,args =(),** kwds)¶ 沿DataFrame的输入轴应用功能.

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)¶ Applies function along input axis of DataFrame.

那么,如何将函数应用于特定列?

So, How can I apply a function to a specific column?

In [1]: import pandas as pd
In [2]: data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
In [3]: df = pd.DataFrame(data)
In [4]: df
Out[4]: 
   A  B  C
0  1  4  7
1  2  5  8
2  3  6  9
In [5]: def addOne(v):
...:        v += 1
...:        return v
...: 
In [6]: df.apply(addOne, axis=1)
Out[6]: 
   A  B   C
0  2  5   8
1  3  6   9
2  4  7  10

我想为df['A']中的每个值而不是所有列添加一个.我该怎么用DataFrame.apply.

I want to addOne to every value in df['A'], not all columns. How can I do that with DataFrame.apply.

感谢您的帮助!

推荐答案

答案是

df['A'] = df['A'].map(addOne)

,也许您会更好地了解区别(mapapplymapapply).

and maybe you would be better to know about the difference of map, applymap, apply.

但是如果您坚持使用apply,则可以尝试以下操作.

but if you insist to use apply, you could try like below.

def addOne(v):
    v['A'] += 1
    return v

df.apply(addOne, axis=1)

这篇关于pandas DataFrame,如何将功能应用于特定列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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