[英]Python: csv file and dictionary without Pandas
我正在嘗試解決一個簡單的問題...我有一個名為 data.csv 的文件,其中包含以下數據:
enroll_code,student_id
10030,55000
10030,55804
10250,55804
10510,55000
我要做的是加載文件,讀取內容,並獲取每個enroll_code 的值數。 不使用 Pandas 怎么辦? 這是我到目前為止所嘗試的......
file = open('data.csv')
csv_reader = csv.reader(file)
next(csv_reader)
for key, value in csv_reader.items():
print(key, len([item for item in csv_reader if item]))
我認為您在正確讀取 CSV 文件時遇到問題。 這是讀取 CSV 的片段。
In [8]: import csv
...: with open("data.csv", 'r') as file:
...: csv_file = csv.DictReader(file)
...: count = {}
...: for row in csv_file:
...: entry = dict(row)
...: if entry['enroll_code'] in count:
...: count[entry['enroll_code']] +=1
...: else:
...: count[entry['enroll_code']] = 1
...: print(count)
...:
...:
...:
{'10030': 2, '10250': 1, '10510': 1}
在 for 循環中添加計算所有注冊的邏輯,您可以使用字典來完成。 一切順利。
不使用 Pandas。 如何才能做到這一點?
假設您閱讀了.csv之類的
0,1,1,2,3,
簡答
Numpy。
tmp = np.loadtxt(path, dtype=np.str, delimiter=",")
獲取數據的長度。 只需打印 tmp 的形狀。
print(tmp.shape)
在不使用任何庫的情況下制作它。
def csv_reader(datafile):
data = []
with open(datafile, "r") as f:
header = f.readline().split(",") # 獲取表頭
counter = 0
for line in f:
data.append(line) # you can split the line later.
fields = line.split(",")
print("line: ",line, " ", fields)
counter += 1
return data
if __name__ == '__main__':
csv_reader("0.csv")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.