【问题标题】:Set column names in pandas data frame from_dict with orient = 'index'在熊猫数据框中设置列名 from_dict 与 orient = 'index'
【发布时间】:2017-12-06 12:31:45
【问题描述】:

我已经看过这个问题:pandas create named columns in dataframe from dict。但是,我的示例略有不同。

我有一本字典: my_dict = {'key1' : [1,2,3], 'key2' : [4,5,6], 'key3' :[7,8,9]}

我创建了一个 pandas 数据框:df = pd.DataFrame.from_dict(my_dict, orient='index'),它是面向行的。但是,在写 columns = ['one', 'two', 'three'] 时,我收到一个错误,如上面的链接所示。

如何命名它们?

【问题讨论】:

  • 解决问题的方法在您的链接问题中得到解答(少一栏)。只要看看接受的答案:pd.DataFrame(list(my_dict.iteritems()),columns=['business_id','business_code']),所以在你的情况下pd.DataFrame(list(my_dict.iteritems()),columns=['one','two','three'])(归功于Andy Hayden

标签: python dictionary key


【解决方案1】:
my_dict = {'key1' : [1,2,3], 'key2' : [4,5,6], 'key3' :[7,8,9]}
df = pd.DataFrame.from_dict(my_dict, orient='columns')
df.columns = ['one', 'two', 'three']

将方向从索引更改为列。这对我有用。

【讨论】:

    【解决方案2】:

    From version 0.23.0,可以在from_dict中指定一个columns参数:

    my_dict = {'key1': [1, 2, 3], 'key2': [4, 5, 6], 'key3': [7, 8, 9]}
    df = pd.DataFrame.from_dict(my_dict, orient='index', columns=['one', 'two', 'three'])
    

    【讨论】:

      【解决方案3】:

      是否有不能在下一行设置列名的原因?

      my_dict = {'key1' : [1,2,3], 'key2' : [4,5,6], 'key3' :[7,8,9]}
      df = pd.DataFrame.from_dict(my_dict, orient='index')
      df.columns = ['one', 'two', 'three']
      

      应该可以。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-17
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多