如何使用Pandas重命名列中重复值并筛选展示hospital列数据相同的行
Got two solid Pandas questions here—let’s break them down with clear, actionable examples so you can apply this right away.
I’m assuming you want to make duplicate values in a column unique by adding a suffix (like Apple_1, Apple_2) instead of just keeping the same name. Here’s how to do it cleanly:
First, let’s set up a sample DataFrame to work with:
import pandas as pd df = pd.DataFrame({ 'fruit': ['Apple', 'Banana', 'Apple', 'Orange', 'Apple', 'Banana'], 'quantity': [5, 3, 2, 7, 4, 1] })
The trick is to use groupby to group rows by the column with duplicates, then use cumcount() to get the position of each row within its group. We’ll only add a suffix to rows that aren’t the first occurrence in their group:
# Generate a renamed column: add "_n" only to duplicate entries (starting from 2) df['fruit_renamed'] = df['fruit'] + df.groupby('fruit').cumcount().apply(lambda x: f'_{x+1}' if x > 0 else '')
After running this, your DataFrame will look like this:
| fruit | quantity | fruit_renamed |
|---|---|---|
| Apple | 5 | Apple |
| Banana | 3 | Banana |
| Apple | 2 | Apple_2 |
| Orange | 7 | Orange |
| Apple | 4 | Apple_3 |
| Banana | 1 | Banana_2 |
This keeps the first occurrence of each value as-is, and appends an incrementing number to every duplicate after that.
If you want to pull all rows where the hospital value appears more than once (i.e., show every row for hospitals that have duplicate entries), here are two straightforward methods:
Let’s use this sample DataFrame for demonstration:
df = pd.DataFrame({ 'hospital': ['Mayo Clinic', 'Johns Hopkins', 'Mayo Clinic', 'Cleveland Clinic', 'Johns Hopkins'], 'patient_id': [101, 102, 103, 104, 105], 'diagnosis': ['Flu', 'COVID', 'Flu', 'Heart Disease', 'COVID'] })
Method 1: Use value_counts() + isin()
First, we get a list of hospitals that appear at least twice, then filter the original DataFrame to only those hospitals:
# Get hospitals that occur 2+ times duplicate_hospitals = df['hospital'].value_counts()[df['hospital'].value_counts() >= 2].index # Filter the DataFrame to show only rows with those hospitals filtered_df = df[df['hospital'].isin(duplicate_hospitals)]
Method 2: Use groupby() + transform() (more concise)
This method calculates the size of each hospital group directly on every row, then filters for groups with size ≥2:
filtered_df = df[df.groupby('hospital')['hospital'].transform('size') >= 2]
Both methods will give you this result, which includes all rows for hospitals that have duplicate entries:
| hospital | patient_id | diagnosis |
|---|---|---|
| Mayo Clinic | 101 | Flu |
| Johns Hopkins | 102 | COVID |
| Mayo Clinic | 103 | Flu |
| Johns Hopkins | 105 | COVID |
The Cleveland Clinic row is excluded because it only appears once.
内容的提问来源于stack exchange,提问作者Andrew

