Python基于以前的时间段创建变量
嗨,我有一个数据集,如下所示:Python基于以前的时间段创建变量,python,pandas,Python,Pandas,嗨,我有一个数据集,如下所示: import pandas as pd d1={'Participant_ID':['P1','P1','P1','P1','P1','P1','P2','P2','P2','P2','P2','P2'], 'Brand_Type':['B1','B1','B2','B1','B2','B2','B2','B2','B1','B2','B1','B1'], 'Date1':['5/6/2010','1/27/2010','4/3/2010','7/11/2010'
import pandas as pd
d1={'Participant_ID':['P1','P1','P1','P1','P1','P1','P2','P2','P2','P2','P2','P2'],
'Brand_Type':['B1','B1','B2','B1','B2','B2','B2','B2','B1','B2','B1','B1'],
'Date1':['5/6/2010','1/27/2010','4/3/2010','7/11/2010','3/1/2010','6/8/2010',
'5/6/2010','1/27/2010','4/3/2010','7/11/2010','3/1/2010','6/8/2010']}
d11=pd.DataFrame(d1)
d11['Date2'] = pd.to_datetime(d11['Date1'])
#converting to date var explicitly to avoid any issues and sorting the data by Participant ID and Date
d111=d11.sort_values(by=['Participant_ID','Date2'])
数据集表示客户在某个时间点消费的品牌
从这个数据集中,我想创建3个变量:
表示品牌类型是B1还是B2的虚拟变量。我可以通过以下方式完成此操作:
d111['Brand_Type_new']=d111['Brand_Type']
#creating a separate column to preserve the Brand_type variable
d1111= pd.get_dummies(d111, prefix='Category_', columns=['Brand_Type'])
b一个虚拟变量,表示参与者是否在两个时期前消费了品牌B1
注意:对于参与者1,前两行为0,因为没有观察结果。2010年4月3日的第三行是1,因为客户在两个时期前的2010年1月27日消费了B1
c一个变量,表示参与者在排除当期之前消费品牌的次数
对于第一行,值为0。第二行是1,因为参与者在上一期间已经消耗了B1,依此类推
先谢谢你
这是一个测试数据,原始数据对两名参与者有不同的日期,对参与者有不同的观察次数。当参与者的日期等数量不同时,我需要帮助如何做到这一点。基于下面a部分所示的解决方案:
d111['Brand_Type_new']=d111['Brand_Type']
#creating a separate column to preserve the Brand_type variable
d1111= pd.get_dummies(d111, prefix='Category_', columns=['Brand_Type'])
print(d1111)
Participant_ID Date1 Date2 Brand_Type_new Category__B1 \
1 P1 1/27/2010 2010-01-27 B1 1
4 P1 3/1/2010 2010-03-01 B2 0
2 P1 4/3/2010 2010-04-03 B2 0
0 P1 5/6/2010 2010-05-06 B1 1
5 P1 6/8/2010 2010-06-08 B2 0
3 P1 7/11/2010 2010-07-11 B1 1
7 P2 1/27/2010 2010-01-27 B2 0
10 P2 3/1/2010 2010-03-01 B1 1
8 P2 4/3/2010 2010-04-03 B1 1
6 P2 5/6/2010 2010-05-06 B2 0
11 P2 6/8/2010 2010-06-08 B1 1
9 P2 7/11/2010 2010-07-11 B2 0
Category__B2
1 0
4 1
2 1
0 0
5 1
3 0
7 1
10 0
8 0
6 1
11 0
9 1
您可以使用+和:
new_d=d1111.copy()
B1_groups=new_d.groupby('Participant_ID')['Category__B1']
new_d['B1_dummy_2periodAgo']=B1_groups.shift(2,fill_value=0)
new_d['B1_Cumulative']=B1_groups.apply(lambda x: x.cumsum().shift(fill_value=0))
print(new_d)
Participant_ID Date1 Date2 Brand_Type_new Category__B1 \
1 P1 1/27/2010 2010-01-27 B1 1
4 P1 3/1/2010 2010-03-01 B2 0
2 P1 4/3/2010 2010-04-03 B2 0
0 P1 5/6/2010 2010-05-06 B1 1
5 P1 6/8/2010 2010-06-08 B2 0
3 P1 7/11/2010 2010-07-11 B1 1
7 P2 1/27/2010 2010-01-27 B2 0
10 P2 3/1/2010 2010-03-01 B1 1
8 P2 4/3/2010 2010-04-03 B1 1
6 P2 5/6/2010 2010-05-06 B2 0
11 P2 6/8/2010 2010-06-08 B1 1
9 P2 7/11/2010 2010-07-11 B2 0
Category__B2 B1_dummy_2periodAgo B1_Cumulative
1 0 0 0
4 1 0 1
2 1 1 1
0 0 0 1
5 1 0 2
3 0 1 2
7 1 0 0
10 0 0 0
8 0 0 1
6 1 1 2
11 0 1 2
9 1 0 3