Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从python dataframe中获取行并将其转换为一个新dataframe的列_Python_Pandas_Rows - Fatal编程技术网

如何从python dataframe中获取行并将其转换为一个新dataframe的列

如何从python dataframe中获取行并将其转换为一个新dataframe的列,python,pandas,rows,Python,Pandas,Rows,我有三种不同的经济指标数据框架。列为年份,行为国家。我想取每个国家的行,并为每个国家形成一个数据框架,这样列是三个经济指标,行是年份 例如:奥地利 GDP | CPI | Interest rate 1998年| xxxxxxxxxx | xxxxxxxxxx | xxxxxxxxxxxx 1999年| xxxxxxxxxx | xxxxxxxxxx | xxxxxxxxxxxx 在python中执行此操作时遇到困难,因为我不确定如何操作行 后续问题

我有三种不同的经济指标数据框架。列为年份,行为国家。我想取每个国家的行,并为每个国家形成一个数据框架,这样列是三个经济指标,行是年份

例如:奥地利

         GDP     |    CPI    |    Interest rate
1998年| xxxxxxxxxx | xxxxxxxxxx | xxxxxxxxxxxx

1999年| xxxxxxxxxx | xxxxxxxxxx | xxxxxxxxxxxx

在python中执行此操作时遇到困难,因为我不确定如何操作行

后续问题:

我现在有一个数据帧,看起来像这样:

按国家分列:[

           GDP | CPI    |    Interest rate
国家|奥地利|奥地利|奥地利

1998 | xx xx xx xx | xx xx xx | xxxxxxxx

1998 | xx xx xx xx | xx xx xx | xxxxxxxx

国家|比利时|比利时|比利时

1998年| xx xx xx xxx | xx xx xxx | xxxxxxxx

]

我希望能够调用这样的东西:Austria.GDP,belling.CPI,等等。我认为第一步应该是定义一个函数,在大数据框架内调用一个国家的信息,例如by_country(奥地利)

基本上,我希望能够称之为国家(奥地利)


你有什么想法吗

首先,您可以对每个数据框进行转置,使行为年份,列为国家,然后从3个数据框中分别提取每一列并将它们连接在一起。类似的内容将为每个国家提供一个数据框架:

gdp = gdp_df.transpose()
cpi = cpi_df.transpose()
interest = interest_df.transpose()

by_country = {}

# Assumes the same ordering of countries in each data frame
for country in gdp.columns:
    country_df = pandas.concat([gdp[country], cpi[country], interest[country]], axis=1)
    country_df.columns = ['GDP', 'CPI', 'Interest rate']
    by_country[country] = country_df
您现在可以执行以下操作:

by_country['Austria'].GDP

你能发布有代表性的原始输入数据,一些代码来重现你的dfs,以及所需的输出和你的尝试吗谢谢,你能看看我的后续问题吗?按国家[奥地利]。GDP不起作用,但按国家[0]。GDP起作用。我想这是因为by_country是一个列表,所以我们只能调用索引?有没有办法命名索引,例如索引:0,名称:Austria?我在编辑中将国家名作为关键字的字典改成了“
”。很抱歉,我没有明确说明这也被更改了。它是有效的,但类似于“由国家['Austria]”。GDP返回的是一个序列而不是一个浮点。有没有办法调整代码以返回一个浮点数?那个浮点数代表什么?你会得到一个系列,因为每年都有一个国家的GDP条目。例如,您可以通过
按_国家['Austria'].GDP.mean()
获取平均GDP,或者通过
按_国家['Austria']获取特定年份的值。loc['GDP',1998']
by_country['Austria'].GDP