How to Convert Marker Values Based on Cutoff Thresholds Using Python Pandas

Here’s an example of how you could do it for both cutoff1 and cutoff2:

import pandas as pd

# Create a sample dataframe (df) with Marker values that need to be converted
data = {
    'cond': ['A', 'B', 'C'],
    'Array': ['S', 'S', 'T'],
    'X': [1, 2, 3],
    'Y': [4, 5, 6],
    'Marker': [0.55, 7.05, 0.35]
}
df = pd.DataFrame(data)

# Create a sample dataframe (df2) with cutoff values
data_cutoffs = {
    'cutoff1': [2.55, 7.06],
    'cutoff2': [1.6, 2.1]
}
df2 = pd.DataFrame(data_cutoffs)

# Merge the two dataframes on cond and Array to create a new dataframe with the cutoff values
df = df.set_index(['cond', 'Array'])
result_cutoff1 = df.merge(df2, on=['cond', 'Array'])
result_cutoff1.loc[result_cutoff1.Marker <= result_cutoff1.cutoff1, 'Marker'] = 0

# Repeat the same process for cutoff2
result_cutoff2 = df.set_index(['cond', 'Array'])
df2 = df2.reset_index()
result_cutoff2 = result_cutoff2.merge(df2, on=['cond', 'Array'])
result_cutoff2.loc[result_cutoff2.Marker <= result_cutoff2.cutoff2, 'Marker'] = 0

# Drop the cutoff columns from both dataframes
result_cutoff1 = result_cutoff1.drop(['cutoff1'], axis=1)
result_cutoff2 = result_cutoff2.drop(['cutoff2'], axis=1)

print(result_cutoff1)
print(result_cutoff2)

This example creates two new dataframes, result_cutoff1 and result_cutoff2, where the Marker values in df are converted to 0 or 1 based on the corresponding cutoff values.


Last modified on 2025-03-05