Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. Country Metric 2011 2012 2013 2014
  2. USA GDP 7 4 0 2
  3. USA Pop. 2 3 0 3
  4. GB GDP 8 7 0 7
  5. GB Pop. 2 6 0 0
  6. FR GDP 5 0 0 1
  7. FR Pop. 1 1 0 5
  8.  
  9. df = data.groupby(['Country', 'Metric'])
  10.  
  11. import pandas
  12. from io import StringIO
  13.  
  14. datastring = StringIO("""
  15. Country Metric 2011 2012 2013 2014
  16. USA GDP 7 4 0 2
  17. USA Pop. 2 3 0 3
  18. GB GDP 8 7 0 7
  19. GB Pop. 2 6 0 0
  20. FR GDP 5 0 0 1
  21. FR Pop. 1 1 0 5
  22. """)
  23. data = pandas.read_table(datastring, sep='ss+')
  24. data.set_index(['Country', 'Metric'], inplace=True)
  25.  
  26. 2011 2012 2013 2014
  27. Country Metric
  28. USA GDP 7 4 0 2
  29. Pop. 2 3 0 3
  30. GB GDP 8 7 0 7
  31. Pop. 2 6 0 0
  32. FR GDP 5 0 0 1
  33. Pop. 1 1 0 5
  34.  
  35. data.xs('GDP', level='Metric')
  36.  
  37. 2011 2012 2013 2014
  38. Country
  39. USA 7 4 0 2
  40. GB 8 7 0 7
  41. FR 5 0 0 1
  42.  
  43. data.columns.names = ['Year']
  44. data = data.stack()
  45. data
  46.  
  47. Country Metric Year
  48. USA GDP 2011 7
  49. 2012 4
  50. 2013 0
  51. 2014 2
  52. Pop. 2011 2
  53. 2012 3
  54. 2013 0
  55. 2014 3
  56. GB GDP 2011 8
  57. 2012 7
  58. 2013 0
  59. 2014 7
  60. Pop. 2011 2
  61. 2012 6
  62. 2013 0
  63. 2014 0
  64. FR GDP 2011 5
  65. 2012 0
  66. 2013 0
  67. 2014 1
  68. Pop. 2011 1
  69. 2012 1
  70. 2013 0
  71. 2014 5
  72.  
  73. data.groupby(level=['Metric', 'Year']).sum()
  74. Metric Year
  75. GDP 2011 20
  76. 2012 11
  77. 2013 0
  78. 2014 10
  79. Pop. 2011 5
  80. 2012 10
  81. 2013 0
  82. 2014 8
  83.  
  84. data.groupby(level=['Metric', 'Year']).sum().unstack(level='Metric')
  85. Metric GDP Pop.
  86. Year
  87. 2011 20 5
  88. 2012 11 10
  89. 2013 0 0
  90. 2014 10 8
  91.  
  92. df = df.groupby(['Metric'])
  93. df.get_group('GDP')
  94.  
  95. Country Metric 2011 2012 2013 2014
  96. 0 USA GDP 7 4 0 2
  97. 2 GB GDP 8 7 0 7
  98. 4 FR GDP 5 0 0 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement