[英]Create dataframe from dictionary where arrays are of unequal length
I have a dictionary - {'Car': ['a', 'b'], 'Bike': ['q', 'w', 'e']}
我有一本字典 - {'Car': ['a', 'b'], 'Bike': ['q', 'w', 'e']}
I want to generate a data frame like this -我想生成这样的数据框 -
S.no. | vehicle | model
1 | Car | a
2 | Car | b
2 | Bike | q
2 | Bike | w
2 | Bike | e
I tried df = pd.DataFrame(vDict)
but I get ValueError: arrays must all be same length
error.我试过df = pd.DataFrame(vDict)
但我得到ValueError: arrays must all be same length
错误。 Help please?请帮忙?
We can use pd.DataFrame.from_dict
here, then use stack
and finally clean up our index and column names:我们可以在这里使用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.