Apologies for the oversight! The extra delta0 column at the end was included in the output columns unintentionally. Let's fix the code by removing it from the output while keeping it in the grouped calculations (as it was in your original code). Here's the corrected version:
python
import pandas as pd
import numpy as np
df = pd.read_csv('deltacoverage-multi.tsv', sep='\t')
# Define percentiles: 0-85% in one box, then 85-87.5%, 87.5-90%, etc.
percentiles = [0, 85, 87.5, 90, 92.5, 95, 97.5, 100]
bins = [np.percentile(df['sliding_scores'], p) for p in percentiles]
# Make sure bins are unique (in case of ties at percentiles)
bins = sorted(list(set(bins)))
# Replace first and last with -inf and inf to catch all values
bins[0] = -np.inf
bins[-1] = np.inf
# Create labels based on the percentile ranges
labels = ['lowest_85']
for i in range(85, 100, 2):
if i < 97.5:
labels.append(f'percentile_{i}_{i+2.5}')
# Adjust labels to match the number of bins
labels = labels[:len(bins)-1]
# 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 # Keep delta0 for calculations but don't include in output
# Reset index
grouped_df = grouped_df.reset_index()
# Add box boundaries
box_mapping = {label: (bins[i], bins[i+1]) for i, label in enumerate(labels)}
grouped_df['box_start'] = grouped_df['box'].apply(lambda x: box_mapping[x][0])
grouped_df['box_end'] = grouped_df['box'].apply(lambda x: box_mapping[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 (excluding delta0) and save to file
output_cols = ['box_start', 'box_end'] + delta_cols # Removed delta0 from output
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:
Removed 'delta0' from the output_cols list, ensuring it is not included in the final output file, while still keeping it in the grouped_df for any internal calculations or consistency with your original code.
This should now produce the output exactly as you intended, without the extra delta0 column at the end.