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 (...)
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:
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With