【问题标题】:transfer dictionary to DataFrame?将字典传输到 DataFrame?
【发布时间】:2016-11-19 22:26:48
【问题描述】:

我有以下字典,如何将其转换为四列 DataFrame? (columns=['country','date','2y','10y']

temp
    {'Germany':           date    2y   10y
    0   2004-02-01  2.47  4.22
    1   2004-03-01  2.22  4.05
    2   2004-04-01  2.20  3.96
    ..         ...   ...   ...
    149 2016-07-01 -0.65 -0.13

   [150 rows x 3 columns], 'Japan':           date    2y   10y
    0   2004-02-01  0.07  1.32
    1   2004-03-01  0.05  1.26
    2   2004-04-01  0.10  1.42
    ..         ...   ...   ...
    148 2016-06-01 -0.24 -0.12
    149 2016-07-01 -0.33 -0.25
type(temp)
     dict

我已经尝试过 pd.DataFrame(temp) 和 pd.DataFrame.from_dict(temp)。两者都返回错误。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您的字典似乎将数据框作为值。如果是这种情况,将字典简化为数据框的一种方法是遍历字典,为每个子字典创建一个新列并将它们连接起来:

    import pandas as pd
    df = pd.DataFrame()
    for k, v in temp.items():
        v['country'] = k
        df = pd.concat([df, v])
    

    类似的例子:

    df1 = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4]})
    df2 = pd.DataFrame({'a': [2,4,5], 'b': [5,6,8]})
    temp = {'x': df1, 'y': df2}
    
    temp    
    #{'x':    a  b
    # 0  1  2
    # 1  2  3
    # 2  3  4, 'y':    a  b
    # 0  2  5
    # 1  4  6
    # 2  5  8}
    

    这给出了:

    df.reset_index()
    
    #   a   b   country
    #0  1   2   x
    #1  2   3   x
    #2  3   4   x
    #3  2   5   y
    #4  4   6   y
    #5  5   8   y
    

    【讨论】:

      【解决方案2】:

      您可以将concatreset_indexrename 一起使用:

      df1 = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4]})
      df2 = pd.DataFrame({'a': [2,4,5], 'b': [5,6,8]})
      temp = {'x': df1, 'y': df2}
      
      print (temp)
      
      print (pd.concat(temp)
               .reset_index(level=1,drop=True)
               .reset_index()
               .rename(columns={'index':'country'}))
      
        country  a  b
      0       x  1  2
      1       x  2  3
      2       x  3  4
      3       y  2  5
      4       y  4  6
      5       y  5  8
      

      通过rename_axis 设置索引名称的另一个解决方案(pandas 0.18.0 中的新功能):

      print (pd.concat(temp)
               .rename_axis(('country','temp'))
               .reset_index(level=1,drop=True)
               .reset_index())
      
        country  a  b
      0       x  1  2
      1       x  2  3
      2       x  3  4
      3       y  2  5
      4       y  4  6
      5       y  5  8
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-14
        • 2019-02-06
        • 2016-10-16
        • 2019-04-30
        • 2016-09-02
        • 2020-06-11
        • 2019-06-27
        相关资源
        最近更新 更多