To improve the performance of your code, you can make several optimizations. The nature of your task involves I/O bound operations (reading and writing files) as well as CPU bound operations (processing data). Here are some suggestions for optimizations:
-
Use Efficient File I/O Operations: You're already doing a good job by avoiding loading unnecessary rows with skiprows=1. Ensure the data types are optimally defined when reading large CSVs to reduce memory usage. For massive files, consider processing them in chunks.
-
Avoid Listing Directories Repeatedly: You're currently using os.listdir() inside a loop, which is fine for your purpose as you're iterating through it just once. Just make sure to avoid redundant directory listings.
-
Minimize DataFrame Operations: DataFrame operations can be costly, especially on large datasets. You're already doing a minimal amount of work, which is great. Consider specifying usecols in pd.read_csv if you only need to modify certain columns and the rest of the data is irrelevant. This can reduce memory usage significantly.
-
Parallel Processing: For tasks like these, where processing of each file is independent of others, consider using parallel processing to utilize multiple CPU cores. Python's concurrent.futures module or third-party libraries like joblib can be used for parallelizing I/O and CPU-bound operations. Here is an example of how you might adapt your code to use concurrent.futures.ThreadPoolExecutor for I/O-bound operations:
import pandas as pd
import os
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
def process_file(file_path):
try:
df = pd.read_csv(file_path, skiprows=1)
columns = df.columns.tolist()
if len(columns) >= 9:
columns[7] = 'volume_crypto'
columns[8] = 'volume_base'
df.columns = columns
df.to_csv(file_path, index=False)
print(f"Renamed {file_path}")
except Exception as e:
print(f"Failed to process {file_path} due to {e}")
def main():
base_directory_path= r"..\downloaded_files\Binance\00_rename_columns_sort"
folders = [d for d in Path(base_directory_path).iterdir() if d.is_dir()]
with ThreadPoolExecutor() as executor:
futures = []
for folder in folders:
for filename in os.listdir(folder):
if filename.endswith('.csv'):
file_path = os.path.join(folder, filename)
futures.append(executor.submit(process_file, file_path))
for future in as_completed(futures):
pass # Future results or exceptions can be processed here if needed
if __name__ == "__main__":
main()
Note: While using multi-threading and multi-processing, be cautious about the resources on your machine. For IO-bound tasks like file reading and writing, ThreadPoolExecutor is generally a good choice, but if you deal with very large data transformations, ProcessPoolExecutor might be more appropriate, as it can take advantage of multiple CPU cores. Always test and monitor the resource usage to avoid overwhelming your system.