如何调整Pandas GroupBy输出的DataFrame并导出为指定格式CSV
Solution for Aggregating and Exporting Pandas GroupBy Results to CSV
Here's how you can transform your grouped data into the exact CSV format you need:
Step 1: Reset the Multi-Index
Your final_df has a multi-index (ID, Seq, float) from the initial groupby operation. First, convert these index levels into regular columns to simplify subsequent aggregation:
final_df = final_df.reset_index()
Step 2: Aggregate Data by ID
Group the cleaned data by ID, then combine the Seq and float columns into comma-separated strings (we deduplicate Seq values to match your target output):
import pandas as pd # Aggregate columns into the desired format aggregated_df = final_df.groupby('ID').agg( # Deduplicate Seq entries and join with commas Sequence=('Seq', lambda x: ','.join(x.unique())), # Convert float values to strings and join with commas float=('float', lambda x: ','.join(map(str, x))) ).reset_index()
Step 3: Export to CSV
Export the aggregated data to a CSV file with no headers, no index, and non-numeric values wrapped in double quotes:
import csv aggregated_df.to_csv( 'output.csv', index=False, header=False, quoting=csv.QUOTE_NONNUMERIC # Ensures string columns are enclosed in " )
Final Output Preview
The resulting output.csv will match your requested format exactly:
3631,"D,P,R","1.31,1.45,1.44" 3633,"D,P","1.26,1.27,1.32,1.33"
内容的提问来源于stack exchange,提问作者nimals1986
相关产品推荐
相关产品推荐

