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

如何调整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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:13:30