我希望能夠制作帶有某個房間出現次數的條形圖(存盤在 csv 檔案中)。房間的數量在開始時沒有定義。
這是存盤在 csv 檔案中的資料:

這是我想顯示的圖表型別,但使用我目前擁有的代碼,它沒有顯示出現次數。

我能做些什么來解決這個問題?
到目前為止,這是我的代碼。
with open('calls.csv') as File:
plots = csv.reader(File, delimiter = ',')
for row in plots:
if (row[0] not in x):
x.append(row[0])
numberOfRooms = len(x)
for i in range(numberOfRooms):
occurence = 0
for row in plots:
if(x[i] == row[0]):
occurence = 1
y.append(occurence)
plt.bar(x,y, width = 0.7, label="Number of calls")
plt.xlabel('room')
plt.ylabel('number of calls')
plt.title('Number of calls per room')
plt.legend()
plt.show()
uj5u.com熱心網友回復:
由于您標記了 Pandas,您可以執行以下操作:
# read dataframe from csv
df = pd.read_csv('calls.csv')
# count the values in the first column
counts = df.iloc[:,0].value_counts()
# plot the count
counts.plot.bar()
也就是說,您當然可以使用csv包,但您可能應該使用不同的資料結構,例如字典:
with open('calls.csv') as File:
data = csv.reader(File, delimiter = ',')
counts = {}
# loop through data
for row in data:
room = row[0]
# initiate if room is first seen
if room not in counts: counts[room] = 0
# increase the count
counts[room] = 1
# plot the counts
plt.bar(list(counts.keys()), list(counts.values()) )
uj5u.com熱心網友回復:
對于這樣的任務,只使用“內置”,我會使用字典來積累資料
data = {}
with open('calls.csv') as File:
plots = csv.reader(File, delimiter = ',')
for row in plots:
# increments the counter of occurrences,
# if the key is not already in there, .get() will return the 0 as a default
data[row[0]] = data.get(row[0],0) 1
# at this point we have processed the whole file, so let's prepare data for plotting
# we take the keys of the dictionary and sort them for the x axis
x = list(data.keys())
x.sort()
# the we take the values, the count of occurrences, in the same order
y = [data[i] for i in x]
# then just ... plot it.
plt.bar(x, y, width = 0.7, label="Number of calls")
plt.xlabel('room')
plt.ylabel('number of calls')
plt.title('Number of calls per room')
plt.legend()
plt.show()
uj5u.com熱心網友回復:
如果沒有pandas,您可以將每個房間的呼叫次數保存在 a 中dict并使用它來繪制:
import csv
import matplotlib.pyplot as plt
rooms = dict()
with open("calls.csv") as infile:
csvreader = csv.reader(infile)
for row in csvreader:
if row[0] not in rooms:
rooms[row[0]] = 0
rooms[row[0]] = 1
plt.bar(rooms.keys(), rooms.values(), width=0.7)
plt.xlabel("room")
plt.ylabel("number of calls")
plt.title("Number of calls per room")
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383660.html
標籤:Python 熊猫 文件 matplotlib
下一篇:在箭袋圖中的箭頭之間填充顏色
