是否有一种直接的方法将CSV文件的内容导入到记录数组中,就像R的read.table(), read.delim()和read.csv()将数据导入到R数据框架中一样?

或者我应该使用csv.reader(),然后应用numpy.core.records.fromrecords()?


当前回答

这是一个非常简单的任务,最好的方法如下

import pandas as pd
import numpy as np


df = pd.read_csv(r'C:\Users\Ron\Desktop\Clients.csv')   #read the file (put 'r' before the path string to address any special characters in the file such as \). Don't forget to put the file name at the end of the path + ".csv"

print(df)`

y = np.array(df)

其他回答

这件作品很有魅力……

import csv
with open("data.csv", 'r') as f:
    data = list(csv.reader(f, delimiter=";"))

import numpy as np
data = np.array(data, dtype=np.float)

您可以使用此代码将CSV文件数据发送到数组中:

import numpy as np
csv = np.genfromtxt('test.csv', delimiter=",")
print(csv)

还可以尝试recfromcsv(),它可以猜测数据类型并返回正确格式化的记录数组。

使用numpy.genfromtxt(),将分隔符kwarg设置为逗号:

from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')

可在最新的熊猫和numpy版本。

import pandas as pd
import numpy as np

data = pd.read_csv('data.csv', header=None)

# Discover, visualize, and preprocess data using pandas if needed.

data = data.to_numpy()