将 2 个数据帧附加在一起并在附加时增加等级

appending 2 dataframes together and increment the ranks while appending

我有 2 个数据帧

dataframe1:

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

dataframe2:

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

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

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 中的排名在将数据帧附加在一起后针对剩余选项增加。

感谢任何帮助!

dense两个排名,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)))