【问题标题】:Create a new column based on corresponding values of two existing columns根据两个现有列的对应值创建一个新列
【发布时间】:2018-10-09 11:03:15
【问题描述】:

我有两个数据框,我根据 User_ID 合并在一起,得到以下数据框,这很好:

junkdf = df = DataFrame({'User_ID': [340,558,558,558,983,422,100,740,740],
'Transaction_Type_x': ['Purchase', 'Purchase', 'Purchase', 'Purchase', 'Purchase', 'Purchase', 'Purchase', 'Purchase', 'Purchase'],
'Rev/Payout_x': [50, 20, 20,28,37,50,40,50,55],
'Cohort_x': ['2010-01','2010-01','2010-02','2010-2','2010-02','2010-02','2010-03','2010-04','2010-04'],
'Transaction_Type_y': ['Sale','Sale','Sale','Sale','Sale','Sale','Sale','Sale','Sale'],
 'Rev/Payout_y': [33,42,66,69,100,22,19,98,39],
 'Cohort_y' : ['2010-03','2010-01','2010-01','2010-04','2010-04','2010-02','2010-01','2010-03','2010-02']})  

junkdf2 =junkdf[['User_ID','Transaction_Type_x','Rev/Payout_x','Cohort_x', 
'Transaction_Type_y','Rev/Payout_y','Cohort_y']]
junkdf2

我想知道是否可以使用 groupby 函数创建一个多索引数据框,其中将队列_x 和队列_y 的常用值组合起来创建一个名为“队列”的新列。

然后我可以使用 .agg 来计算当月购买商品的用户总数 (total_users_x) 和当月售出商品的用户总数,并将 x 和 y 的收入相加。理想情况下,它看起来像这样:

            Total_Users_x  Rev/Payout_x  total_user_y  Rev/Payout_y
Cohort
2010-01          2             70             3           132
2010-02          x             x              x            x
2010-03          x             x              x            x
2010-04          x             x              x            x

【问题讨论】:

  • 你能解释一下你是如何形成你的输出的吗?
  • 嗨@HarvIpan,我更新了帖子,以解释输出。
  • Rev/Payot_y2010-01 应该是 127?
  • 呃,对,我错了

标签: python pandas


【解决方案1】:

IIUC 使用wide_to_long 来增加你的df,然后我们使用agggroupby + unstack 来计算和格式化结果

s=pd.wide_to_long(junkdf2[['Cohort_x','Cohort_y','Rev/Payout_x','Rev/Payout_y']].reset_index().reset_index(),stubnames=['Rev/Payout','Cohort'],i=['index','User_ID'],j='xory',sep='_',suffix='\w+').set_index('Cohort',append=True)
s.reset_index(inplace=True)

s.groupby(['Cohort','xory']).agg({'Rev/Payout':'sum','User_ID':'nunique'}).unstack()
Out[298]: 
        User_ID    Rev/Payout     
xory          x  y          x    y
Cohort                            
2010-01       2  2         70  127
2010-02       3  2        135   61
2010-03       1  2         40  131
2010-04       1  2        105  169

【讨论】:

  • 已解决。谢谢!
猜你喜欢
  • 2021-11-23
  • 2019-04-17
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多