本文介绍了使用函数在pandas df中添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个熊猫df [见下文].如何将函数中的值添加到新的价格"列中?
I have a Pandas df [see below].How do I add values from a function to a new column "price"?
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
(...)
推荐答案
通常,您可以使用apply函数.如果您的函数只需要一列,则可以使用:
In general, you can use the apply function. If your function requires only one column, you can use:
df['price'] = df['Symbol'].apply(getquotetoday)
如@EdChum建议.如果您的函数需要多个列,则可以使用类似以下内容的
as @EdChum suggested. If your function requires multiple columns, you can use something like:
df['new_column_name'] = df.apply(lambda x: my_function(x['value_1'], x['value_2']), axis=1)
这篇关于使用函数在pandas df中添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!