pandas 使用函数在pandas df中添加一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40045632/
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-09-14 02:13:09  来源:igfitidea点击:

Adding a column in pandas df using a function

pythonfunctionpandasdataframeyahoo

提问by RageAgainstheMachine

I have a Pandas df [see below]. How do I add values from a function to a new column "price"?

我有一个 Pandas df [见下文]。如何将函数中的值添加到新列“价格”?

function:

    def getquotetoday(symbol):
        yahoo = Share(symbol)
        return yahoo.get_prev_close()

df:

Symbol    Bid      Ask
MSFT     10.25   11.15
AAPL     100.01  102.54


  (...)

回答by scomes

In general, you can use the apply function. If your function requires only one column, you can use:

通常,您可以使用 apply 函数。如果您的函数只需要一列,您可以使用:

df['price'] = df['Symbol'].apply(getquotetoday)

as @EdChum suggested. If your function requires multiple columns, you can use something like:

正如@EdChum 建议的那样。如果您的函数需要多列,您可以使用以下内容:

df['new_column_name'] = df.apply(lambda x: my_function(x['value_1'], x['value_2']), axis=1)