You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Streamlit中用st.selectbox比较两列百分比差异报错排查

解决Streamlit中列百分比差异计算与柱状图绘制的报错问题

错误原因

st.selectbox返回的是列名的字符串(比如'Score'),不是DataFrame中对应列的数值数据。直接对字符串做除法会触发unsupported operand type(s) for /: 'str' and 'str'错误;而试图把列名字符串转成整数,自然会因为列名不是数字字符串而报错invalid literal for int() with base 10: 'Score'。

修复后的代码

你需要通过列名字符串去提取DataFrame中对应的列数据,再进行计算:

import pandas as pd
import plotly.express as px
import streamlit as st

df = pd.read_csv('df.csv')

select1 = st.selectbox('Option 1', options=df.columns)
select2 = st.selectbox('Option 2', options=df.columns)

# 提取对应列的数值数据,计算百分比差异
y_axis_val = (df[select1] / df[select2]) * 100

# 绘制柱状图
plot = px.bar(df, x=df["Name"], y=y_axis_val, template="plotly_dark",
              title=f"{select1} 相对于 {select2} 的百分比")
st.plotly_chart(plot, use_container_width=True)

额外优化建议

  • 可以避免选择同一列(防止除以0报错),修改第二个selectbox的选项:
    select2 = st.selectbox('Option 2', options=[col for col in df.columns if col != select1])
    
  • 如果数据中存在0值,建议添加异常处理,比如替换为NaN或者提示用户:
    y_axis_val = (df[select1] / df[select2].replace(0, float('nan'))) * 100
    

内容的提问来源于stack exchange,提问作者Markus Fürst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:35:29