48

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
...
0

2 Answers 2

93

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)
Sign up to request clarification or add additional context in comments.

Comments

0

Alternatively you can use pipe:

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

1 Comment

This assumes Share works on a Series. Is that reasonable? I'm not familiar with whatever library OP's using. If it is, why bother when you could just do df['price'] = getquotetoday(df['Symbol'])? If it isn't, maybe you're thinking of map?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.