我已經(jīng)用 Python 創(chuàng)建了一個(gè) DataFrame,并希望顯示每個(gè)郵政編碼最流行的狗品種。我已經(jīng)編碼了以下內(nèi)容,但我只能顯示每個(gè)品種的總數(shù),而不是品種本身。我的代碼:import pandas as pddf = pd.DataFrame({'zip_code':[12345,66666,12345,22222,22222,12345,66666,22222,44444], 'primary_breed': ['labrador','pug','poodle','labrador','labrador','pug','whippet','poodle','labrador'], 'animals_name':['lucy','charley','scout','hank','sweetie','lucy','daddy','lucy','charley'], 'species':['dog','dog','dog','dog','dog','dog','dog','dog','dog']})# assign correct data typesdf['species'] = df['species'].astype('category')df['animals_name'] = df['animals_name'].astype('string')df['primary_breed'] = df['primary_breed'].astype('category')df['zip_code'] = df['zip_code'].astype('string')dogs = df.species == 'dog'# total number per breed per zipdf_total_per_breed_zip = df[dogs].groupby('zip_code')['primary_breed'].value_counts() print('\n\ntotal number per breed: \n', df_total_per_breed_zip)# most popular breed per zipdf_mostpop_breed_zip = df_total_per_breed_zip.max(level='zip_code')print('\n\nmost popular breed per zip: \n', df_mostpop_breed_zip)所以我得到的是:total number per breed: zip_code primary_breed12345 labrador 1 poodle 1 pug 122222 labrador 2 poodle 144444 labrador 166666 pug 1 whippet 1Name: primary_breed, dtype: int64most popular breed per zip: zip_code12345 122222 244444 166666 1Name: primary_breed, dtype: int64但我想得到的是:total number per breed: zip_code primary_breed12345 labrador 1 poodle 1 pug 122222 labrador 2 poodle 144444 labrador 166666 pug 1 whippet 1Name: primary_breed, dtype: int64most popular breed per zip: zip_code12345 labrador22222 labrador44444 labrador66666 pugName: primary_breed, dtype: int64
如何在Python中顯示每列的最高計(jì)數(shù)
當(dāng)年話下
2023-12-12 10:15:58