如何对 x 列进行分组并对 y 列求和

问题描述 投票:0回答:1

!我不知道为什么我在这方面如此挣扎,我已经尝试了一切。我导入了两列,如下所示:

地点: 事件:

巴黎1号 伦敦 2 慕尼黑 1 慕尼黑。 3 慕尼黑 5 伦敦 1 巴黎 8

``

我已将站点列转换为我的函数的列表,因为存在类型错误“巴黎”。我需要删除它(如果有一种简单的方法来修改 iloc 列本身,那也会很方便:)我现在想创建一个函数来输出每个站点的出现次数总和

{巴黎:9,伦敦:3,慕尼黑:9}

这是我最近的尝试

def indicatorcount(sitelist, occurrenceslist):
    xlist = []
    ylist = []

    for x in (sitelist):
       xlist.append(x)
    for y in occurrenceslist:
        ylist.append(y)

    df = pd.DataFrame({'xlist'}, {'ylist'})
    sort = df.groupby('xlist')[ylist].apply(list).reset_index(name='new')
    return sort

我已经尝试过这个,但我不确定如何构造它,以便当 xlist == in_occurrence 中的键的迭代时,ylist 的相同迭代被添加到字典值中。 ... def IndicatorCount(站点列表, 出现次数列表): x列表=[] y列表=[] 兹列表=[] 对于(县名单)中的 x: xlist.append(x) 对于出现列表中的 y: ylist.append(y) zlist.append(0)

    a = Counter(xlist).keys()
    in_occurrence = dict(zip(a, zlist))
    for a, z in in_occurrence.items():
        for c, i in itertools.izip(xlist, ylist):
           if c == (a for a in in_occurrence):
                z.append(i)
           else: 
               continue 
     for a, b in in_occurrence.items():
         yield (f"{a}: {b}") 
python dataframe function dictionary analysis
1个回答
0
投票

我不确定你到底想做什么,但如果你想显示出现次数的总和,你可以使用一个更简单的函数:

occurences_ = df.groupby("site")["occurence"].sum().to_dict()

假设您已将 site_list 和occurrence_list 传递到DataFrame 中。

如果您有 Tipo 问题,您可以使用以下方法提前清洁它们:

df['site'] = df['site'].str.replace(r'\.$', '', regex=True)

这应该删除“。”在字符串的末尾。这 ”。”用于指定特殊字符,而“$”指定字符串的结尾。

© www.soinside.com 2019 - 2024. All rights reserved.