Python提取新数据帧

Python提取新数据帧,python,pandas,Python,Pandas,我有一个数据帧: topic student level 1 a 1 1 b 2 1 a 3 2 a 1 2 b 2 2 a 3 2 b 4 3 c 1 3

我有一个数据帧:

  topic  student level 
    1      a       1     
    1      b       2     
    1      a       3     
    2      a       1     
    2      b       2     
    2      a       3     
    2      b       4     
    3      c       1     
    3      b       2     
    3      c       3     
    3      a       4     
    3      b       5  
它包含一个列级别,指定谁开始了主题,谁回复了主题。如果级别为1,则表示学生开始讨论该主题。如果级别为2,则表示学生回答了开始主题的学生。如果级别为3,则表示一名学生在级别2时回答了该学生的问题,并继续回答

我想提取一个新的数据框架,通过这个主题呈现学生之间的交流。它应该包含三列:“学生来源”、“学生目的地”和“回复数量”。回复计数是学生目的地“直接”回复学生来源的次数

我应该得到类似于:

   st_source st_dest reply_count
        a        b       4
        a        c       0
        b        a       2
        b        c       1
        c        a       1
        c        b       1
我尝试使用此代码查找前两列

idx_cols = ['topic']
std_cols = ['student_x', 'student_y']
df1 = df.merge(df, on=idx_cols)
df2 = df1.loc[f1.student_x != f1.student_y, idx_cols + std_cols]

df2.loc[:, std_cols] = np.sort(df2.loc[:, std_cols])
有人对第三栏有什么建议吗


提前谢谢你

假设您的数据已按主题、学生和级别排序。如果没有,请先分类

#generate the reply_count for each valid combination by comparing the current row and the row above.
count_list = df.apply(lambda x: [df.ix[x.name-1].student if x.name >0 else np.nan, x.student, x.level>1], axis=1).values

#create a count dataframe using the count_list data
df_count = pd.DataFrame(columns=['st_source','st_dest','reply_count'], data=count_list)

#Aggregate and sum all counts belonging to a source-dest pair, finally remove rows with same source and dest.
df_count = df_count.groupby(['st_source','st_dest']).sum().astype(int).reset_index()[lambda x: x.st_source != x.st_dest]

print(df_count)
Out[218]: 
  st_source st_dest  reply_count
1         a       b            4
2         b       a            2
3         b       c            1
4         c       a            1
5         c       b            1

你尝试了什么?@blackmamba现在检查一下……太棒了!谢谢大家!@Allenbtw我如何也保留0行?