我有一个像这样的DataFrame:
a = date | user | value
-------------------------
2017-05-01 | AAA | 1
2017-05-02 | AAA | 2
... | AAA | ...
2017-08-31 | AAA | 1.7
2017-05-01 | BBB | 1.5
2017-05-02 | BBB | 3
... | BBB | ...
2017-08-31 | BBB | 2.7
另外,我有一个像这样的列表:
b = start_date | user
-----------------
2017-05-02 | AAA
2017-05-05 | AAA
2017-05-03 | BBB
我现在想从包含从b中给出的b中给出的start_date开始的3个下一个日期的列表中提取三维矩阵。所以在上面的例子中如下:
[
[[2017-05-02, AAA, 2], [2017-05-03, AAA, x], [2017-05-04, AAA, x]],
[[2017-05-05, AAA, 2], [2017-05-06, AAA, x], [2017-05-07, AAA, x]],
[[2017-05-03, BBB, 2], [2017-05-04, BBB, x], [2017-05-05, BBB, x]],
]
x代表一个随机值,我只是懒得输入所有的例子。
我使用的是Python 3.5。非常感谢提前。我很期待你的明智答案: - )
答案 0 :(得分:2)
试试这个..同时查看link关于'如何制作好的可重复的熊猫示例'
DF=pd.merge(df1,df2,on='user',how='outer')
DF['DIFF']=DF['date_x']-DF['date_y']
DF=DF.loc[(DF.DIFF/np.timedelta64(1, 'D')>=0)&(DF.DIFF/np.timedelta64(1, 'D')<=2),:]
DF.drop('DIFF',1).groupby([DF.index.get_level_values(0),'date_y'])['date_x','user','value'].\
apply(lambda x :x.values.tolist()).values.tolist()
Out[760]:
[[[Timestamp('2017-05-02 00:00:00'), 'AAA ', 2.0],
[Timestamp('2017-05-03 00:00:00'), 'AAA ', 2.0],
[Timestamp('2017-05-04 00:00:00'), 'AAA ', 2.0]],
[[Timestamp('2017-05-05 00:00:00'), 'AAA ', 2.0],
[Timestamp('2017-05-06 00:00:00'), 'AAA ', 2.0],
[Timestamp('2017-05-07 00:00:00'), 'AAA ', 1.7]],
[[Timestamp('2017-05-03 00:00:00'), 'BBB ', 3.0],
[Timestamp('2017-05-04 00:00:00'), 'BBB ', 3.0],
[Timestamp('2017-05-05 00:00:00'), 'BBB ', 3.0]]]
数据输入
df1
Out[748]:
date user value
0 2017-05-01 AAA 1.0
1 2017-05-02 AAA 2.0
2 2017-05-03 AAA 2.0
3 2017-05-04 AAA 2.0
4 2017-05-05 AAA 2.0
5 2017-05-06 AAA 2.0
6 2017-05-07 AAA 1.7
7 2017-05-01 BBB 1.5
8 2017-05-02 BBB 3.0
9 2017-05-03 BBB 3.0
10 2017-05-04 BBB 3.0
11 2017-05-05 BBB 3.0
df2
Out[749]:
date user
0 2017-05-02 AAA
1 2017-05-05 AAA
2 2017-05-03 BBB