![](/img/trans.png)
[英]Python function to count the number of unique values in a df column, the output must be a df. NOTE: NOT how many times does the unique value appears
[英]Trying to access column by index number in a pandas df. The dataframe is created by value.counts() function. It does not work
我正在嘗試使用iloc通過熊貓數據框中的索引號訪問列:
new = df_new.iloc[:,0]
拋出錯誤:
IndexingError:索引器過多
iloc上的其他帖子顯示它們工作正常。 不明白為什么這發生在我身上。 請幫忙 !!
數據幀為:
Games 3862 Entertainment 535 Education 453 Photo & Video 349 Utilities 248 Health & Fitness 180 Productivity 178 Social Networking 167 Lifestyle 144 Music 138 Shopping 122 Sports 114 Book 112 Finance 104 Travel 81 News 75 Weather 72 Reference 64 Food & Drink 63 Business 57 Navigation 46 Medical 23 Catalogs 10
並由以下代碼創建:
df_new=obj_df["prime_genre"].value_counts()
通過計數另一個數據幀的類別數
obj_df["prime_genre"].value_counts()
返回一個只有一維的pd.Series
( reference )。 語法[:, 0]
表示選擇所有行和索引為0的列 。 但是因為這是一個系列,所以使用行/列進行切片沒有任何意義
采用
.iloc[0]
如果只需要第一個元素。
如果要繼續使用df,請將此pd.Series
分配給列
obj_df['counts'] = obj_df["prime_genre"].value_counts()
然后您可以使用obj_df[:, 0]
]進行切片
如果需要索引,只需使用
obj_df["prime_genre"].value_counts().index
或者,如果您想使用iloc
表示法
obj_df["prime_genre"].value_counts().reset_index().iloc[:,0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.