[英]Skip multiple rows using pandas.read_csv
我正在分塊讀取一個較大的csv文件,因為我沒有足夠的內存來存儲。 我想讀取其前10行(0至9行),跳過接下來的10行(10至19行),然后閱讀接下來的10行(20至29行),再次跳過接下來的10行(30至39行) ),然后讀取40到49之間的行,依此類推。 以下是我正在使用的代碼:
#initializing n1 and n2 variable
n1=1
n2=2
#reading data in chunks
for chunk in pd.read_csv('../input/train.csv',chunksize=10, dtype=dtypes,skiprows=list(range( ((n1*10)+1), ((n2*10) +1) ))):
sample_chunk=chunk
#displaying the sample_chunk
print(sample_chunk)
#incrementing n1
n1=n1+2
#incrementing n2
n2=n2+2
但是,該代碼不起作用,正如我認為的那樣。 它僅跳過10到19的行(即:它讀取0到9的行,跳過10到19,然后讀取20到29,然后再次讀取30到39,然后再次讀取40到49,並繼續讀取所有行)。 請幫助我確定我在做什么錯。
使用您的方法,您需要在初始化pd.read_csv
時定義所有的skiprows
,
rowskips = [i for x in range(1,int(lengthOfFile/10),2) for i in range(x*10, (x+1)*10)]
lengthOfFile
是文件的長度。
然后對於pd.read_csv
pd.read_csv('../input/train.csv',chunksize=10, dtype=dtypes,skiprows=rowskips)
從文檔中:
skiprows : list-like, int or callable, optional
Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file.
If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be lambda x: x in [0, 2].
因此,您可以傳遞list
, int
或callable
,
int
>它跳過文件開頭的給定行
list
- >它跳過給出的行數list
callable
- >它的計算結果與所述的行號callable
,然后決定跳過或沒有。
您正在傳遞在啟動時指定要跳過的行的list
。 您無法再次更新。 另一種方法可能是在行跳過中傳遞可調用的lamda x: x in rowskips
它將評估行是否適合要跳過的條件。
碼:
ro = list(range(0, lengthOfFile + 10, 10))
d = [j + 1 for i in range(1, len(ro), 2) for j in range(ro[i], ro[i + 1])]
# print(ro)
print(d)
pd.read_csv('../input/train.csv',chunksize=10, dtype=dtypes,skiprows=d)
例如:
lengthOfFile = 100
ro = list(range(0, lengthOfFile + 10, 10))
d = [j for i in range(1, len(ro), 2) for j in range(ro[i], ro[i + 1])]
print(d)
輸出: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.