gpt4 book ai didi

Python - Pandas - 根据现有级别填充缺失数据

转载 作者:太空宇宙 更新时间:2023-11-04 04:52:53 25 4
gpt4 key购买 nike

  • 我使用 pandas 并从 SQL 数据库获取数据
  • 我有两个代码。一个是美国股票,另一个是欧洲股票。两只股票的日期不一定相同(节假日等)。
  • 我的所有数据都存储在一个多索引 DataFrame 中。
  • 希望根据级别填补缺失值

运行下面的代码:

import pandas as pd
import datetime
ticker_date = [('US',datetime.date.today()-datetime.timedelta(3)),
('US',datetime.date.today()-datetime.timedelta(2)),
('US',datetime.date.today()-datetime.timedelta(1)),
('EU',datetime.date.today()-datetime.timedelta(3)),
('EU',datetime.date.today()-datetime.timedelta(1))]
index_df = pd.MultiIndex.from_tuples(ticker_date)
example = pd.DataFrame([12.2,12.5,12.6,15.1,15],index_df,['value'])

输出:

Output from code above

enter image description here

我正在寻找一种方法来 reshape 我的输出,用以前的值填充缺失的数据:

Objective: add a dec 11th line and fill with previous value

enter image description here

最佳答案

我会这样做:

In [24]: idx = pd.MultiIndex.from_product((
example.index.get_level_values(0).unique(),
example.index.get_level_values(1).unique()))

In [25]: example = example.reindex(idx).ffill()

In [26]: example
Out[26]:
value
US 2017-12-10 12.2
2017-12-11 12.5
2017-12-12 12.6
EU 2017-12-10 15.1
2017-12-11 15.1
2017-12-12 15.0

关于Python - Pandas - 根据现有级别填充缺失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47795001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com