簡體   English   中英

如何使用 pandas.dataframe 轉換表格?

[英]How to convert a table using pandas.dataframe?

我有一本字典(數組)。 我需要他的外表與照片中的一樣。 怎么做?

照片與應在 output 獲得的表

我的代碼

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

           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

如果你使用下面的代碼,你應該得到你想要的:

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一長列,標題為 0),然后使用pd.transpose將該列轉置為您想要的一長行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM