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

如何在Python 2.7中按指定表头转置特定列(借助Pandas)

Solution using Pandas in Python 2.7

Here's a complete implementation that meets all your requirements:

import pandas as pd
from StringIO import StringIO

# Your input data (replace this with reading from a file if necessary)
input_data = """ID,var_name,var_value
1,ABC,This is abc1
1,DEF,This is def1
2,ABC,This is abc2
2,DEF,This is def2
2,GHI,This is ghi2
3,ABC,This is abc3
4,ABC,This is abc4
4,DEF,This is def4"""

# Define your target header variables
target_headers = ['ABC', 'GHI']

# Step 1: Read the data into a Pandas DataFrame
df = pd.read_csv(StringIO(input_data))

# Step 2: Pivot the data to restructure it (ID as rows, variables as columns)
pivoted = df.pivot(index='ID', columns='var_name', values='var_value')

# Step 3: Keep only the variables we care about, fill missing values with empty strings
filtered = pivoted[target_headers].fillna('').reset_index()

# Step 4: Convert to the nested list format
result = [['ID'] + target_headers]
for _, row in filtered.iterrows():
    result.append(row.tolist())

# Output the result
print(result)

Explanation of each step:

  • Reading the data: We use StringIO to simulate reading from a CSV file. If your data is in an actual file, replace StringIO(input_data) with your file path (e.g., 'your_data.csv').
  • Pivoting: This transforms the long-format data into a wide format where each ID becomes a row, and each variable becomes a column with its corresponding value.
  • Filtering and filling: We select only the variables in your target_headers list, then replace any missing values (for variables an ID doesn't have) with empty strings.
  • Converting to nested list: We first create the header row, then iterate over each row in the filtered DataFrame to build the exact nested list structure you need.

This code will produce exactly the output you specified:

[['ID', 'ABC', 'GHI'], [1, 'This is abc1', ''], [2, 'This is abc2', 'This is ghi2'], [3, 'This is abc3', ''], [4, 'This is abc4', '']]

内容的提问来源于stack exchange,提问作者Sourajit Roy Chowdhury

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:11:05