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

如何使用Pandas拼接多行值及合并OTC-07重复行?

How to Concatenate Values Across Rows in Pandas and Merge Duplicate Entries

Hey there! I see you need to merge duplicate rows where the Ctrl column is "OTC-07", concatenating the values in the Type and Assertion columns. Let's walk through exactly how to do this with Pandas.

Step 1: Set Up Example Data (Matching Your Scenario)

First, let's simulate a DataFrame that mirrors your setup (since you mentioned a screenshot with duplicate OTC-07 rows):

import pandas as pd

# Sample data matching your description
df = pd.DataFrame({
    "Ctrl": ["OTC-07", "OTC-07", "OTC-09"],
    "Type": ["A", "B", "D"],
    "Assertion": ["a,b", "c,d", "e,f"]
})

Step 2: Group by Ctrl and Concatenate Column Values

Use Pandas' groupby() and agg() methods to group rows by the Ctrl column, then concatenate the values in your target columns with commas:

# Group by 'Ctrl' and concatenate values in specified columns
merged_df = df.groupby("Ctrl").agg(
    Type=("Type", lambda x: ",".join(x)),
    Assertion=("Assertion", lambda x: ",".join(x))
).reset_index()

What This Does:

  • groupby("Ctrl"): Clusters all rows with the same Ctrl value together (so both OTC-07 rows are grouped).
  • agg(...): Defines how to aggregate each column:
    • For Type, we use lambda x: ",".join(x) to join all values in the group with commas (resulting in "A,B").
    • For Assertion, the same logic joins "a,b" and "c,d" into "a,b,c,d".
  • reset_index(): Turns the Ctrl group label back into a regular column instead of an index.

Result:

Your merged DataFrame will look like this:

CtrlTypeAssertion
OTC-07A,Ba,b,c,d
OTC-09De,f

Bonus: Handling Other Columns

If you have additional columns you want to keep (e.g., a column where you just need the first value from the group), you can add that to the agg() call:

merged_df = df.groupby("Ctrl").agg(
    Type=("Type", lambda x: ",".join(x)),
    Assertion=("Assertion", lambda x: ",".join(x)),
    OtherColumn=("OtherColumn", "first")  # Keep the first value from the group
).reset_index()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:12:37