Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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     (...) 
like image 376
RageAgainstheMachine Avatar asked Oct 14 '16 14:10

RageAgainstheMachine


People also ask

How to add a new column to a pandas Dataframe?

You can use the assign () function to add a new column to the end of a pandas DataFrame: df = df.assign(col_name= [value1, value2, value3, ...]) And you can use the insert () function to add a new column to a specific location in a pandas DataFrame:

How do I apply a function to a column or Dataframe?

This article will introduce how to apply a function to a column or an entire dataframe. Both apply () and transform () methods operate on individual columns and the whole dataframe. The apply () method applies the function along a specified axis.

What is the difference between apply() and transform() methods in pandas?

The apply () method applies the function along a specified axis. It passes the columns as a dataframe to the custom function, whereas a transform () method passes individual columns as pandas Series to the custom function.

How do I compare tweets in a Dataframe in pandas?

We’ll do that using a Boolean filter: Now that we've created those, we can use built-in pandas math functions like .mean () to quickly compare the tweets in each DataFrame. We'll use print () statements to make the results a little easier to read.


1 Answers

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) 
like image 147
scomes Avatar answered Oct 02 '22 04:10

scomes