如何使用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 sameCtrlvalue together (so both OTC-07 rows are grouped).agg(...): Defines how to aggregate each column:- For
Type, we uselambda 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".
- For
reset_index(): Turns theCtrlgroup label back into a regular column instead of an index.
Result:
Your merged DataFrame will look like this:
| Ctrl | Type | Assertion |
|---|---|---|
| OTC-07 | A,B | a,b,c,d |
| OTC-09 | D | e,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
相关产品推荐
相关产品推荐

