give me a app that we enter a medicine and give which medicines is prescribed with depending on excel file
To upload files, please first save the app
import streamlit as st
import pandas as pd
import numpy as np
# Create sample medicine prescription data
@st.cache_data
def create_sample_data():
"""Create sample prescription data for demonstration"""
medicines = [
'Aspirin', 'Ibuprofen', 'Acetaminophen', 'Lisinopril', 'Metformin',
'Atorvastatin', 'Omeprazole', 'Amoxicillin', 'Metoprolol', 'Amlodipine',
'Hydrochlorothiazide', 'Simvastatin', 'Losartan', 'Levothyroxine', 'Warfarin',
'Prednisone', 'Albuterol', 'Insulin', 'Clopidogrel', 'Gabapentin'
]
# Generate combinations of medicines that are commonly prescribed together
data = []
np.random.seed(42) # For reproducible results
for primary_med in medicines:
# Each medicine can be prescribed with 3-8 other medicines
num_combinations = np.random.randint(3, 9)
secondary_meds = np.random.choice(
[m for m in medicines if m != primary_med],
size=num_combinations,
replace=False
)
for secondary_med in secondary_meds:
# Add some realistic frequency data
frequency = np.random.randint(1, 100)
data.append({
'Primary_Medicine': primary_med,
'Prescribed_With': secondary_med,
'Frequency': frequency,
'Condition': np.random.choice([
'Hypertension', 'Diabetes', 'Heart Disease', 'Arthritis',
'Infection', 'Pain Management', 'Cholesterol', 'Thyroid'
])
})
return pd.DataFrame(data)
def load_data():
"""Load data from uploaded file or use sample data"""
uploaded_file = st.file_uploader(
"Upload your medicine prescription Excel file",
type=['xlsx', 'xls', 'csv'],
help="Upload an Excel/CSV file with columns: Primary_Medicine, Prescribed_With, Frequency (optional), Condition (optional)"
)
if uploaded_file is not None:
try:
if uploaded_file.name.endswith('.csv'):
df = pd.read_csv(uploaded_file)
else:
df = pd.read_excel(uploaded_file)
# Validate required columns
required_cols = ['Primary_Medicine', 'Prescribed_With']
if not all(col in df.columns for col in required_cols):
st.error(f"Please ensure your file has these columns: {required_cols}")
return None
return df
except Exception as e:
st.error(f"Error reading file: {str(e)}")
return None
else:
st.info("Using sample data. Upload your own Excel file to use real prescription data.")
return create_sample_data()
def main():
st.title("🏥 Medicine Prescription Finder")
st.markdown("Enter a medicine name to find which other medicines are commonly prescribed with it.")
# Load data
df = load_data()
if df is None:
return
# Display data info
with st.expander("📊 View Data Summary"):
st.write(f"**Total prescription combinations:** {len(df)}")
st.write(f"**Unique medicines:** {df['Primary_Medicine'].nunique()}")
# Show sample of data
st.write("**Sample data:**")
st.dataframe(df.head(10))
# Medicine search
st.subheader("🔍 Search for Medicine Combinations")
# Get unique medicines for dropdown
all_medicines = sorted(df['Primary_Medicine'].unique())
# Medicine selection
selected_medicine = st.selectbox(
"Select or type a medicine name:",
options=all_medicines,
index=0
)
if selected_medicine:
# Filter data for selected medicine
filtered_data = df[df['Primary_Medicine'] == selected_medicine].copy()
if not filtered_data.empty:
st.success(f"Found {len(filtered_data)} medicines commonly prescribed with **{selected_medicine}**")
# Sort by frequency if available
if 'Frequency' in filtered_data.columns:
filtered_data = filtered_data.sort_values('Frequency', ascending=False)
# Display results
col1, col2 = st.columns([2, 1])
with col1:
st.subheader("💊 Medicines Prescribed Together")
# Create a clean display dataframe
display_df = filtered_data[['Prescribed_With']].copy()
display_df.index = range(1, len(display_df) + 1)
if 'Frequency' in filtered_data.columns:
display_df['Frequency'] = filtered_data['Frequency'].values
if 'Condition' in filtered_data.columns:
display_df['Common Condition'] = filtered_data['Condition'].values
st.dataframe(display_df, use_container_width=True)
with col2:
st.subheader("📈 Statistics")
if 'Frequency' in filtered_data.columns:
st.metric("Most Common Combination",
filtered_data.iloc[0]['Prescribed_With'],
f"Frequency: {filtered_data.iloc[0]['Frequency']}")
st.metric("Average Frequency",
f"{filtered_data['Frequency'].mean():.1f}")
if 'Condition' in filtered_data.columns:
st.write("**Common Conditions:**")
condition_counts = filtered_data['Condition'].value_counts()
for condition, count in condition_counts.head(3).items():
st.write(f"• {condition}: {count}")
else:
st.warning(f"No prescription combinations found for **{selected_medicine}**")
# Additional features
st.subheader("🔄 Reverse Search")
st.markdown("Find which medicines commonly include a specific medicine in their combinations:")
reverse_medicine = st.selectbox(
"Select medicine to find what it's prescribed with:",
options=sorted(df['Prescribed_With'].unique()),
key="reverse_search"
)
if reverse_medicine:
reverse_data = df[df['Prescribed_With'] == reverse_medicine].copy()
if not reverse_data.empty:
st.write(f"**{reverse_medicine}** is commonly prescribed WITH:")
if 'Frequency' in reverse_data.columns:
reverse_data = reverse_data.sort_values('Frequency', ascending=False)
reverse_display = reverse_data[['Primary_Medicine']].copy()
reverse_display.index = range(1, len(reverse_display) + 1)
if 'Frequency' in reverse_data.columns:
reverse_display['Frequency'] = reverse_data['Frequency'].values
st.dataframe(reverse_display.head(10), use_container_width=True)
if __name__ == "__main__":
main()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?