Below is one solution. In the code below the lowest 85% of the data (i.e. values below the 85th percentile of the sliding_scores column) are grouped into one box, and then for the remaining values the bins are calculated in steps of 2.5% (i.e. 85–87.5, 87.5–90, …, 97.5–100). We use np.percentile to compute the boundaries and then use pd.cut with custom labels. Finally, we group by the new box category and output the results.
python
import pandas as pd
import numpy as np
# Read input file
df = pd.read_csv('deltacoverage-multi.tsv', sep='\t')
# Compute essential percentile boundaries
# First: the 85th percentile boundary (lowest 85% get one bin)
bound_85 = np.percentile(df['sliding_scores'], 85)
# Next: boundaries for the remaining percentiles in steps of 2.5 (from 87.5 to 97.5)
upper_percentiles = [87.5, 90, 92.5, 95, 97.5]
upper_bounds = [np.percentile(df['sliding_scores'], p) for p in upper_percentiles]
# Set up the bins:
# The first bin: [-inf, 85th percentile)
# Then bins: [85th, 87.5th), [87.5th, 90th), ... [97.5th, inf)
bins = [-np.inf, bound_85] + upper_bounds + [np.inf]
# Create labels for the bins
# First label is for the lowest 85%; subsequent labels indicate the percentile range.
labels = ['lowest_85', '85-87.5', '87.5-90', '90-92.5', '92.5-95', '95-97.5', '97.5-100']
# Bin the data
df['box'] = pd.cut(df['sliding_scores'], bins=bins, labels=labels, right=False, include_lowest=True)
# Identify the delta columns (assuming these columns start with 'delta')
delta_cols = [col for col in df.columns if col.startswith('delta')]
# Group by the box category and compute the mean for the delta columns
grouped_df = df.groupby('box')[delta_cols].mean()
# (Optional) Adjust or set any additional column, for example, setting 'delta0' to 0
grouped_df['delta0'] = 0
# Reset index so that we can add boundary columns based on the labels
grouped_df = grouped_df.reset_index()
# Map each label to its corresponding bin boundaries.
# The index of a label in our "labels" list matches the lower boundary index in our "bins" list.
def get_boundaries(label):
idx = labels.index(label)
return bins[idx], bins[idx + 1]
grouped_df[['box_start', 'box_end']] = grouped_df['box'].apply(
lambda x: pd.Series(get_boundaries(x))
)
# Replace -np.inf and np.inf with readable strings
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'})
# Arrange the final columns to output.
output_cols = ['box_start', 'box_end'] + delta_cols
output_df = grouped_df[output_cols]
# Write the output to a TSV file.
output_filename = 'average_deltas_by_box-85percentile-2.5.tsv'
output_df.to_csv(output_filename, sep='\t', index=False)
print(f"Saved {len(output_df)} rows to {output_filename}")
Explanation
Percentile Boundaries and Bin Definition
We calculate bound_85 as the 85th percentile of sliding_scores.
For the remaining bins, we compute boundaries at 87.5, 90, 92.5, 95, and 97.5 percentiles.
We then define our bin edges as:
[-np.inf, bound_85)
[bound_85, bound_87.5)
[bound_87.5, bound_90)
[bound_90, bound_92.5)
[bound_92.5, bound_95)
[bound_95, bound_97.5)
[bound_97.5, np.inf)
Labeling
The bins are labeled with "lowest_85" for the first bin and then with the appropriate percentile ranges (e.g., "85-87.5") for each subsequent bin.
Grouping and Output
The data is grouped by the new box column and the mean values of the delta columns are computed.
The corresponding numerical boundaries for each bin are extracted and added as columns.
Finally, the output is saved as a TSV file.
This modification meets the requirements by placing the lowest 85% in one box and then further grouping the remaining values in 2.5% increments.