0
df = pd.DataFrame({'Country':['China','China', 'India', 'India', 'America', 
    'Japan', 'China', 'India'],
    'Year': ['2001', '2002', '2001', '2002', '2001', '2001', '1999', '1999'],
    'Income':[10000, 10000, 5000, 5002, 40000, 50000, 8000, 5000],
    'Age':[5000, 4321, 1234, 4010, 250, 250, 4500, 4321]})

print(df)
   Country  Year  Income   Age
0    China  2001   10000  5000
1    China  2002   10000  4321
2    India  2001    5000  1234
3    India  2002    5002  4010
4  America  2001   40000   250
5    Japan  2001   50000   250
6    China  1999    8000  4500
7    India  1999    5000  4321

this is the expected result

   Country   Income-2000, Income-2001, Income-2002 
0    China  8000   10000  10000  
1    India  5000    5000  5002
4  America  n/a   40000  n/a
5    Japan  n/a   50000   n/a

is there any simple way to get this? or the way is loop it like this then merge as a new datafram?

for index,data in df.groupby('Country'):
    print(index)
    print(data)
dboy
  • 1,004
  • 2
  • 16
  • 24
user1023333
  • 51
  • 2
  • 4
  • try : `table = pd.pivot_table(df, index=['Country'], columns=['Year']) `, should close to what you want. – dboy Apr 14 '20 at 07:02
  • if works with above sample data, but the actual data is very big and a lot of other columns, i can't make sure whether this is caused by some dirty data, i got this error: DataError: No numeric types to aggregate – user1023333 Apr 14 '20 at 08:48

0 Answers0