python - pandas 将多索引重新索引为更高频率的日期

标签 python pandas

我有一个季度数据的 ID 和日期表,我想将其重新索引为每日(工作日)。

示例表:

enter image description here

我正在尝试找出一种 pythonic 或 pandas 方式来重新索引到更高频率的日期范围,例如每日和向前填充任何 NaN。

到目前为止已经尝试过:

df = pd.read_sql('select date, id, type, value from db_table' con=conn, index_col=['date', 'id', 'type'])
dates = pd.bdate_range(start, end)
new_idx = pd.MultiIndex.from_product([dates, df.index.get_level_values(1), df.index.get_level_values(2)]
new_df = df.reindex(new_idx)

#this just hangs
new_df = new_df.groupby(level=1).fillna(method='ffill')

无济于事。我要么得到一个

异常:无法处理非唯一的多重索引!

或者,如果 ID 和类型之间的日期一致,则各个日期会重复多次(这听起来像是一个错误?)

最终,我只想按日期、ID 和类型对表进行分组,并在 ID 和类型之间拥有一致的日期索引。

有没有办法在 pandas 中做到这一点?

最佳答案

是的,您可以使用合并

new_idx_frame=new_idx.to_frame()
new_idx_frame.columns=['date', 'id', 'type']
Yourdf=df.reset_index().merge(new_idx_frame,how='right',sort =True).groupby('id').ffill()# here I am using toy data 
Out[408]: 
   id  date  type     value
0   1     1     1       NaN
1   1     1     2       NaN
2   2     1     1  666666.0
3   2     1     2   99999.0
4   1     2     1      -1.0
5   1     2     1      -1.0
6   1     2     2      -1.0
7   2     2     1   99999.0
8   2     2     2   99999.0
<小时/>

示例数据

df=pd.DataFrame({'date':[1,1,2,2],'id':[2,2,1,1],'type':[2,1,1,1],'value':[99999,666666,-1,-1]})
df=df.set_index(['date', 'id', 'type'])
new_idx = pd.MultiIndex.from_product([[1,2], [1,2],[1,2]])

关于python - pandas 将多索引重新索引为更高频率的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55436896/

相关文章:

python - numpy 数组中每个元素的邻居加权数组

python - LOAD DATA LOCAL INFILE sqlalchemy 和 python 到 mysql 数据库

python - Postgres+SQLAlchemy 在使用 default=func.now() 时将时间转换为 UTC

python - 在 Python 中与 Pandas 进行大型合并时出现 MemoryError

python - Numpy 和 Pandas - 用零填充 reshape

python - 使用许多 Pandas 列创建一个新列的字符串格式

python - 如何从 Dask 数据框中选择值等于组最小值的所有行

python - pandas 内的 np reshape 应用

python - Callable 是无效的基类?

python - 创建新表(模型)并将其与 Django 中的 auth_user 相关联