Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

python - Adding a column in pandas df using a function

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


  (...)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...