我有两个要合并的熊猫数据框。数据框的大小不同,所以我只希望df1保留那些出现在其中的数据框- 有些学生只出现在df1或之一中df2。df1具有标题,['student', 'week1_count', 'week1_mean', ..., 'week11_count', 'week11_mean']并使用除'student'列之外的所有单元格初始化为零。df2具有标题['student', 'week', 'count', 'mean']并填充了相应的'student'. 'week'是一个介于 1-11 之间的整数,并且'count'和'mean'是相应的浮点数。我想要做的是对于给定的学生 in df1and df2,在给定的一周内,取相应的'count'and'mean'值并将其放入df1相应的列中。例如, 的'week'值1意味着 in'count'和'mean'in的值df2将分别放入'week1_count'和'week1_mean'中df1。关于我一直循环range(11)并创建子集数据框的几周,但想知道是否有更快的方法。IEdf1: student week1_count week1_mean week2_count week2_mean ... '0' 0 0 0 0 ... '2' 0 0 0 0 ... '3' 0 0 0 0 ... . . . '500' 0 0 0 0 ... '541' 0 0 0 0 ... '542' 0 0 0 0 ... 和df2: student week count mean '0' 1 5 6.5 '1' 1 3 7.0 '2' 1 2 8.2 '2' 2 10 15.1 . . . '500' 2 12 4.3 '540' 4 1 3.0 '542' 1 4 1.2 '542' 2 9 5.2所以预期的结果df_result: student week1_count week1_mean week2_count week2_mean ... '0' 5 6.5 0 0 ... '2' 2 8.2 10 15.1 ... '7' 0 0 0 0 ... . . . '500' 0 0 12 4.3 ... '541' 0 0 0 0 ... '542' 4 1.2 9 5.2 ... 我已经尝试了各种例程 - 这些例程都没有按预期工作 - 在熊猫中,例如:合并:使用“左”连接,因为我想要df1. 我尝试重命名列df2以匹配列名。加入连接更新:尝试将所有单元格初始化为df1tonp.nan而不是0.0,然后使用df1.update(df2)(在将 cols 重命名为 in 之后df2)用预期的值更新所有 nan 值试图只设置值:即类似df1[rows_in_both][['week1_count','week1_mean']] = df2[rows_in_both][['count','mean']]但也不起作用
1 回答
慕后森
TA贡献1802条经验 获得超5个赞
这更像是一个update问题而不是 merge
s=df2.pivot(index='student',columns='week',values=['count','mean'])# pivot df2 to format it to df1 like .
s.columns.map('week{0[1]}_{0[0]}'.format) # modify the column
Out[645]:
Index(['week1_count', 'week2_count', 'week4_count', 'week1_mean', 'week2_mean',
'week4_mean'],
dtype='object')
s.columns=s.columns.map('week{0[1]}_{0[0]}'.format)
然后我们做 update
df1=df1.set_index('student')
df1=df1.update(s)
添加回答
举报
0/150
提交
取消