Pandas Handling Large Files (chunksize)
When processing large data files, memory may be insufficient to load all the data at once. Pandas provides chunked reading, which can process data in batches.
Read CSV in chunks
The chunksize parameter
Example
import
pandas
as
pd
import
io
Simulate large file content (replace with a file path in actual use)
data
=
"""id,value
1,100
2,200
3,300
4,400
5,500
6,600
7,700
8,800
9,900
10,1000
"""
Read in chunks using chunksize
chunks
=
pd.
read_csv
(
io.
StringIO
(
data
)
,
chunksize
=
3
)
(
"Chunk processing:"
)
for
i
,
chunk
in
enumerate
(
chunks
)
:
(
f
"\nChunk {i+1}:"
)
(
chunk
)
Aggregate processing
Example
import
pandas
as
pd
import
io
import
numpy
as
np
Simulate a large file
data
=
"value\n"
"\n"
.
join
(
[
str
(
i
)
for
i
in
range
(
1
,
1001
)
]
)
Compute the sum in chunks
total
=
0
count
=
0
for
chunk
in
pd.
read_csv
(
io.
StringIO
(
data
)
,
chunksize
=
100
)
:
total +
=
chunk
[
"value"
]
.
sum
(
)
count +
=
len
(
chunk
)
(
f
"Total rows: {count}"
)
(
f
"Total: {total}"
)
(
f
"Average: {total / count}"
)
Incremental processing
Filter
Example
import
pandas
as
pd
import
io
Simulated data
data
=
"""id,value,category
1,100,A
2,200,B
3,150,A
4,300,C
5,250,B
6,180,A
"""
Filter data by specific conditions
filtered_chunks
=
[
]
for
chunk
in
pd.
read_csv
(
io.
StringIO
(
data
)
,
chunksize
=
2
)
:
filtered
=
chunk
[
chunk
[
"category"
]
==
"A"
]
if
len
(
filtered
)
0
:
filtered_chunks.
append
(
filtered
)
result
=
pd.
concat
(
filtered_chunks
)
(
"Data filtered where category='A':"
)
(
result
)
Multiprocessing in parallel
Example
import
pandas
as
pd
import
io
from
concurrent.
futures
import
ProcessPoolExecutor
Parallel processing (for CPU-intensive tasks)
def
process_chunk
(
chunk
)
:
"""Process a single data chunk"""
return
chunk
[
"value"
]
.
sum
(
)
Simulated data
data
=
"value\n"
"\n"
.
join
(
[
str
(
i
)
for
i
in
range
(
1
,
101
)
]
)
Prepare data chunks
chunks
=
list
(
pd.
read_csv
(
io.
StringIO
(
data
)
,
chunksize
=
10
)
)
Serial processing
total
=
sum
(
process_chunk
(
chunk
)
for
chunk
in
chunks
)
(
f
"Serial processing sum: {total}"
)
Process large JSON files
Example
import
pandas
as
pd
import
json
import
io
Simulate JSON Lines format data
jsonl_data
=
'\n'
.
join
(
[
json.
dumps
(
{
"id"
: i
,
"value"
: i *
10
}
)
for
i
in
range
(
1
,
101
)
]
)
Read JSON Lines in chunks
chunks
=
[
]
chunk_size
=
20
for
chunk
in
pd.
read_json
(
io.
StringIO
(
jsonl_data
)
,
lines
=
True
,
chunksize
=
chunk_size
)
:
chunks.
append
(
chunk
)
if
len
(
chunks
)
=
3
:
Process only the first 3 chunks as an example
break
result
=
pd.
concat
(
chunks
)
(
f
"Read {len(result)} rows of data"
)
(
result.
head
(
)
)
Chunked processing can significantly reduce memory usage but increases processing time. Choose the chunk size wisely to balance memory and time.