Python 将日期时间序列合并到多索引数据帧
我有一个多索引数据框:Python 将日期时间序列合并到多索引数据帧,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个多索引数据框: tuples = list(zip(*[ ['8000', '8000', '8000', '8100', '8100', '8200'], ['2021-04-02', '2021-04-05', '2021-04-06', '2021-04-02', '2021-04-10', '2021-04-28'] ])) idx = pd.MultiIndex.from_tuples(tuples, names=['cardNumber', 'date_on
tuples = list(zip(*[
['8000', '8000', '8000', '8100', '8100', '8200'],
['2021-04-02', '2021-04-05', '2021-04-06', '2021-04-02', '2021-04-10', '2021-04-28']
]))
idx = pd.MultiIndex.from_tuples(tuples, names=['cardNumber', 'date_only'])
values = [4, 4, 2, 5, 1, 2]
df = pd.DataFrame(data=values, index=idx, columns=['Count'])
df.index = df.index.set_levels([df.index.levels[0], pd.to_datetime(df.index.levels[1])])
我还有一系列关于四月的日子:
april_days = pd.date_range(start='2021-04-01', end='2021-04-30').to_series(index=None, name='Date')
在df
中,并非每天都显示,因此我想将april\u days
与df
合并,这样如果没有观察到,就会有一个空值
我尝试了
merge
,但运气不好,concat
其中axis=1
,但也不起作用。如何组合这两个数据集?一个可能的解决方案是基于现有数据创建一个新索引并重新索引数据帧。注意,对于此解决方案,我不会为4月日创建序列对象:
april_days = pd.date_range(start='2021-04-01', end='2021-04-30')
为了创建新索引,我在4月份的每个日期重复cardNumber索引:
idx_1 = df.index.levels[0].repeat(len(april_days))
之后,我创建了一个新的时间索引。因此,我重复了三次四月日,因为有三个卡号。注意,这里您需要另一种方法来重复,因为否则4月的日期将具有以下顺序[01.04,01.04,01.04,02.04,…]
。但是我们需要[01.04,02.04,…,30.04,01.04,…]
。因此,我使用以下方法:
import numpy as np
idx_time = np.array([april_days.values] * 3).flatten()
现在,我可以创建新的多重索引:
idx = list(zip(idx_1, idx_time))
并对现有数据帧重新编制索引:
df.reindex(idx)
完美的非常感谢。我使用以下代码使时间索引成为动态的
num\u unique\u cardname=len(df.index.levels[0])
idx\u time=np.array([april\u days.values]*num\u unique\u cardname)。展平()