如何在NumPy中将CSV数据读入记录数组?

565

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

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

14个回答

6

最新的pandas和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()

4

我尝试了这个:

import pandas as p
import numpy as n

closingValue = p.read_csv("<FILENAME>", usecols=[4], dtype=float)
print(closingValue)

0
In [329]: %time my_data = genfromtxt('one.csv', delimiter=',')
CPU times: user 19.8 s, sys: 4.58 s, total: 24.4 s
Wall time: 24.4 s

In [330]: %time df = pd.read_csv("one.csv", skiprows=20)
CPU times: user 1.06 s, sys: 312 ms, total: 1.38 s
Wall time: 1.38 s

1
请编辑问题,提供更多关于您解决方案的信息。 - Ruli

-1

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

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)

2
OP要求直接读取到numpy数组。将其作为dataframe读取并转换为numpy array需要更多的存储空间和时间。 - user3503711
是的,没错。但如果上面的方法不起作用,我刚刚提供了另一种可能的解决方案。 - Ovu Sunday

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接