質問: 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 4TH STREET 324 EAST 4TH STREET 324 EAST 4TH STREET 324 EAST 4TH STREET 324 EAST 4TH STREET 324 EAST 4TH STREET 754 EAST 6TH STREET ``` How can I get counts, in the same data frame, like this? ``` 250 EAST HOUSTON STREET 3 211 EAST 3RD STREET 1 182 EAST 2ND STREET 1 511 EAST 11TH STREET 1 324 EAST 4TH STREET 8 324 EAST 4TH STREET 8 324 EAST 4TH STREET 8 324 EAST 4TH STREET 8 324 EAST 4TH STREET 8 324 EAST 4TH STREET 8 324 EAST 4TH STREET 8 324 EAST 4TH STREET 8 754 EAST 6TH STREET 1 ``` The name of the field that I want to count is 'Street'. I found some code that counts dupes, but it does a group by and takes everything into a new data frame. I want to assign counts to a new column in the same data frame. Thanks!
回答: 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 question df['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 ```