'Access certain values in python pandas
The following code gives me.
import yfinance as yf
import pandas as pd
tickers = ['AAPL', 'MSFT', 'AMZN']
start_date = datetime.date(2019, 1, 2)
end_date = datetime.date(2020, 1, 1)
delta = datetime.timedelta(days=21)
tickers = ['AAPL', 'MSFT', 'AMZN']
daily_data = yf.download(tickers, start=start_date, end=end_date)
daily_data = daily_data['Adj Close'].dropna()
f = [v for _, v in daily_data.groupby(pd.Grouper(freq='M'))]
for i in f:
z = i.pct_change().mean()
print(z)
my question is then how do I store/ split the above output up. So for example how do i access the first 3 values?
Thanks in advance
Solution 1:[1]
Instead of just printing the mean, you could store those values into a dataframe and then get the top 3 values using head(). See code below.
df = pd.DataFrame(columns=['AAPL','AMZN', 'MSFT'])
for i in f:
z = i.pct_change().mean()
df.loc[-1] = [z['AAPL'], z['AMZN'], z['MSFT']]
df.index = df.index + 1
df = df.sort_index()
print(df.head(3))
Output:
AAPL AMZN MSFT
0 0.005355 0.001892 0.002672
1 0.002492 0.000307 0.002928
2 0.004748 0.001112 0.002121
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manjunath K Mayya |

