简体   繁体   English

从具有不同长度值的字典创建 DataFrame

[英]Creating DataFrame from dictionary with different lengths of values

So, I'm looking to create a DataFrame from a dictionary similar to the follow:因此,我希望从类似于以下内容的字典中创建 DataFrame:

d = {A: ['cat','dog','zebra'],
     B: ['frog,'lion'],
     C: ['snake','cat','ant','bird','turtle'],
     D: ['sloth']}

I want the dataframe to look as such:我希望 dataframe 看起来像这样:

Col1   Col2   Col3   Col4   Col5   Col6
 A    'cat'  'dog'  'zebra'  na     na
 B    'frog' 'lion'   na     na     na
 C    'snake' 'cat'  'ant'  'bird'  'turtle'
 D    'sloth'  na      na    na     na

Any ideas?有任何想法吗? thank you!谢谢你!

Use list comprehension for add keys of dictionary for nested lists, pass to DataFrame constructor and add DataFrame.add_prefix :使用列表推导为嵌套列表添加字典键,传递给DataFrame构造函数并添加DataFrame.add_prefix

df = pd.DataFrame([[k,] + v for k, v in d.items()]).add_prefix('Col')
print (df)
  Col0   Col1  Col2   Col3  Col4    Col5
0    A    cat   dog  zebra  None    None
1    B   frog  lion   None  None    None
2    C  snake   cat    ant  bird  turtle
3    D  sloth  None   None  None    None

Or use DataFrame.from_dict with convert index to column and then set new columns names:或者使用DataFrame.from_dict将索引转换为列,然后设置新的列名:

df = pd.DataFrame.from_dict(d, orient='index').reset_index()
df.columns = [f'col{x}' for x in range(1, len(df.columns) + 1)]
print (df)
  col1   col2  col3   col4  col5    col6
0    A    cat   dog  zebra  None    None
1    B   frog  lion   None  None    None
2    C  snake   cat    ant  bird  turtle
3    D  sloth  None   None  None    None      

If want starting by col1 is possible use rename with custom function:如果想从col1开始,可以使用自定义 function rename

f = lambda x: f'col{x+1}'
df = pd.DataFrame([[k,] + v for k, v in d.items()]).rename(columns=f)
print (df)
  col1   col2  col3   col4  col5    col6
0    A    cat   dog  zebra  None    None
1    B   frog  lion   None  None    None
2    C  snake   cat    ant  bird  turtle
3    D  sloth  None   None  None    None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM