从数据透视表中提取列

时间:2020-11-07 21:12:35

标签: python pandas dataframe indexing pivot

我从这个数据框开始

life_expectancy.head(5)
    

|   |   Entity    | Code | Year | Life expectancy |

| 0 | Afghanistan | AFG  | 1950 |          27.638 |

| 1 | Afghanistan | AFG  | 1951 |          27.878 |

| 2 | Afghanistan | AFG  | 1952 |          28.361 |

| 3 | Afghanistan | AFG  | 1953 |          28.852 |

| 4 | Afghanistan | AFG  | 1954 |          29.350 |

我已经从现有的df中创建了以下数据透视表

pivot = life_expectancy.pivot_table('Life expectancy', index=['Entity'], columns = ['Year'])

我正在尝试进入2019年,但没有成功

pivot['Year']['2019']

2 个答案:

答案 0 :(得分:0)

您不需要'Year',请尝试pivot[2019](或者如果'Year'列中的值是字符串而不是整数,请使用pivot['2019'])。

答案 1 :(得分:0)

您用于访问该列的语法错误。这是正确的方法:

#converts columns names into strings
pivot.columns = map(str, pivot.columns)

#acessing the column '2019'
pivot['2019']

测试数据输出

>>> pivot.columns = map(str, pivot.columns)
>>> pivot['1950']
Entity
 Afghanistan     27.638
Name: 1950, dtype: float64