简体   繁体   English

从数组长度不等的字典中创建数据框

[英]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.

相关问题 从不等长的数组创建堆叠直方图 - Create stacked histogram from unequal length arrays 使用不等长的字符串创建数据框 - Create a dataframe from unequal length strings 通过重复一个值,从不等长度的长度创建Pandas数据帧 - Create a Pandas dataframe from unequal length lengths by repeating one value 将列表中长度不等的值追加到字典中 - Append unequal length of values from a list to a dictionary 如何从不等长列表的字典创建数据帧,并截断到特定长度? - How to create a DataFrame from dict of unequal length lists, and truncating to a specific length? 从具有可变长度的列表字典创建数据帧 - Create dataframe from dictionary of list with variable length Python 从 arrays 的可变长度字典创建数组的元组 zip - Python create tuple of arrays' zip from variable length dictionary of arrays 如何从长度不等的列表中创建虚拟数据框? - How can I create a dataframe of dummies from a dict of lists of unequal length? 如何从键值不相等的字典中创建 pydatatable dataframe? - How to create a pydatatable dataframe from a dictionary which has unequal values across keys? 创建一个 pandas dataframe ,其中两个长度不等的向量之间存在差异 - Create a pandas dataframe with differences between two vectors of unequal length
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM