使用groupby对A列进行分组,然后基于B列创建一个列表

时间:2019-08-19 08:41:44

标签: python pandas

我认为我很难解释,但我将展示我的预期结果。 我有以下数据框。

a = pd.DataFrame({"Character":["a","a","a","a","a","a","b","b","b","b","b","b"],
"value": [1,2,3,4,5,6,7,8,9,10,11,12]})
data.groupby("Sentence")

我可以根据句子对它进行分组,但是我不知道如何通过引用groupby来基于列将其提取。

预期结果:

[[1,2,3,4,5,6],[7,8,9,10,11,12]]

2 个答案:

答案 0 :(得分:1)

GroupBy.applylist一起用于Series,并为列表列表添加tolist

data = pd.DataFrame({"Character":["a","a","a","a","a","a","b","b","b","b","b","b"],
"value": [1,2,3,4,5,6,7,8,9,10,11,12]})
L = data.groupby("Character")['value'].apply(list).tolist()

print (L)
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]

答案 1 :(得分:1)

下面的代码给出了预期的输出

list(a.groupby("Character")["value"].apply(list))