python - 添加额外的行到数据框,其中日期是索引

标签 python dataframe

我正在尝试向索引为 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/

相关文章:

python - 有包含列表的 Pandas 列,如何将唯一的列表元素转换为列?

python - 在 Python 中使用列名构建 DataFrame

python - 如何同时将函数与 if 语句应用于多个数据帧列

python - 使用 xhtml2pdf Django 从 HTML 页面获取 PDF

python - scikit-learn MinMax 缩放器无法缩放

python - 将数据框的多列值合并到一个中间带有括号的列中

python - 如何展平 pandas 数据框多列中的字典列表

python - 填充来自另一个 DataFrame 的 NaN 值(具有不同的形状)

python - 将多个 HDF5 文件的数据集合并为一个虚拟数据集

python - 在 CPU 上运行 tf.slim 评估循环