我正在嘗試將其他行添加到索引為 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
uj5u.com熱心網友回復:
您最好先將日期轉換string為datetimePandas 中的物件型別,然后做任何您想做的事情。這是你的方法:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/403840.html
標籤:
上一篇:根據找到的相同措辭協調PandasDataframe
下一篇:pandasdf中的條件計數
