我正在尝试向索引为 DateTime 的数据框添加其他行,但不知道如何执行此操作
AAPL=yf.download('AAPL')
AAPL=AAPL['Adj Close']
AAPL.loc[len(AAPL.index)]=['2021-12-04',0]
这是我收到的错误消息
TypeError: cannot insert DatetimeArray with incompatible label
最佳答案
你最好先将日期string
转换为pandas中的datetime
对象类型,然后做你想做的事情。
这是你的方法:
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)
这是我处理这个问题的方法:
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)
输出
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
关于python - 添加额外的行到数据框,其中日期是索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70574257/