python - 图形的 Python/Pandas 结构化/索引
问题描述
- 尝试将仅包含在每行中重复的系列名称的列更改为具有各自值的自己的列。
- 这样做是为了使绘制/绘制数据更容易
从
[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 年。
解决方案
您可以使用列表推导轻松做到这一点。列表推导式是一种快速、简单的方法,可以从本系列中提取您想要的数据(即国家名称和 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)
推荐阅读
- perl - 当 SIGALRM 在 perl 中引发异常时,面临“refcnt:fd -1 < 0”错误
- r - 如何在R中的服务日内生成特定时期
- python - 如何从另一个 python 文件写入 python 驱动的配置文件
- android - glMapBufferRange 在三星 Galaxy S8 / S10 / Note 10 Lite 上出现 GL_OUT_OF_MEMORY 失败
- php - Symfony 选择注入什么类
- webdriver-io - 无法添加自定义命令
- android - 用于获取图像的单独可绘制文件夹
- ruby-on-rails - 如何将 facebook glyphicon 添加到 rails link_to
- http - 捕获微服务中的服务间通信
- c# - How to setup settings from a windows service at installation?