【问题标题】:Create dataframe from dictionary where arrays are of unequal length从数组长度不等的字典创建数据框
【发布时间】:2020-11-18 20:11:47
【问题描述】:

我有一本字典 - {'Car': ['a', 'b'], 'Bike': ['q', 'w', 'e']}

我想生成这样的数据框-

S.no. | vehicle | model
1     | Car     | a
2     | Car     | b
2     | Bike     | q
2     | Bike     | w
2     | Bike     | e

我尝试了df = pd.DataFrame(vDict),但出现ValueError: arrays must all be same length 错误。请帮忙?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    用途:

    pd.Series(dct, name='model').explode().rename_axis(index='vehicle').reset_index()
    

    【讨论】:

      【解决方案2】:

      我们可以在这里使用pd.DataFrame.from_dict,然后使用stack,最后清理我们的索引和列名:

      dct = {'Car': ['a', 'b'], 'Bike': ['q', 'w', 'e']}
      
      df = pd.DataFrame.from_dict(dct, orient='index').stack()
      df = df.reset_index(level=0, name='model').rename(columns={'level_0':'vehicle'})
      df = df.reset_index(drop=True)
      
        vehicle model
      0     Car     a
      1     Car     b
      2    Bike     q
      3    Bike     w
      4    Bike     e
      

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        • 2013-11-13
        • 2019-03-20
        • 1970-01-01
        • 2020-09-04
        • 2018-03-07
        • 2022-09-28
        相关资源
        最近更新 更多