首页 > 解决方案 > 从python语言的excel表中获取特定“字符串”的相应单元格值以绘制线/散点图

问题描述

country name == 'Argentina'我只想从整个数据中绘制与其对应的“值”相对应的线/散点图。

样本数据

是

总数据文件

这是我的代码

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_excel("C:/Users/kdandebo/Desktop/Models/Python excercise/Data3.xlsx")
x = (df['Country Name'])

#Although i have figured out x cannot be compared to a string named Argentina, i couldnt think of any other way, Also ive tried the below version too, but none works
#if (df['Country Name'] == 'Argentina'):
#    y = (df['Value'])
for x == ("Argentina"):
    y = (df['Value'])
plt.scatter(x,y)
plt.show()

标签: pythonpython-3.xpython-2.7python-requestsspyder

解决方案


在你开始制作情节之前,首先你应该提取关于阿根廷的数据。

import pandas as pd
import matplotlib.pyplot as plt
# Define the headers
headers = ["SeriesName", "CountryName", "Time", "Value"]
# Read in the Excel file
df_raw = pd.read_excel("C:/1/Data3.xlsx",header=None, names=headers)
# extract data to only Argentina
country = ["Argentina"]
# Create a copy of the data with only the Argentina
df = df_raw[df_raw.CountryName.isin(country)].copy()
#print(df)

提取后,您只能使用 Pandas 来制作情节。

'''Pandas plot'''
df.plot.line(x='Time', y='Value', c='Red',legend =0, title = "ARGENTINA GDP per capita")
plt.show()

您还可以通过 Matplotlib 库和 Seaborn 或 Plotly 进行绘图。

# Create plot from matplotlib
plt.figure()
plt.scatter(df.Value, df.Time)
plt.xlabel('GPD Value')
plt.ylabel('Years')
plt.title('''ARGENTINA
          GDP per capita (constant 2010 US$) ''')
plt.show()

在此处输入图像描述

希伯恩情节

import seaborn as sns
sns.scatterplot(x="Value", y="Time", data=df, color = 'DarkBlue')
plt.subplots_adjust(top=0.9)
plt.suptitle("ARGENTINA GDP per capita")
plt.show()

情节情节

import plotly
import plotly.graph_objs as go

trace = go.Scatter(x = df.Time, y = df.Value)
data = [trace]
plotly.offline.plot({"data": data}, filename='Argentina GDP.html')

推荐阅读