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

Streamlit项目中字典转DataFrame遇长度不匹配错误求解

解决ValueError: Length of values (4) does not match length of index (1)问题

问题根源

你代码里的type_of_company和annual_volatility这两个变量没正确调用Streamlit的slider组件,而是直接写成了元组(比如('Is it a Tech Company?', 0, 1, 0)),这俩元组各有4个元素;但其他变量都是slider返回的单个数值。

当用字典创建DataFrame时,pandas要求每个键对应的值长度必须和index长度一致:

  • 如果值是单个标量,pandas会自动把它填充到index的每一行(这里你指定了index=[0],也就是1行)
  • 如果值是序列(比如元组、列表),序列的长度必须和index的行数完全匹配

你这里两个元组长度是4,和index的1不匹配,所以直接抛出了长度不匹配的错误。

修复代码

把这两个变量改成正确调用st.sidebar.slider的形式,获取单个输入值:

def user_input_features():

    price_to_earnings = st.sidebar.slider('Price to Earnings', -100, 100, 0)
    debt_to_equity = st.sidebar.slider('Debt to Equity', -50, 50, 0)
    book_value_per_share = st.sidebar.slider('Book Value per Share', -400, 400, 0)
    price_to_book_ratio = st.sidebar.slider('Price to Book Ratio', 0, 500, 0)
    # 修复:调用slider组件获取值,而非直接写元组
    type_of_company = st.sidebar.slider('Is it a Tech Company?', 0, 1, 0)
    annual_volatility = st.sidebar.slider('Annual Volatility Swing (In Percent)', 0, 100, 0)

    # Dictionary
    data = {'price_to_earnings': price_to_earnings,
            'debt_to_equity': debt_to_equity,
            'book_value_per_share': book_value_per_share,
            'price_to_book_ratio': price_to_book_ratio,
            'type_of_company': type_of_company,
            'annual_volatility': annual_volatility}

    features = pd.DataFrame(data, index=[0])
    return features

补充知识点

用字典创建DataFrame时,常见的两种合法形式:

  1. 字典的每个值都是标量:此时pandas会生成一个行数等于index长度、列数等于字典键数量的DataFrame,每个标量填充对应列的所有行
  2. 字典的每个值都是长度相同的序列:此时序列的长度就是DataFrame的行数,不需要额外指定index(除非自定义索引)

比如你之前错误的写法里,如果非要用元组,那得把所有值都改成长度为1的元组(比如price_to_earnings: (0,)),但显然这不符合你的需求——你需要的是用户通过滑块输入的单个值,所以直接调用slider获取标量才是正确做法。

内容的提问来源于stack exchange,提问作者Hyun Jong Lee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:25:33