[英]I'm trying to install django in virtual environment but getting some error and I don't understand what is it about
[英]I'm trying to plot a pie chart using data from a CSV file but I'm getting an error I don't understand
这是我尝试过的代码。 CSV文件的SS和错误附在下面。
def displayGraph():
with open('seats.csv', newline='') as csvfile:
s = pd.read_csv(csvfile)
x=0
y=0
for p in range(48):
if s[p]==0:
x+=1
for g in range(48):
if s[g]==1:
y+=1
a=x/(x+y) *100
b=y/(x+y) *100
graph=[a,b]
plt.pie(graph, labels=['Empty Seats', 'Booked Seats'])
https://imgur.com/XCMJMal错误(第 1 部分)
https://imgur.com/UsJmrVb错误(第 2 部分)
https://imgur.com/a/6WbeRGV CSV 文件
CSV 文件以文本格式提供如下:
0,0,1,1,0,1,1,1
0,1,1,0,0,1,0,1
1,0,0,1,0,1,1,0
0,1,1,1,0,0,0,1
0,0,1,1,0,1,0,0
1,1,1,1,0,0,1,1
csv 模块和 Pandas 是处理 CSV 文件的两种方式,但除此之外它们是不相关的并且使用方式不同。 在这里,您已使用 pandas 加载文件并按原样使用csv.reader
。 你应该选择一个。
csv
模块方式
with open('seats.csv', newline='') as csvfile:
s = csv.reader(csvfile)
x = 0
y = 0
for row in s:
for val in row:
if val == '1': # csv module sets values as strings...
y += 1
else:
x += 1
a=x/(x+y) *100
b=y/(x+y) *100
graph=[a,b]
plt.pie(graph, labels=['Empty Seats', 'Booked Seats'])
Pandas 方式(这里更神奇......)
df = pd.read_csv('seats.csv', header = None)
y = df.sum().sum()
x = len(df) * len(df.columns) - y
a=x/(x+y) *100
b=y/(x+y) *100
graph=[a,b]
plt.pie(graph, labels=['Empty Seats', 'Booked Seats'])
您是否尝试过实际查看 DataFrame 的内容?
在 Python 中像这样访问 DataFrame:
表.csv:
A | B | C
-----------------
0.1 | 0.2 | 0.3
------------------
0.4 | 0.5 | 0.6
------------------
脚本:
pd.read_csv("table.csv")
print(list(pd["A"]))
OUTPUT
[0.1,0.4]
您的 csv 没有任何列名,因此您不能只执行 s[p],这就是它抛出 KeyError: 0 的原因(您的 csv 中不存在名为“0”的列)
您需要使用 iloc:(如果 p 指的是列索引)
s.iloc[:,p]
或者如果 p 指的是行索引
s.iloc[p,:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.