首页 > 解决方案 > 图形的 Python/Pandas 结构化/索引

问题描述

  1. 尝试将仅包含在每行中重复的系列名称的列更改为具有各自值的自己的列。
  1. 这样做是为了使绘制/绘制数据更容易

[Country, Series(GDP), Time(2018)]

[US, GDP, 123432]
[UK, GDP, 4345]
[China, GDP, 5722]
[Russia, GDP, 57764]
etc...

[Country, GDP(@2018)]

[US, 123432]
[UK, 4345]
[China, 5722]
[Russia, 57764]
etc...

我猜这与更改索引(?)有关。我可以根据“国家”而不是默认的 0、1、2、3 等对其进行索引,但这对于以后的绘图目的是否正确?

进一步查询:

实际数据集由 apprx 组成。80 个国家、70 个系列及其各自的值(例如:GDP 120941、GNI 9717)和 30 年。

标签: pythonindexingdata-structures

解决方案


您可以使用列表推导轻松做到这一点。列表推导式是一种快速、简单的方法,可以从本系列中提取您想要的数据(即国家名称和 gdp)。然后,您可以将这些名为 country 和 gdp 的新列表放回数据框中以查看和绘制图表。

您不需要将索引更改为 Country,但我想这取决于您要对数据框做什么以及您希望如何绘制它。

import pandas as pd

#Original Data, all just lists in one column
data = [['US', 'GDP', 123432],['UK', 'GDP', 4345],['China', 'GDP', 5722],
        ['Russia', 'GDP', 57764]]
df = pd.DataFrame({'Column_1': data})

#Pluck out countries and gdps from the lists using list comprehensions
country = [row[0] for row in df['Column_1']]
gdp = [row[2] for row in df['Column_1']]

#Create a new dataframe
df_new = pd.DataFrame({'Country': country, 'GDP(@2018)': gdp})
display(df_new) 

推荐阅读