Here's the modified code that puts the smallest 85% of scores in one box and then creates additional boxes in steps of 2.5%:
import pandas as pd
import numpy as np
df = pd.read_csv('deltacoverage-multi.tsv', sep='\t')
# Calculate the 85th percentile of sliding_scores
percentile_85 = np.percentile(df['sliding_scores'], 85)
# Define bins: lowest 85% in one box, then each 2.5% above that in its own box
percentiles = np.arange(85, 100, 2.5)
bins = [-np.inf, percentile_85] + [np.percentile(df['sliding_scores'], p) for p in percentiles] + [np.inf]
# Custom labels for the bins
labels = ['lowest_85'] + [f'percentile_{p}' for p in percentiles]
# Apply the custom binning
df['box'] = pd.cut(df['sliding_scores'], bins=bins, labels=labels, right=False, include_lowest=True)
# Identify delta columns
delta_cols = [col for col in df.columns if col.startswith('delta')]
# Group by box and calculate mean of delta columns
grouped_df = df.groupby('box')[delta_cols].mean()
grouped_df['delta0'] = 0
# Reset index and extract box boundaries
grouped_df = grouped_df.reset_index()
grouped_df['box_start'] = grouped_df['box'].apply(lambda x: bins[labels.index(x)])
grouped_df['box_end'] = grouped_df['box'].apply(lambda x: bins[labels.index(x) + 1])
# Handle -np.inf and np.inf in box boundaries
grouped_df['box_start'] = grouped_df['box_start'].replace({-np.inf: '-inf', np.inf: 'inf'})
grouped_df['box_end'] = grouped_df['box_end'].replace({-np.inf: '-inf', np.inf: 'inf'})
# Define output columns and save to file
output_cols = ['box_start', 'box_end'] + delta_cols
output_df = grouped_df[output_cols]
output_filename = 'average_deltas_by_box-85-2.5percentile.tsv'
output_df.to_csv(output_filename, sep='\t', index=False)
print(f"Saved {len(output_df)} rows to {output_filename}")
Key Changes:
-
Binning Logic:
- The lowest 85% of
sliding_scores are grouped into a single box labeled 'lowest_85'.
- Each subsequent 2.5% above the 85th percentile gets its own box, labeled as
'percentile_85', 'percentile_87.5', etc., up to 'percentile_97.5'.
-
Bin Calculation:
- Percentiles are calculated dynamically using
np.percentile to determine the boundaries for each 2.5% interval above the 85th percentile.
-
Labels:
- Custom labels are assigned to each bin to clearly indicate the range they represent.
-
Boundary Handling:
-np.inf and np.inf are replaced with strings '-inf' and 'inf' for better readability in the output.
This approach ensures that the data is grouped as specified, with the lowest 85% in one box and each 2.5% above that in separate boxes.