【问题标题】:Pandas import two csv files and plot specific dataPandas 导入两个 csv 文件并绘制特定数据
【发布时间】:2020-03-06 05:37:39
【问题描述】:

link 1
link 2 *我复制了表格并创建了csv文件

我需要将文件 1 中的总人口和新泽西州的信徒总数绘制为折线图或条形图以进行比较。

我试过 append 来合并两个 cvs,但结果很奇怪

import pandas as pd
import matplotlib.pyplot as plt

clifton_data = pd.read_csv('cliftondata2010census.csv')

religion = pd.read_csv('2010_ Top Five States by Adherence Rate - Sheet1.csv')

all_data = clifton_data.append(religion)
all_data.plot()
all_data.plot(kind='line',x='1',y='2') # scatter plot
all_data.plot(kind='density')

我需要从文件 1 中绘制总人口图,并以折线图或条形图与新泽西州的信徒总数进行比较。

【问题讨论】:

  • 网站上没有数据。可以分享一下样品吗?

标签: python python-3.x pandas matplotlib jupyter-notebook


【解决方案1】:

这里有一个快速指南让你盯着看。希望对你有帮助。

从链接 2,你看到

Massachusetts   641     2,940,199   449.05
Rhode Island    159     466,598     443.30
New Jersey      729     3,235,290   367.99
Connecticut     399     1,252,936   350.56
New York        1,630   6,286,916   324.43

复制上面的文字,粘贴并保存数据到congregation.txt

链接 1 已损坏。但是,假设人口数据如下,

Massachusetts   3,141,270
Rhode Island    530,698
New Jersey      4,335,399
Connecticut     2,134,935
New York        10,366,556

同样,复制上面的文字,粘贴并保存数据到population.txt

然后,你可以运行这样的东西

import pandas as pd
import matplotlib.pyplot as plt

con = pd.read_csv('congregation.txt', sep=r'[ \t]{2,}',header=None, index_col=False,engine='python')
pop = pd.read_csv('population.txt', sep=r'[ \t]{2,}',header=None, index_col=False,engine='python')

#note concat and not append
#con[0] is state, con[2] is congregation, pop[1] is population
#print(con.head()) and print(pop.head()) to visualize if you are still confused
df = pd.concat([con[[0,2]],pop[1]],axis=1)

df.columns = ['State', 'Congregation', 'Population']

#need to do some cleaning here to convert numbers with comma to an integer
df['Congregation'] = df['Congregation'].apply(lambda t: t.replace(',','')).astype(int)
df['Population'] = df['Population'].apply(lambda t: t.replace(',','')).astype(int)

df.set_index('State',inplace=True)

print(df.head())
#at this stage your df looks like this
#               Congregation  Population
#State                                  
#Massachusetts       2940199     3141270
#Rhode Island         466598      530698
#New Jersey          3235290     4335399
#Connecticut         1252936     2134935
#New York            6286916    10366556

输出

注意:这里我保留其他状态是为了演示,否则如果只是新泽西,条形图会看起来是空的。

ax = df.plot.bar()
plt.show()

编辑:我的意思是“信徒”而不是“会众”。我在那里犯了一个错误。

【讨论】:

  • 这是 2010 年新泽西州克利夫顿人口的链接 factfinder.census.gov/faces/tableservices/jsf/pages/…..... 我需要比较 2010 年新泽西州克利夫顿人口与新泽西州信徒总数
  • 我也收到错误:int() 以 10 为基数的无效文字:'Adherents'
  • @WhitneyHughes 新链接对我不起作用 - American FactFinder 出现错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-05
  • 2019-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多