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

如何使用Pandas重命名列中重复值并筛选展示hospital列数据相同的行

Got two solid Pandas questions here—let’s break them down with clear, actionable examples so you can apply this right away.

1. 重命名数据列中重复出现的相同值

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:

fruitquantityfruit_renamed
Apple5Apple
Banana3Banana
Apple2Apple_2
Orange7Orange
Apple4Apple_3
Banana1Banana_2

This keeps the first occurrence of each value as-is, and appends an incrementing number to every duplicate after that.

2. 筛选并展示hospital列中数据相同的所有行

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:

hospitalpatient_iddiagnosis
Mayo Clinic101Flu
Johns Hopkins102COVID
Mayo Clinic103Flu
Johns Hopkins105COVID

The Cleveland Clinic row is excluded because it only appears once.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 06:47:37