我正在处理一些广告数据,例如电子邮件数据。我有两个数据集:
邮件级别,针对每个人,说明他们的邮寄日期,以及他们的转换日期。
import pandas as pd df_emailed=pd.DataFrame() df_emailed['person']=['A','A','A','A','B','B','B'] df_emailed['day']=[2,4,8,9,1,2,5] df_emailed print(df_emailed) person day 0 A 2 1 A 4 2 A 8 3 A 9 4 B 1 5 B 2 6 B 5
我有一个摘要数据框,其中显示某人是否进行了转化,以及他们在哪一天进行了转化。
df_summary=pd.DataFrame() df_summary['person']=['A','B'] df_summary['days_max']=[10,5] df_summary['convert']=[1,0] print(df_summary) person days_max convert 0 A 10 1 1 B 5 0
我想将这些组合成一个最终的数据框,对于每个人来说:
- 1 到最大日期,
- 他们是否通过电子邮件发送(0,1)以及数据框中的最后一天,
- 他们是否转换(0,1)。
我们假设它们在数据框中的最后一天进行转换。
我知道使用嵌套的 for 循环来做到这一点,但我认为这效率低得令人难以置信,而且有点愚蠢。有谁知道完成此任务的有效方法吗?
期望的结果
df_final=pd.DataFrame()
df_final['person']=['A','A','A','A','A','A','A','A','A','A','B','B','B','B','B']
df_final['day']=[1,2,3,4,5,6,7,8,9,10,1,2,3,4,5]
df_final['emailed']=[0,1,0,1,0,0,0,1,1,0,1,1,0,0,1]
df_final['convert']=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0]
print(df_final)
person day emailed convert
0 A 1 0 0
1 A 2 1 0
2 A 3 0 0
3 A 4 1 0
4 A 5 0 0
5 A 6 0 0
6 A 7 0 0
7 A 8 1 0
8 A 9 1 0
9 A 10 0 1
10 B 1 1 0
11 B 2 1 0
12 B 3 0 0
13 B 4 0 0
14 B 5 1 0
谢谢您,节日快乐!
最佳答案
高级方法涉及修改df_summary
(别名df2
)以获得我们的输出。我们需要
-
对
set_index
操作。我们还将名称更改为days
(这将在稍后有所帮助)groupby
对person
进行分组应用
对索引进行reindex
操作(天,因此我们获取截至最后一天的每一天的行)fillna
用于填充由于重新索引而生成的convert
列中的 NaN分配
为我们稍后设置的emailed
创建一个虚拟列。
df2
上的 days_max
列进行 接下来,使用 df_emailed 索引上一操作的结果。我们将使用这些值将相应的emailed
单元格设置为1
。这是通过使用 loc
进行多重索引来完成的。
最后,使用 reset_index
将索引作为列显示出来。
def f(x):
return x.reindex(np.arange(1, x.index.max() + 1))
df = df2.set_index('days_max')\
.rename_axis('day')\
.groupby('person')['convert']\
.apply(f)\
.fillna(0)\
.astype(int)\
.to_frame()\
.assign(emailed=0)
df.loc[df1[['person', 'day']].apply(tuple, 1).values, 'emailed'] = 1
df.reset_index()
person day convert emailed
0 A 1 0 0
1 A 2 0 1
2 A 3 0 0
3 A 4 0 1
4 A 5 0 0
5 A 6 0 0
6 A 7 0 0
7 A 8 0 1
8 A 9 0 1
9 A 10 1 0
10 B 1 0 1
11 B 2 0 1
12 B 3 0 0
13 B 4 0 0
14 B 5 0 1
哪里
df1 = df_emailed
并且,
df2 = df_summary
关于python - 无需 for 循环即可高效创建数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47981341/