Adding A Label Column To A Dataframe
I have a data frame where I get the stocks data (OHLC) and date as index. However, the ticker name is not shown there. So, data looks something like this : open
Solution 1:
I'm not familiar with the iexfinance
library. But Let's say you have a magic function get_data_from_ticker
which, as the name implies, gets data given a ticker input, possibly as a pd.DataFrame
object.
Given a list tickers
, your current process may look like:
dfs = []
for ticker in tickers:
data = get_data_from_ticker(ticker)
dfs.append(data)
df = pd.concat(dfs)
This isn't particularly useful if the ticker information is not stored in your dataframe. So you can use pd.DataFrame.assign
to add a series accordingly:
dfs = []
for ticker in tickers:
data = get_data_from_ticker(ticker)
dfs.append(data.assign(ticker=ticker))
df = pd.concat(dfs)
Finally, you can make this a more efficient by using a list comprehension:
dfs = [get_data_from_ticker(ticker).assign(ticker=ticker) for ticker in tickers]
df = pd.concat(dfs)
Post a Comment for "Adding A Label Column To A Dataframe"