numpy 如何在python中处理csv文件的数据?[duplicate]

cetgtptt  于 2023-03-30  发布在  Python
关注(0)|答案(3)|浏览(114)

此问题在此处已有答案

How do I read CSV data into a record array in NumPy?(14个答案)
昨天关门了。
我有一个csv文件,我需要遍历每一行,访问每一行的特定字段,并在下一阶段使用这些数据。
正在考虑使用一些numpy load csv方法。

v1uwarro

v1uwarro1#

这应该行得通。

pip install csv
with open('my-csv-file.csv', newline='') as csvFile:
    csvData = csv.reader(csvFile, delimiter=',', quotechar='|')
    for row in csvData:
        print(', '.join(row))
qaxu7uf2

qaxu7uf22#

最流行的表格数据处理库是pandas
样本数据-

csv = '''"Header1", "Header2"
"Replace", 100
"string", 200
"with", 300
"file location", 400
"or url", 500'''

只导入一列的代码-

import pandas
data = pandas.read_csv(csv, headers=["header1"]

打印数据会给出一个表,如

|"Header1"       |
|----------------|
|"Replace"       |
|"string"        |
|"with"          |
|"file location" |
|"or url"        |

更多信息:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

c3frrgcw

c3frrgcw3#

使用NumPy加载CSV

Numpy确实提供了一个功能,叫做np.loadtxt

import numpy as np
 
# using loadtxt()
arr = np.loadtxt("sample_data.csv",
                 delimiter=",", dtype=str)
display(arr)

使用Python的csv库将CSV加载到数组中

Python也为此提供了一个csv library

import csv
with open('sample_data.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        print(', '.join(row))

使用内置Python加载CSV

或者,你实际上不需要使用第三方库。CSV只是一个用逗号分隔的文本文件。知道这一点,你可以使用Python内置的方法来解析它。

with open("data.csv") as data:
    for line in data:
        items = [item for item in line.split(",")]
        print(items)

相关问题