You can use the pandas library in Python to read the CSV file, filter the intergenic regions based on the specified criteria, and then write the filtered data back to a new CSV file. Below is a Python script that accomplishes this task:
import pandas as pd
# Load the CSV file
input_file = 'genes_averages.csv'
output_file = 'genes_averages-filtered.csv'
# Read the CSV file with the correct delimiter
df = pd.read_csv(input_file, delimiter=';')
# Calculate the length of each region
df['length'] = df['ending bp'] - df['starting bp']
# Filter out intergenic regions shorter than 137 bp
filtered_df = df[(df['Gene name'].str.startswith('INTERGENIC')) & (df['length'] >= 137)]
# Drop the 'length' column as it's no longer needed
filtered_df = filtered_df.drop(columns=['length'])
# Write the filtered DataFrame to a new CSV file
filtered_df.to_csv(output_file, sep=';', index=False)
print(f"Filtered data has been saved to {output_file}")
Explanation:
- Importing Libraries: The script starts by importing the
pandas library, which is essential for data manipulation.
- Reading the CSV File: The
pd.read_csv() function reads the input CSV file, specifying the delimiter as ;.
- Calculating Lengths: A new column
length is created to store the difference between ending bp and starting bp.
- Filtering Data: The DataFrame is filtered to keep only the intergenic regions (
Gene name starting with "INTERGENIC") that have a length of 137 bp or more.
- Dropping Unnecessary Columns: The
length column is dropped from the filtered DataFrame since it is no longer needed.
- Writing to CSV: The filtered DataFrame is written to a new CSV file using
to_csv(), again specifying the delimiter as ;.
- Completion Message: A message is printed to indicate that the filtered data has been saved.
Note:
Make sure you have the pandas library installed. You can install it using pip if you haven't done so:
pip install pandas
You can run this script in your Python environment, and it will create the filtered CSV file as specified.