Adding a column in pandas df using a function

こ雲淡風輕ζ 提交于 2020-01-01 04:29:40

问题


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


  (...)

回答1:


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

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

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)


来源:https://stackoverflow.com/questions/40045632/adding-a-column-in-pandas-df-using-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!