将具有多个列数据的相同列行数据转换为新数据框

时间:2018-12-07 20:01:07

标签: python python-3.x pandas

我有一个大熊猫数据框,看起来像这样:

"name" "price" "quantity"
"s1"   2       5
"s2"   3       7
"s3"   9       2
"s1"   5       10
"s2"   8       1
etc    etc     etc

我想制作一个新的数据框,如下所示:

"name" "price" "quantity"
"s1"   [2, 5]  [5, 10]
"s2"   [3, 8]  [7, 1]
etc    etc     etc

谢谢!

1 个答案:

答案 0 :(得分:1)

pd.groupby与lambda函数一起用于聚合:

df.groupby('"name"').agg(lambda x: tuple(x))

输出:

        "price" "quantity"
"name"                   
"s1"    (2, 5)    (5, 10)
"s2"    (3, 8)     (7, 1)
"s3"      (9,)       (2,)