The error occurs because some entries in the PromoterSequence column are NaN (floats) rather than strings, and len() cannot be applied to a float. To fix this, we need to handle missing or empty sequences properly. Here's the corrected code:
Fixed Code:
import pandas as pd
import numpy as np
# Load the PWM
pwm_file = 'sigma70-PWM.txt'
pwm_df = pd.read_csv(pwm_file, sep='\t')
# Read the promoter sequences
promoter_file = 'promoters_with_sequences.tsv'
promoter_df = pd.read_csv(promoter_file, sep='\t')
seq_length = len(pwm_df)
output_file = 'sigma70-promoters-pwm.txt'
# Function to calculate PWM score for a given sequence
def calculate_pwm_score(seq):
if pd.isna(seq): # Skip NaN (missing) sequences
return float('-inf')
if not isinstance(seq, str): # Ensure it's a string
return float('-inf')
if len(seq) != seq_length:
return float('-inf') # Return negative infinity for length mismatch
score = 0.0
seq = seq.lower()
for i, nt in enumerate(seq):
if nt not in 'acgt':
return float('-inf') # Return negative infinity for invalid nucleotides
score += pwm_df.loc[i, nt.upper()] # Add log-odds scores
return score
# Apply the function to the PromoterSequence column and store the results in a new column "PWM"
promoter_df['PWM'] = promoter_df['PromoterSequence'].apply(calculate_pwm_score)
# Save the updated DataFrame to a new file
promoter_df.to_csv(output_file, sep='\t', index=False)
print(f"PWM scores calculated and saved to {output_file}")
Key Fixes:
-
Handling NaN values:
pd.isna(seq) checks if the sequence is missing (NaN).
- If it is, we return
-inf (or you could skip it entirely if preferred).
-
Ensuring the sequence is a string:
isinstance(seq, str) ensures we only process valid strings.
- If the sequence is not a string (e.g.,
NaN or another type), we return -inf.
-
Other checks remain the same:
- Length mismatch →
-inf
- Invalid nucleotides →
-inf
- Valid sequences → sum of log-odds scores.
Output:
- The final file (
sigma70-promoters-pwm.txt) will contain the original data with an additional PWM column storing the scores.
- Missing or invalid sequences will have
-inf as their score.
This should resolve the TypeError while ensuring all edge cases are handled properly. Let me know if you need further modifications! 🚀