Pandas Dataframe: how to add column with number of occurrences in other column
groupby
on 'col1' and then apply transform
on Col2
to return a Series with its index aligned to the original df so you can add it as a column:
In [3]:
df['Occur'] = df.groupby('Col1')['Col2'].transform(pd.Series.value_counts)
df
Out[3]:
Col1 Col2 Occur
0 test Something 2
1 test2 Something 2
2 test3 Something 1
3 test Something 2
4 test2 Something 2
5 test5 Something 1
You can also use GroupBy
+ transform
with size
:
df['Occur'] = df.groupby('Col1')['Col1'].transform('size')
print(df)
Col1 Col2 Occur
0 test Something 2
1 test2 Something 2
2 test3 Something 1
3 test Something 2
4 test2 Something 2
5 test5 Something 1