【问题标题】:How to copy unique keys and values from another dictionary in Python如何在 Python 中从另一个字典中复制唯一键和值
【发布时间】:2014-11-23 00:12:02
【问题描述】:

我有一个数据框df,其中包含Col 列中的值可以重复的事务。我使用计数器dictionary1 来计算每个Col 值的频率,然后我想对数据的子集运行for 循环并获得值pit。我想创建一个新字典dict1,其中键是来自dictionary1 的键,值是pit 的值。这是我到目前为止的代码:

dictionary1 = Counter(df['Col'])
dict1 = defaultdict(int)

for i in range(len(dictionary1)):       
    temp = df[df['Col'] == dictionary1.keys()[i]]
    b = temp['IsBuy'].sum()
    n = temp['IsBuy'].count()
    pit = b/n
    dict1[dictionary1.keys()[i]] = pit

我的问题是,如何根据dictionary1 的键和pit 的计算得到的值来为dict1 分配键和值。也就是说,上面脚本最后一行代码的正确写法是什么。

谢谢。

【问题讨论】:

    标签: python dictionary pandas defaultdict


    【解决方案1】:

    由于您使用的是pandas,我应该指出您面临的问题很常见,因此有一种内置方法可以解决。我们称将“相似”数据收集到组中,然后对它们执行操作 groupby 操作。阅读 groupby split-apply-combine idiom 上的教程部分可能很有价值——你可以做很多巧妙的事情!

    计算pit 值的可行方法类似于

    df.groupby("Col")["IsBuy"].mean()
    

    例如:

    >>> # make dummy data
    >>> N = 10**4
    >>> df = pd.DataFrame({"Col": np.random.randint(1, 10, N), "IsBuy": np.random.choice([True, False], N)})
    >>> df.head()
       Col  IsBuy
    0    3  False
    1    6   True
    2    6   True
    3    1   True
    4    5   True
    >>> df.groupby("Col")["IsBuy"].mean()
    Col
    1      0.511709
    2      0.495697
    3      0.489796
    4      0.510658
    5      0.507491
    6      0.513183
    7      0.522936
    8      0.488688
    9      0.490498
    Name: IsBuy, dtype: float64
    

    如果你坚持的话,你可以把它变成一个系列的字典:

    >>> df.groupby("Col")["IsBuy"].mean().to_dict()
    {1: 0.51170858629661753, 2: 0.49569707401032703, 3: 0.48979591836734693, 4: 0.51065801668211308, 5: 0.50749063670411987, 6: 0.51318267419962338, 7: 0.52293577981651373, 8: 0.48868778280542985, 9: 0.49049773755656106}
    

    【讨论】:

    • 感谢@DSM!这完美地工作,并且不需要执行 for 循环。
    猜你喜欢
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多