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

如何基于pandas DataFrame列条件生成带Location字段的新索引行

你可以用pandas内置的宽表转长表函数实现,完全不需要手动拆分拼接每个城市的结果,代码更简洁易维护。

方法1:使用melt函数(可读性更高,逻辑更清晰)

import pandas as pd 
import numpy as np

# 原始数据构造
data = [['Apple', 1, 1, 1 ,1,], ['Orange', np.nan, 1, 1, np.nan], ['Banana', 1, np.nan, 1, np.nan]]
df = pd.DataFrame(data, columns = ['Type of fruit', 'Paris', "Boston", "Austin", "New York"])

# 转换逻辑
result = (
    # 宽表转长表,把城市列转为行
    df.melt(id_vars='Type of fruit', var_name='Location', value_name='flag')
    # 过滤掉值为空的行
    .dropna(subset=['flag'])
    # 调整列顺序,保留需要的字段
    [['Location', 'Type of fruit']]
    # 重置连续索引
    .reset_index(drop=True)
)
print(result)

方法2:使用stack函数(代码更简洁,stack会自动丢弃空值)

result = (
    df.set_index('Type of fruit')
    # 把城市列堆叠为行,自动删除NaN
    .stack()
    # 重置索引
    .reset_index()
    # 调整列名和顺序
    .rename(columns={'level_1': 'Location'})
    [['Location', 'Type of fruit']]
    .reset_index(drop=True)
)
print(result)

两种方法运行后输出的结果都和你要求的预期完全一致,后续如果新增城市列,不需要修改额外的处理逻辑,直接适配。

内容的提问来源于stack exchange,提问作者Bobbert

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 00:15:02