如何从 pandas 中的同一列创建行值数组?

How to make an array of row values from same column in pandas?

这里我有以下 table 有 3 列 S.No,Test 和 Key.I 想以数组的形式连接“Key”列中的那些行,其中的值“测试”列与 table 2 中的一样(结果 table)。 Table1:

S.No    Test    Key
   1    AB     X1
   2    AB     X2
   3    12     X1
   4    34     X4
   5    AB     X3
   6    12     X5
   7    11     X2
   8    12     X6
   9    QW     X0

Table 2(结果):

S.No    Test       Key
 1      AB        [X1,X2,X3]
 2      12        [X1,X5,X6]
 3      34        [X4]
 4      11        [X2]
 5      QW        [X0]

有人可以帮助我如何做 this.Right 现在我刚得到重复的 entries.Thanks。

使用 groupby Test

创建 Key 的列表
new_df = df.groupby('Test', sort=False)['Key'].apply(list).to_frame()
new_df.reset_index(inplace=True)
new_df.index = np.arange(1,len(new_df)+1)
new_df['S.No'] = new_df.index
new_df = new_df[df.columns]

输出:

  S.No    Test    Key
1 1   AB  [X1, X2, X3]
2 2   12  [X1, X5, X6]
3 3   34  [X4]
4 4   11  [X2]
5 5   QW  [X0]