简体   繁体   中英

How to convert a table using pandas.dataframe?

I have a dictionary(array). I need his appearance to be the same as in the photo. How to do it?

Photo with a table that should be obtained at the output

My Code

array = {1: {2016: 22818888925.021294, 2017: 23215791927.55883, 2018: 24241415053.75489, 2019: 25526831987.89783, 2007: 18183059018.027966, 2008: 16868527277.51174, 2009: 18331809529.53519, 2010: 19724006864.797657, 2011: 20392912788.825798, 2012: 19580849153.840134, 2013: 22084393933.539394, 2014: 22030084567.47173, 2015: 21700822555.267574}, 2: {2016: 15081873888.10038, 2017: 15377071873.462284, 2018: 16253879799.12362, 2019: 16517025291.019705, 2007: 10038529774.615318, 2008: 11611749842.042978, 2009: 12040185617.510305, 2010: 12508816879.258118, 2011: 13711111085.100977, 2012: 13219008951.675236, 2013: 14209627046.021126, 2014: 15371996764.61913, 2015: 14417938720.997215}, 6: {2016: 0.6609381349660216, 2017: 0.6623539667069717, 2018: 0.6705004539991144, 2019: 0.6470456380505956, 2007: 0.5520814602571774, 2008: 0.6883677306864346, 2009: 0.6567919876164886, 2010: 0.6341924825418297, 2011: 0.6723468700662476, 2012: 0.6750988605150847, 2013: 0.6434239077958611, 2014: 0.6977729348945159, 2015: 0.6643959547744175}})

print pd.DataFrame.from_dict(mass_factor) 

Output of my code

           1             2         6
2007  1.818306e+10  1.003853e+10  0.552081
2008  1.686853e+10  1.161175e+10  0.688368
2009  1.833181e+10  1.204019e+10  0.656792
2010  1.972401e+10  1.250882e+10  0.634192
2011  2.039291e+10  1.371111e+10  0.672347
2012  1.958085e+10  1.321901e+10  0.675099
2013  2.208439e+10  1.420963e+10  0.643424
2014  2.203008e+10  1.537200e+10  0.697773
2015  2.170082e+10  1.441794e+10  0.664396
2016  2.281889e+10  1.508187e+10  0.660938
2017  2.321579e+10  1.537707e+10  0.662354
2018  2.424142e+10  1.625388e+10  0.670500
2019  2.552683e+10  1.651703e+10  0.647046

You should get what you want if you use the following code:

new_df = pd.DataFrame(df.unstack()).transpose()

print(new_df)

This works by converting your original df to a series with the MultiIndex of all current columns + the year via pd.DataFrame.unstack , then converting the resultant series back into a dataframe with one row by feeding that series into pd.DataFrame (resulting in one long column, titled 0), then using pd.transpose to transpose that column to be one long row as you intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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