如何将“是”和“否”相加成一个总数,使用matplotlib、pandas、python从CSV导入来绘制一个图形

2024-06-07 06:00:47 发布

您现在位置:Python中文网/ 问答频道 /正文

[m][1]

问题#1)我对python和一般的代码都不熟悉。我想从一个CSV中获取数据,该CSV有一列标记为“U.S.OSHA Recordable?”。在那一栏里,每个答案不是“是”就是“否”。我想展示一个绘图栏显示“23个是”和“7个不是”。基本上是将列中“是”和“否”的总数相加,然后在1个干净的条形图中显示总数。它将显示两个条形图,总数字位于两个条形图的顶部。。。。问题是,条形图现在在X轴上有一条直线,每条直线分别表示27次“不,是,不,是,不”。我希望用户可以很容易地看到1个条形图显示只有2个总在顶部像这张图片条。你知道吗

这是我的代码,我不知道我需要什么来总结是和否一栏。你知道吗

import pandas as pd # powerful data visualization library
import numpy as np
import matplotlib.pyplot as plt # allows us to plot things
import csv # allows us to import and use CSV commands which are simple but effective


data = pd.read_csv(r'C:\Users\rmond\Downloads\PS_csvFile.csv', encoding="ISO-8859-1", skiprows=6) #skiprows allows you to skip the comments on top... & ecoding allows pandas to work on this CSV
data.head() # this will give the first row that you want it to read the header
data.plot.bar(x='U.S. OSHA Recordable?') #creates a plot in pandas
plt.show() # shows the plot to the user

Tags: csvtheto代码importpandasdataplot
2条回答
df['Val'].value_counts().plot(kind='bar')

这里Val是包含“Yes”和“No”的列的名称

enter image description here

import pandas as pd # powerful data visualization library
import numpy as np
import matplotlib.pyplot as plt # allows us to plot things
import csv # allows us to import and use CSV commands which are simple but effective
import seaborn as sns # it counts everything for you and outputs it exactly like I want
# This website saved my life https://www.pythonforengineers.com/introduction-to-pandas/
# use this to check the available styles: plt.style.available


data = pd.read_csv(r'C:\Users\rmond\Downloads\PS_csvFile.csv', encoding="ISO-8859-1", skiprows=6) #skiprows allows you to skip the comments on top... & ecoding allows pandas to work on this CSV
sns.set(style="whitegrid")
ax = sns.countplot(x='U.S. OSHA Recordable?', data=data)
plt.show() # shows the plot to the user

有趣的是,我发现了关于“海洋出生”的事,我安装了它并尝试了一下。它应该从一个URL中提取数据,但是在查看了其他一些关于堆栈溢出的页面之后,我发现了一个很好的建议。不管怎么说,这很好,它为我做了一切。我对这个解决方案很满意。现在到下一个问题,哈哈。我希望这有助于其他人在未来。你知道吗

我的图表看起来完全一样的SH-SF顺便说一句。工程伟大

相关问题 更多 >