【问题标题】:Pandas only recognizes one column in my data frame [duplicate]Pandas 只识别我的数据框中的一列 [重复]
【发布时间】:2019-01-23 13:40:06
【问题描述】:

我是 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”)被识别为一列。

我该怎么做才能让 'country' 和 'date' 也被识别为列?

我的目标是拥有一个如下所示类型的面板数据集。其中有三个变量(=Stata 语言):国家、日期和 GNI。并且 Country 变量中不存在空白,因为每个 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 语法和语言,但我们将不胜感激任何帮助或指导。

【问题讨论】:

标签: python pandas


【解决方案1】:

您仅将 GNI 视为列,因为 Country 和 Date 用作索引(准确地说是 MultiIndex)。

你需要的是reset_index:

df = df.reset_index(drop=False)

【讨论】:

  • 感谢您的解释。 Pandas 中的索引有什么意义?我在网上和网上搜索过需要事先了解 Python 术语和数据结构的解释。
  • 这可能是您问题的一个很好的参考:stackoverflow.com/questions/27238066/… 我个人倾向于将不同的列视为“实体”,将行视为对该实体的观察,因此索引是观察的标签。例如,在时间序列中,您可能希望按日期引用观察
猜你喜欢
  • 1970-01-01
  • 2019-06-20
  • 2018-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多