簡體   English   中英

從數組長度不等的字典中創建數據框

[英]Create dataframe from dictionary where arrays are of unequal length

我有一本字典 - {'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錯誤。 請幫忙?

我們可以在這里使用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

用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM