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

Pandas中DataFrame格式化:实现列数据纵向堆叠展示

Solution to Reshape DataFrame for Vertical Transaction Display

Got it, let's work through this. The core issue here is that when you used orient='index' to build your DataFrame, you ended up with transaction fields as rows and individual transactions as columns. What you need is to flip this structure so each transaction's fields and values are listed vertically, one transaction after another.

Step-by-Step Fix

First, let's address the empty lists in your dictionary (refundNotes and notes)—right now they'll default to None for all transactions, but we'll make that explicit to avoid unexpected behavior. Then we'll reshape the DataFrame to match your desired output.

1. Prepare the Dictionary

import pandas as pd

transactionDetails = {"paymentStatus":["COMPLETED", "REFUNDED", "COMPLETED"], 
                      "address":["123 Fake Street", "123 Example Street", "123 Top Secret"], 
                      "item":["Apple", "Banana", "Orange"], 
                      "transactionID":["2132123", "54654645", "56754646"], 
                      "orderTime":["14:55", "15:10", "23:11"], 
                      "email":["example@example.com", "fake@example.com", "notreal@notreal.com"], 
                      "refundNotes":[], 
                      "notes": []}

# Fill empty lists with None for every transaction
num_transactions = len(transactionDetails['paymentStatus'])
transactionDetails['refundNotes'] = [None] * num_transactions
transactionDetails['notes'] = [None] * num_transactions

2. Create the Original DataFrame

df = pd.DataFrame.from_dict(transactionDetails, orient='index')

3. Reshape to Vertical Transaction Format

The magic here is transposing the DataFrame first (swapping rows and columns) so each row represents a single transaction. Then we use stack() to convert each transaction's columns into vertical field-value pairs:

# Transpose to make transactions rows, then stack to get vertical field-value pairs
result = df.T.stack().reset_index(level=0, drop=True)

# Convert to a clean 2-column DataFrame (Field + Value)
result_df = result.reset_index(name='Value')

# Print the final output
print(result_df.to_string(index=False))

This will output exactly the format you requested:

Field                    Value
 paymentStatus                  COMPLETED
        address         123 Fake Street
           item                    Apple
  transactionID                 2132123
      orderTime                    14:55
           email    example@example.com
    refundNotes                     None
           notes                     None
 paymentStatus                   REFUNDED
        address      123 Example Street
           item                   Banana
  transactionID                54654645
      orderTime                    15:10
           email       fake@example.com
    refundNotes                     None
           notes                     None
 paymentStatus                  COMPLETED
        address          123 Top Secret
           item                   Orange
  transactionID                56754646
      orderTime                    23:11
           email notreal@notreal.com
    refundNotes                     None
           notes                     None

Optional: Separate Transactions with Headers

If you want to clearly split each transaction (like your example implies), loop through each transaction column and print individually:

for transaction_num, col in enumerate(df.columns, 1):
    print(f"--- Transaction {transaction_num} ---")
    print(df[col].reset_index(name='Value').to_string(index=False))
    print()

Why Your Original stack() Didn't Work

You applied stack() to the un-transposed DataFrame, which grouped all transactions under each field first. By transposing first, we ensure we group by individual transactions before stacking their fields into vertical pairs—this aligns with how you want the data displayed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:40:33