Thank you for your feedback!
Let’s address the issues and provide a fully working, robust solution.
Key Points:
pd.cut with right=False means the left edge is included, right is excluded.
- The labels and bins must match in length:
len(labels) == len(bins) - 1.
- The boundaries must be strictly increasing (no duplicates).
- We need to handle the case where percentiles may not be unique (e.g., if the data is not very diverse).
Corrected Code
import pandas as pd
import numpy as np
# Read input file
df = pd.read_csv('deltacoverage-multi.tsv', sep='\t')
# Compute the 85th percentile boundary
bound_85 = np.percentile(df['sliding_scores'], 85)
# Compute the upper percentile boundaries in steps of 2.5%
upper_percentiles = np.arange(87.5, 100, 2.5)
upper_bounds = [np.percentile(df['sliding_scores'], p) for p in upper_percentiles]
# Combine all bin edges: [-inf, 85th, 87.5th, 90th, ..., 97.5th, inf]
bins = [-np.inf, bound_85] + upper_bounds + [np.inf]
# Remove duplicate bin edges (can happen if data is not diverse)
bins = np.unique(bins)
# Create labels for the bins
labels = []
if len(bins) > 2:
labels.append('lowest_85')
for i in range(1, len(bins)-2):
labels.append(f'{85 + 2.5*(i-1):.1f}-{85 + 2.5*i:.1f}')
labels.append(f'{bins[-2]:.2f}+') # Last bin label
else:
labels = ['all']
# Bin the data
df['box'] = pd.cut(df['sliding_scores'], bins=bins, labels=labels, right=False, include_lowest=True)
# Identify the delta columns
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().reset_index()
# Add bin boundaries for each label
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', '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}")
What was fixed:
- Bin edges and labels are always consistent.
- Duplicate bin edges are removed (avoids
ValueError from pd.cut).
- Labels are generated dynamically to match the number of bins.
- Handles edge cases where data is not diverse enough for all bins.
If you still have issues, please provide the error message or a sample of your data for further debugging!