如何用Pandas的groupby按Character列分组并提取value列生成嵌套列表
Hey there! Let's sort this out for you. You've got a Pandas DataFrame where you want to group by the Character column, then pull each group's value entries into a sublist to get that [[1,2,3,4,5,6],[7,8,9,10,11,12]] output you're after.
First, let's recap your original DataFrame code for clarity:
import pandas as pd 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] })
Here's the straightforward way to get your desired result:
# Group by Character, convert each group's value column to a list, then turn the Series into a list result = a.groupby("Character")["value"].apply(list).tolist() print(result) # Output: [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
Let me break that down step by step:
a.groupby("Character")["value"]: We first group the DataFrame by theCharactercolumn, and narrow our focus to only thevaluecolumn we care about..apply(list): This takes each group of values and converts it into a standard Python list..tolist(): Finally, we turn the resulting Pandas Series (which uses "a" and "b" as indexes) into a plain list of lists.
If you prefer, you can use .agg(list) instead of .apply(list)—they work identically here:
result = a.groupby("Character")["value"].agg(list).tolist()
One quick note: By default, groupby sorts group keys alphabetically, so "a" comes before "b" which matches your expected output. If you ever need to preserve the original order of groups as they appear in your DataFrame, just add sort=False to the groupby call:
result = a.groupby("Character", sort=False)["value"].apply(list).tolist()
内容的提问来源于stack exchange,提问作者Anonymous

