在本文中,我们将带你了解从Python中的巨大CSV文件中读取随机行在这篇文章中,我们将为您详细介绍从Python中的巨大CSV文件中读取随机行的方方面面,并解答python读取超大csv文件常见的疑
在本文中,我们将带你了解从Python中的巨大CSV文件中读取随机行在这篇文章中,我们将为您详细介绍从Python中的巨大CSV文件中读取随机行的方方面面,并解答python读取超大csv文件常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的c# – 从大文本文件中读取随机行、python pandas不从csv文件中读取第一列、Python-使用csv模块从csv文件中读取特定列?、Python-读取巨大的.csv文件。
本文目录一览:- 从Python中的巨大CSV文件中读取随机行(python读取超大csv文件)
- c# – 从大文本文件中读取随机行
- python pandas不从csv文件中读取第一列
- Python-使用csv模块从csv文件中读取特定列?
- Python-读取巨大的.csv文件
从Python中的巨大CSV文件中读取随机行(python读取超大csv文件)
我有一个很大的CSV文件(15 Gb),我需要从中读取大约一百万行。据我所见-并实现-Python中的CSV实用程序仅允许在文件中顺序迭代。
将所有文件读入内存以使用一些随机选择非常耗费内存,并且遍历所有文件并丢弃一些值并选择其他值非常耗时,因此, 无论如何 ,
是否有必要从CSV文件中选择一些随机行,只读那行?
我尝试没有成功:
import csv with open(''linear_e_LAN2A_F_0_435keV.csv'') as file: reader = csv.reader(file) print reader[someRandomInteger]
CSV文件示例:
331.093,329.735 251.188,249.994 374.468,373.782 295.643,295.159 83.9058,0 380.709,116.221 352.238,351.891 183.809,182.615 257.277,201.30261.4598,40.7106
答案1
小编典典import randomfilesize = 1500 #size of the really big fileoffset = random.randrange(filesize)f = open(''really_big_file'')f.seek(offset) #go to random positionf.readline() # discard - bound to be partial linerandom_line = f.readline() # bingo!# extra to handle last/first line edge casesif len(random_line) == 0: # we have hit the end f.seek(0) random_line = f.readline() # so we''ll grab the first line instead
正如@AndreBoos指出的那样,这种方法将导致选择偏向。如果知道线的最小和最大长度,则可以通过执行以下操作消除此偏差:
假设(在这种情况下)我们有min = 3和max = 15
1)找到前一行的长度(Lp)。
然后,如果Lp = 3,则该线的偏置最大。因此,如果Lp = 15,则该行应为100%的时间。我们只应选择20%的时间,因为它选择的可能性高5 *。
我们通过在以下时间随机保留行X%来实现此目的:
X =分钟/ Lp
如果我们不遵守要求,我们将进行另一个随机选择,直到骰子掷骰成功为止。:-)
c# – 从大文本文件中读取随机行
什么是最有效的方法:随机方法或新文件方法?
该程序将每5分钟运行一次,我使用的是c#4.5
解决方法
string line = File.ReadLines(FileName).Skip(X).First();
完整示例:
var fileName = @"C:\text.txt" var file = File.ReadLines(fileName).ToList(); int count = file.Count(); Random rnd = new Random(); int skip = rnd.Next(0,count); string line = file.Skip(skip).First(); Console.WriteLine(line);
python pandas不从csv文件中读取第一列
我有一个简单的2列csv文件,名为st1.csv:
GRID St1
1457 614
1458 657
1459 679
1460 732
1461 754
1462 811
1463 748
但是,当我尝试读取csv文件时,未加载第一列:
a = pandas.DataFrame.from_csv('st1.csv')
a.columns
输出:
Index([u'ST1'],dtype=object)
为什么不读取第一列?
Python-使用csv模块从csv文件中读取特定列?
我正在尝试解析一个csv文件,并仅从特定列中提取数据。
范例csv:
ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
我想只捕获特定的列,说ID
,Name
,Zip
和Phone
。
我看过的代码使我相信我可以通过其对应的编号来调用特定的列,即:Name
将对应于2并遍历每一行使用row[2]
会产生列2中的所有项目。只有它不能。
到目前为止,这是我所做的:
import sys, argparse, csvfrom settings import *# command argumentsparser = argparse.ArgumentParser(description=''csv to postgres'',\ fromfile_prefix_chars="@" )parser.add_argument(''file'', help=''csv file to import'', action=''store'')args = parser.parse_args()csv_file = args.file# open csv filewith open(csv_file, ''rb'') as csvfile: # get number of columns for line in csvfile.readlines(): array = line.split('','') first_item = array[0] num_columns = len(array) csvfile.seek(0) reader = csv.reader(csvfile, delimiter='' '') included_cols = [1, 2, 6, 7] for row in reader: content = list(row[i] for i in included_cols) print content
并且我希望这只会打印出我想要的每一行的特定列,除非不是,我只会得到最后一列。
答案1
小编典典你会得到从这个代码的最后一列的唯一方法是,如果你不包括你的print语句中的for
循环。
这很可能是代码的结尾:
for row in reader: content = list(row[i] for i in included_cols)print content
你希望它是这样的:
for row in reader: content = list(row[i] for i in included_cols) print content
既然我们已经解决了你的错误,那么我想花时间向你介绍pandas模块。
Pandas在处理csv文件方面非常出色,以下代码将是你读取csv并将整列保存到变量中所需的全部:
import pandas as pddf = pd.read_csv(csv_file)saved_column = df.column_name #you can also use df[''column_name'']
因此,如果你想将列中的所有信息保存Names到变量中,则只需执行以下操作:
names = df.Names
这是一个很棒的模块,建议你研究一下。如果由于某种原因你的打印语句处于for
循环状态,并且仍然仅打印出最后一列,则不应该发生,但是请让我知道我的假设是否错误。你发布的代码有很多缩进错误,因此很难知道应该在哪里。希望这对你有所帮助!
Python-读取巨大的.csv文件
如何解决Python-读取巨大的.csv文件?
你正在将所有行读入列表,然后处理该列表。不要那样做。
在生成行时对其进行处理。如果需要首先过滤数据,请使用生成器函数:
import csv
def getstuff(filename, criterion):
with open(filename, "rb") as csvfile:
datareader = csv.reader(csvfile)
yield next(datareader) # yield the header row
count = 0
for row in datareader:
if row[3] == criterion:
yield row
count += 1
elif count:
# done when having read a consecutive series of rows
return
我还简化了你的过滤器测试;逻辑相同,但更为简洁。
因为只匹配与条件匹配的单个行序列,所以还可以使用:
import csv
from itertools import dropwhile, takewhile
def getstuff(filename, criterion):
with open(filename, "rb") as csvfile:
datareader = csv.reader(csvfile)
yield next(datareader) # yield the header row
# first row, plus any subsequent rows that match, then stop
# reading altogether
# Python 2: use `for row in takewhile(...): yield row` instead
# instead of `yield from takewhile(...)`.
yield from takewhile(
lambda r: r[3] == criterion,
dropwhile(lambda r: r[3] != criterion, datareader))
return
你现在可以getstuff()直接循环。在getdata():
def getdata(filename, criteria):
for criterion in criteria:
for row in getstuff(filename, criterion):
yield row
现在直接getdata()在你的代码中循环:
for row in getdata(somefilename, sequence_of_criteria):
# process row
现在,你仅在内存中保留一行,而不是每个条件存储数千行。
解决方法
我目前正在尝试从Python 2.7中的.csv文件中读取数据,该文件最多包含100万行和200列(文件范围从100mb到1.6gb)。对于少于300,000行的文件,我可以(非常缓慢地)执行此操作,但是一旦超过该行,就会出现内存错误。我的代码如下所示:
def getdata(filename,criteria):
data=[]
for criterion in criteria:
data.append(getstuff(filename,criteron))
return data
def getstuff(filename,criterion):
import csv
data=[]
with open(filename,"rb") as csvfile:
datareader=csv.reader(csvfile)
for row in datareader:
if row[3]=="column header":
data.append(row)
elif len(data)<2 and row[3]!=criterion:
pass
elif row[3]==criterion:
data.append(row)
else:
return data
在getstuff函数中使用else子句的原因是,所有符合条件的元素都将一起列在csv文件中,因此,经过它们以节省时间时,我离开了循环。
我的问题是:
-
我如何设法使其与较大的文件一起使用?
-
有什么办法可以使它更快?
我的计算机具有8gb RAM,运行64位Windows 7,处理器为3.40 GHz(不确定您需要什么信息)。
今天的关于从Python中的巨大CSV文件中读取随机行和python读取超大csv文件的分享已经结束,谢谢您的关注,如果想了解更多关于c# – 从大文本文件中读取随机行、python pandas不从csv文件中读取第一列、Python-使用csv模块从csv文件中读取特定列?、Python-读取巨大的.csv文件的相关知识,请在本站进行查询。
本文标签: