将集合计数器转换为字典

2024-04-25 17:49:07 发布

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

我有一个收集的结果是由函数:

Counter(df.email_address)

它返回每个电子邮件地址及其重复次数。

Counter({nan: 1618, 'store@kiddicare.com': 265, 'testorders@worldstores.co.uk': 1})

我要做的是像使用字典一样使用它,并用它创建一个pandas数据框,其中有两列,一列用于电子邮件地址,另一列用于关联的值。

我试过:

dfr = repeaters.from_dict(repeaters, orient='index')

但我犯了以下错误:

AttributeError: 'Counter' object has no attribute 'from_dict'

它使计数器不像看上去那样是一本字典。你知道怎么把它附加到df上吗?


Tags: store函数fromdf字典address电子邮件email
3条回答
d = {}
cnt = Counter(df.email_address)
for key, value in cnt.items():
    d[key] = value

编辑

或者,@Trif Nefzger建议:

d = dict(Counter(df.email_address))

正如ajcr在评论中所写,from_dict是属于dataframe的方法,因此您可以编写以下内容来实现您的目标:

from collections import Counter
import pandas as pd

repeaters = Counter({"nan": 1618, 'store@kiddicare.com': 265, 'testorders@worldstores.co.uk': 1})

dfr = pd.DataFrame.from_dict(repeaters, orient='index')
print dfr

输出:

testorders@worldstores.co.uk     1
nan                           1618
store@kiddicare.com            265

或者可以使用pd.Series.value_counts,它返回一个Series对象。

df.email_address.value_counts(dropna=False)

样本输出:

b@y.com    2
a@x.com    1
NaN        1
dtype: int64

这不完全是你所要求的,但看起来像是你想要达到的。

相关问题 更多 >

    热门问题