繁体   English   中英

Python:csv 文件和字典没有 Pandas

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM