Python pandas DataFrame,如何将函数应用于特定列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36213383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:34:06  来源:igfitidea点击:

pandas DataFrame, how to apply function to a specific column?

pythonpandas

提问by GoingMyWay

I have read the docs of DataFrame.apply

我已经阅读了DataFrame.apply的文档

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

DataFrame.apply(func,axis=0,broadcast=False,raw=False,reduce=None,args=(),**kwds)?沿 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

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

我想将 addOne 添加到 中的每个值df['A'],而不是所有列。我怎么能用DataFrame.apply.

Thanks for help!

感谢帮助!

回答by su79eu7k

The answer is,

答案是,

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

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

也许你会更好地了解的区别mapapplymapapply

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

但如果你坚持使用apply,你可以尝试如下。

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

df.apply(addOne, axis=1)

回答by felix_as

One simple way would be:

一种简单的方法是:

df['A'] = df['A'].apply(lambda x: x+1)