在python中对列表中的相同名称进行分组

2024-09-26 22:52:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,所以希望你能在这件事上提供帮助。我有一个元组的列表。我想根据列表的第一个元素对这些列表进行分组,这可能会重复。另外,我想对重复元素列表中的第2和第3个元素求和。在

样本输入:

[("henry", 10, 20), ("alex", 25, 40), ("henry", 13, 21)]

样本输出:

^{pr2}$

我尝试过python中的groupby方法,但它只适用于排序的列表。在


Tags: 方法元素列表排序元组样本groupbyalex
1条回答
网友
1楼 · 发布于 2024-09-26 22:52:39

IIUC这里有一个使用^{}的解决方案:

lst = [['henry', 10, 20], ['henry', 23, 42], ['alex', 25, 40]]
import pandas as pd
#Create a dataframe using the list
df = pd.DataFrame(lst)
#Name the columns
df.columns = ['name', 'val1', 'val2']
#Groupby name and sum it.
df.groupby('name').sum()
#Will produce this result
       val1  val2
name
alex     25    40
henry    33    62

#To access the rows and columns following is the example
dfg = df.groupby('name').sum()
#Row, Column
dfg.ix[0,0]
#Will get 25 & likewise can get any other values
25 

相关问题 更多 >

    热门问题