【问题标题】:Construct Pandas DataFrame from dictionary in form {index: list of row values}从字典中以 {index: list of row values} 的形式构造 Pandas DataFrame
【发布时间】:2015-02-24 06:55:47
【问题描述】:

我已经设法做到这一点:

dft = pd.DataFrame.from_dict({
                    0: [50, 45, 00, 00], 
                    1: [53, 48, 00, 00],
                    2: [56, 53, 00, 00],
                    3: [54, 49, 00, 00],
                    4: [53, 48, 00, 00],
                    5: [50, 45, 00, 00]
                    }, orient='index'
                    )

这样完成,构造函数看起来就像 DataFrame 一样,易于阅读/编辑:

>>> dft
    0   1   2   3
0   50  45  0   0
1   53  48  0   0
2   56  53  0   0
3   54  49  0   0
4   53  48  0   0
5   50  45  0   0

DataFrame.from_dict constructor 没有列参数,因此为列提供合理的名称需要额外的步骤:

dft.columns = ['A', 'B', 'C', 'D']

对于这样一种方便(例如,用于单元测试)初始化 DataFrames 的方法来说,这似乎很笨重。

所以我想知道:有没有更好的方法?

【问题讨论】:

    标签: python list pandas dictionary dataframe


    【解决方案1】:

    或者,您可以使用DataFrame.from_items() 从您的字典中构造 DataFrame;这允许您同时传入列名。

    例如,如果d 是您的字典:

    d = {0: [50, 45, 0, 0],
         1: [53, 48, 0, 0],
         2: [56, 53, 0, 0],
         3: [54, 49, 0, 0],
         4: [53, 48, 0, 0],
         5: [50, 45, 0, 0]}
    

    数据是d.items(),方向又是'index'。字典键成为索引值:

    >>> pd.DataFrame.from_items(d.items(), 
                                orient='index', 
                                columns=['A','B','C','D'])
        A   B  C  D
    0  50  45  0  0
    1  53  48  0  0
    2  56  53  0  0
    3  54  49  0  0
    4  53  48  0  0
    5  50  45  0  0
    

    在 Python 2 中,您可以使用 d.iteritems() 来生成字典的内容,以避免在内存中创建另一个列表。

    【讨论】:

      【解决方案2】:

      一种方法如下:

      df = pd.DataFrame.from_dict({
      0: {"A":50, "B":40},
      1: {"A":51, "B":30}}, orient='index')
      

      但是,对于快速测试初始化​​,我可能更喜欢您的方式 + 然后设置列。

      【讨论】:

        【解决方案3】:

        你可以试试:

        x=pd.DataFrame({0:[50,45],1:[53,48],2:[56,53]}, index=["A","B"]).transpose()
        

        但这仍然很奇怪,因为您将标准索引指定为字典的键。

        为什么不直接

        x = pd.DataFrame({"A":[50,53,56],"B":...})
        

        【讨论】:

        • "为什么不直接 x = pd.DataFrame({"A":[50,53,56],"B":...})"?正如问题所述,只是为了将初始化中的数字保持在与df相同的位置......
        • 标准索引键只是占位符,以保持示例简单。可能我需要使用日期时间对象。
        猜你喜欢
        • 2013-11-26
        • 1970-01-01
        • 2012-11-14
        • 2022-12-01
        • 2022-11-09
        • 1970-01-01
        • 1970-01-01
        • 2013-04-27
        • 2022-12-27
        相关资源
        最近更新 更多