【问题标题】:Convert Series to list of dictionaries in pandas将 Series 转换为 pandas 中的字典列表
【发布时间】:2014-11-20 08:19:54
【问题描述】:

我有一个["A","B","B","C","A"] 形式的系列。

我使用pandas.Series.value_counts 计算每个唯一元素的频率,它还返回一个系列:["A":2,"B":2,"C":1]

我想将此系列转换为字典列表[{A:2},{B:2},{C:1}]。但是,to_dictto_records 都没有给我想要的结果。有什么替代方案?

【问题讨论】:

    标签: python list pandas dictionary


    【解决方案1】:

    我认为 Pandas for Series 或 DataFrames 中的任何类型转换方法都不会产生您想要的输出。

    您可能只需要使用列表理解来调整 to_dict() 的结果:

    >>> counts = pd.value_counts(series).to_dict()
    >>> [{u: v} for (u, v) in counts.iteritems()]
    [{'A': 2}, {'C': 1}, {'B': 2}]
    

    【讨论】:

      【解决方案2】:

      你需要counter

      >>> from collections import Counter
      >>> [ {x:y} for x,y in Counter(["A","B","B","C","A"]).items() ]
      [{'A': 2}, {'C': 1}, {'B': 2}]
      

      【讨论】:

      • 我没有投反对票,但问题似乎要求提供字典列表,而不是单个字典。
      • @ajcr 感谢通知我,我没看清楚 OP
      猜你喜欢
      • 2014-01-05
      • 2021-11-28
      • 1970-01-01
      • 2019-12-31
      • 2022-10-13
      • 1970-01-01
      相关资源
      最近更新 更多