Skip to content Skip to sidebar Skip to footer

How Can We Do Counts Of Items In A Data Frame And Asign Results To A New Column In The Dataframe?

I have street addresses that look like this. 250 EAST HOUSTON STREET 211 EAST 3RD STREET 182 EAST 2ND STREET 511 EAST 11TH STREET 324 EAST 4TH STREET 324 EAST 4TH STREET 324 EAST 4

Solution 1:

Use groupby + transform. Transform allows you to call the series to a new column. If you do not use transform, then you have a consolidated series that is a mismatch for the dataframe and your column will instead be filled with NaN values:

import pandas as pd
# df = pd.read_clipboard('\s\s+', header=None).rename({0: 'Street'}, axis=1) # how I read in your data from your StackOverflow questiondf['Count'] = df.groupby('Street')['Street'].transform('count')
df
Out[1]: 
                     Street  Count
0   250 EAST HOUSTON STREET  1
1       211 EAST 3RD STREET  1
2       182 EAST 2ND STREET  1
3      511 EAST 11TH STREET  1
4       324 EAST 4TH STREET  8
5       324 EAST 4TH STREET  8
6       324 EAST 4TH STREET  8
7       324 EAST 4TH STREET  8
8       324 EAST 4TH STREET  8
9       324 EAST 4TH STREET  8
10      324 EAST 4TH STREET  8
11      324 EAST 4TH STREET  8
12      754 EAST 6TH STREET  1

Solution 2:

I'm really new to trying to help people on this platform so feel free to tell me I'm not looking in the right places for the info, but are you using Pandas or another library? If you're using Pandas I think there's a method called valuecount (maybe value_count) that could be useful. Sorry I can't be more helpful but I'm learning the ropes here.

Post a Comment for "How Can We Do Counts Of Items In A Data Frame And Asign Results To A New Column In The Dataframe?"