python - Pandas 只识别我的数据框中的一列

标签 python pandas

<分区>

我是 Python 新手。我有以下代码:

import wbdata # World Bank's API
import pandas
import matplotlib.pyplot as plt

#countries I want
countries = ["CL","UY","HU"]

#indicators I want
indicators = {'NY.GNP.PCAP.CD':'GNI per Capita'}

#grab indicators above for countries I want and load into data frame
df = wbdata.get_dataframe(indicators, country=countries, convert_date=False)

#list the columns in data frame
list(df.columns.values)

我的数据框的输出和数据框中的列数如下:

In [1]:df
Out[1]: 
                GNI
country date         
Chile   2017  13610.0
        2016  13430.0
        2015  14270.0
        2014  15140.0
        2013  15360.0
        2012  14410.0
        2011  12380.0
              ...
Uruguay 2017  23410.0
        2016  11430.0
        2015  11270.0
        2014  11440.0
        2013  65360.0
        2012  94410.0
        2011  10380.0

[174 rows x 1 columns]

In [2]: list(df.columns.values)
Out[2]: ['GNI']

如您所见,数据框中只有一列(“GNI”)被识别为一列。

我该怎么做才能让“国家/地区”和“日期”也被识别为列?

我的目标是拥有如下所示类型的面板数据集。其中有三个变量(=Stata 语言):Country、Date 和 GNI。并且国家变量中不存在空白,因为每个 GNI 观测值都对应一个国家/日期组合。

Country Date   GNI   
Chile   2017  13610.0
Chile   2016  13430.0
Chile   2015  14270.0
Chile   2014  15140.0
Chile   2013  15360.0
Chile   2012  14410.0
Chile   2011  12380.0
              ...
Uruguay 2017  23410.0
Uruguay 2016  11430.0
Uruguay 2015  11270.0
Uruguay 2014  11440.0
Uruguay 2013  65360.0
Uruguay 2012  94410.0
Uruguay 2011  10380.0

[174 rows × 3 columns]

当然,我正在破坏 Python 语法和语言,但我们将不胜感激任何帮助或指导。

最佳答案

您只看到 GNI 作为列,因为 Country 和 Date 用作索引(准确地说是 MultiIndex)。

你需要的是reset_index :

df = df.reset_index(drop=False)

关于python - Pandas 只识别我的数据框中的一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51879686/

相关文章:

python - 如何使用 pandas 替换跨列的时间戳

python - pandas DataFrame 中的级别是什么?

python - 分割包含数字、罗马数字和项目符号列表的字符串的最佳方法是什么?

python - sklearn将文本系列转换为稀疏矩阵,然后缩放数字,然后组合成单个X

python - 在 DjangoRestFramework(DRF) 中,未定义名称 'request'

python - Pandas If Else 条件对多列

python - 向 Pandas Dataframe 对象添加样式后,如何将其保存为 PDF?

python - 使用 Pandas 计算固定时间范围之间的总和

python - 如何获取字典列表中具有最高值的字典

python - 将数据作为参数或文件从 python 发送到 c++?