python - 将 2 个数据帧 append 在一起并在 append 时增加等级

标签 python pandas append rank

我有 2 个数据框

数据框1:

index cust_id   rank opt
0   customer_1  1   test1
2   customer_1  2   test3 
3   customer_1  3   test4
4   customer_2  1   test1
5   customer_2  2   test4   
7   customer_2  3   test3   
9   customer_3  1   test3   
10  customer_3  2   test4   
11  customer_3  3   test1

数据框2:

index cust_id rank opt
1   customer_1  1  new_opt
2   customer_2  2  new_opt
3   customer_3  3  new_opt

我想将这两个数据帧合并在一起并获得如下输出:

index cust_id   rank opt
0   customer_1  1   new_opt
1   customer_1  2   test1
2   customer_1  3   test3 
3   customer_1  4   test4
4   customer_2  1   test1
5   customer_2  2   new_opt
6   customer_2  3   test4   
7   customer_2  4   test3   
8   customer_3  1   test3   
9   customer_3  2   test4
10  customer_3  3   new_opt
11  customer_3  4   test1

基本上,我希望 dataframe2 中的排名保持不变,而 dataframe1 中的排名在将数据帧 append 在一起后针对剩余选项增加。

感谢任何帮助!

最佳答案

在两者都具有密集排名的情况下,concat第一帧到第二帧,然后排序。这确保 df2 中的行出现在 df1 中排名相似的行之上。新的排名是组内的 cumcount

df = pd.concat([df2, df1], ignore_index=True).sort_values(['cust_id', 'rank'])
df['rank'] = df.groupby('cust_id').cumcount()+1

       cust_id  rank      opt
0   customer_1     1  new_opt
3   customer_1     2    test1
4   customer_1     3    test3
5   customer_1     4    test4
6   customer_2     1    test1
1   customer_2     2  new_opt
7   customer_2     3    test4
8   customer_2     4    test3
9   customer_3     1    test3
10  customer_3     2    test4
2   customer_3     3  new_opt
11  customer_3     4    test1

相反,如果您通常希望将 1 添加到排名高于 new_opt 的所有行的排名中,而不管初始排名如何,我们可以使用groupby.apply。相同的第一步,但现在我们使用 cummaxnew_opt 之后向组内的所有行添加 1。这导致与上面相同的输出。

df = pd.concat([df2, df1], ignore_index=True).sort_values(['cust_id', 'rank'])
df['rank'] = (df['rank'] 
              + (df.opt.eq('new_opt')
                   .groupby(df.cust_id)
                   .apply(lambda x: x.shift().cummax()).fillna(0).astype(int)))

关于python - 将 2 个数据帧 append 在一起并在 append 时增加等级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58631184/

相关文章:

python - 比较一行中的值并将结果写入新列

java - "append"JTextField 的文本

python - scipy 勒让德多项式中的正交性问题

python - Flask App 进行多次登录尝试的奇怪行为

python - 使用分隔符将字符串/字符数组连接成单个字符串[不使用理解、映射等]

Python dataframe 将点击路径行转为列

append - 添加到 LISP 列表的末尾

ios - 在 Realm 中追加结果数组

javascript - Google 图表 - 无效语法或意外标记

python - 为什么我的 Facebook 应用程序出现错误 104 ("invalid signature")?