Pandas中DataFrame格式化:实现列数据纵向堆叠展示
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

