python - 如何使用 Python 重新采样

标签 python pandas

我有一个数据框,如下所示。

import pandas as pd

frame = pd.DataFrame({"a":range(7),'b':range(7,0,-1),
'id':['one','one','two','two','two','three','four'],
'date':['2019-05-01','2019-05-08','2019-05-01','2019-05-08','2019-05-15','2019-05-01','2019-05-15']})
print(frame)
pd.to_datetime(frame['date'],yearfirst=True)

看起来像:

0  7    one  2019-05-01
1  6    one  2019-05-08
2  5    two  2019-05-01
3  4    two  2019-05-08
4  3    two  2019-05-15
5  2  three  2019-05-01
6  1   four  2019-05-15

我希望每个 id 都有三行日期。

预期的数据帧是:

0  7    one  2019-05-01
1  6    one  2019-05-08
1  6    one  2019-05-15
2  5    two  2019-05-01
3  4    two  2019-05-08
4  3    two  2019-05-15
5  2  three  2019-05-01
5  2  three  2019-05-08
5  2  three  2019-05-15
NA NA   four  2019-05-01
NA NA   four  2019-05-08
6 1   four  2019-05-15

如何使用重新采样来获取此数据帧? 谢谢!

最佳答案

用途:

frame['date'] = pd.to_datetime(frame['date'],yearfirst=True)

#create MultiIndex by unique values of both columns
mux = pd.MultiIndex.from_product([frame['id'].unique(), 
                                  frame['date'].unique()], names=['id','date'])

#add missing rows by reindex and per groups forward filling missing values
frame = (frame.set_index(['id','date'])
              .reindex(mux)
              .groupby(level=0)
              .ffill()
              .drop('id', axis=1)
              .reset_index()
              )

print (frame)
       id       date    a    b
0     one 2019-05-01  0.0  7.0
1     one 2019-05-08  1.0  6.0
2     one 2019-05-15  1.0  6.0
3     two 2019-05-01  2.0  5.0
4     two 2019-05-08  3.0  4.0
5     two 2019-05-15  4.0  3.0
6   three 2019-05-01  5.0  2.0
7   three 2019-05-08  5.0  2.0
8   three 2019-05-15  5.0  2.0
9    four 2019-05-01  NaN  NaN
10   four 2019-05-08  NaN  NaN
11   four 2019-05-15  6.0  1.0

关于python - 如何使用 Python 重新采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56274787/

相关文章:

python - Python 中的等效 gprnd(MATLAB) 方法

python - Django表单,表单字段的继承和顺序

python - 查找数组中最小值的索引,其中相同的索引在另一个数组中指向零

python : How to create columns from words occurred in a column?

python - 根据另一列中的两行计算数据框列

python - 并行处理数据帧

python - 如何将 Pandas 中的数据帧设为 "unconcatenate"?

不使用 yield 的 python 生成器无尽的流

python - Google Collab Notebook与普通的Python脚本创建了不同类型的绘图大小

pandas - dask read_sql_table 在具有数字日期时间的 sqlite 表上失败