如何在Pandas中按原顺序重复展示列元素及其出现次数?
Hey there! No problem at all—here are two straightforward Pandas methods to get that B column showing the global occurrence count for each value in A, while keeping your original order intact:
Method 1: Using value_counts() + map()
First, calculate how many times each unique value appears in column A with value_counts(), which gives a Series where the index is the unique value and the value is its total count. Then use map() to assign these counts back to every row in your original DataFrame.
import pandas as pd # Create your sample DataFrame df = pd.DataFrame({'A': [1, 1, 2, 3, 3, 4, 4, 4, 4]}) # Get the count of each unique value in A value_counts = df['A'].value_counts() # Add the B column by mapping each value in A to its global count df['B'] = df['A'].map(value_counts) print(df)
This outputs exactly the structure you want:
A B 0 1 2 1 1 2 2 2 1 3 3 2 4 3 2 5 4 4 6 4 4 7 4 4 8 4 4
Method 2: Using groupby() + transform()
A more direct approach uses groupby() combined with transform(). The transform() method calculates the count for each group of values in A and automatically broadcasts that count back to every row in the original group, preserving your initial order.
import pandas as pd df = pd.DataFrame({'A': [1, 1, 2, 3, 3, 4, 4, 4, 4]}) # Assign group counts directly to each row as column B df['B'] = df.groupby('A')['A'].transform('count') print(df)
This will produce the exact same result as the first method. Both are efficient, but the groupby + transform method feels more intuitive since it directly links each row to its group's count without an explicit mapping step.
内容的提问来源于stack exchange,提问作者Eleanor

