Adding additional rows to dataframe where date is the index

0

Issue

Im trying to add additional rows to a data frame where the index is DateTime and am not sure how to go about doing this

AAPL=yf.download('AAPL')
AAPL=AAPL['Adj Close']
AAPL.loc[len(AAPL.index)]=['2021-12-04',0]

This is the error message i recieved

TypeError: cannot insert DatetimeArray with incompatible label

Solution

You had better first convert your date string to a datetime object type in pandas and then do whatever you want.
This is your method:

import pandas as pd
import yfinance as yf

AAPL = yf.download('AAPL')
AAPL = AAPL['Adj Close']
AAPL.loc[pd.to_datetime('2021-12-04')] = 0
# This is also acceptable
# AAPL.loc['2021-12-04'] = 0
print(AAPL)

And Here is my method to cope with this:

import pandas as pd
import yfinance as yf

AAPL = yf.download('AAPL')
AAPL = AAPL[['Adj Close']]
AAPL = AAPL.append(pd.DataFrame(0, index=[pd.to_datetime('2021-12-04')], columns=AAPL.columns))
print(AAPL)

Output

             Adj Close
1980-12-12    0.100453
1980-12-15    0.095213
1980-12-16    0.088224
1980-12-17    0.090408
1980-12-18    0.093029
...                ...
2021-12-30  178.199997
2021-12-31  177.570007
2022-01-03  182.009995
2022-01-04  179.699997
2021-12-04    0.000000

Answered By – AlirezaAsadi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More