【问题标题】:Converting dictionary into two-column panda dataframe [duplicate]将字典转换为两列熊猫数据框[重复]
【发布时间】:2020-09-08 03:38:55
【问题描述】:

我在 python 中有一个名为word_counts 的字典,由关键词和值组成,代表它们在给定文本中出现的频率:

word_counts = {'the':2, 'cat':2, 'sat':1, 'with':1, 'other':1}

我现在需要把它变成一个带有两列的 pandas DataFrame:一个名为“word”的列表示单词,一个名为“count”的列表示频率。

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:
    >>> import pandas as pd
    >>> pd.DataFrame(list(word_counts.items()), columns=['word', 'count'])
        word  count
    0    the      2
    1    cat      2
    2    sat      1
    3   with      1
    4  other      1
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
    【解决方案2】:

    您可以从字典创建数据框:

    df=pd.DataFrame({"word":list(word_counts.keys()) , "count": list(word_counts.values())})
    

    【讨论】:

      【解决方案3】:

      您可以使用来自pd.DataFrame.from_dict 附件

      pd.DataFrame.from_dict(word_counts, orient="index", columns=["Count"]).rename_axis(
          "Word", axis=1
      )
      Word   Count
      the        2
      cat        2
      sat        1
      with       1
      other      1
      

      【讨论】:

        猜你喜欢
        • 2020-12-01
        • 2017-11-22
        • 2019-07-18
        • 2017-12-12
        • 2018-11-25
        • 1970-01-01
        • 2018-07-14
        • 2019-05-07
        相关资源
        最近更新 更多