Home > Enterprise >  Python Pandas multiindex
Python Pandas multiindex

Time:04-12

i'm try create table like in example: Example_picture

My code:

data = list(range(39)) # mockup for 39 values

columns = pd.MultiIndex.from_product([['1', '2', '6'], [str(year) for year in range(2007, 2020)]],
                                     names=['Factor', 'Year'])
df = pd.DataFrame(data, index=['World'], columns=columns)

print(df)

But i get error:

Shape of passed values is (39, 1), indices imply (1, 39)

What i'm did wrong?

CodePudding user response:

You need to wrap the data in a list to force the DataFrame constructor to interpret the list as a row:

data = list(range(39))

columns = pd.MultiIndex.from_product([['1', '2', '6'],
                                      [str(year) for year in range(2007, 2020)]],
                                     names=['Factor', 'Year'])
df = pd.DataFrame([data], index=['World'], columns=columns)

output:

Factor    1                                                                2                                                                6                                                            
Year   2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
World     0    1    2    3    4    5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38
  • Related