簡體   English   中英

根據重復次數選擇列

[英]Selecting columns based on how many times it repeats

考慮我在 python pandas 中有一個列並且有 1000 個字符串值,我如何根據重復次數從中選擇前 10 個值

data['country_state'] = data['place'].str.rsplit(',').str[-1] #column 

country_state有 1000 個值我必須根據相同字符串重復的次數從 1000 個中選擇前 10 個country_state

我認為 value_counts ( https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html ) 和 nlargest ( https://pandas.pydata.org/pandas-docs/stable/ reference/api/pandas.Series.nlargest.html ) 應該在這里工作:

data['country_state'].value_counts().nlargest(10)

嗨,您可以使用一些 Pandas 函數來解決這個問題,首先value_counts將通過重復對您的數據進行排序並對其進行計數,然后您可以拆分前 10 個並獲取它們的索引。 這里有一個例子:

import numpy as np
import pandas as pd

#create the dataframe I used numbers for simplicity it's the same for other var
n = np.random.randint(0,50,1000)
df_n = pd.DataFrame(n,columns= ['num'])

#get values by frequency 
nreps = df_n['num'].value_counts()

#get the top ten and print it's index
top10_values = nreps.iloc[:10].index
top10_counts    = nreps.iloc[:10].values

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM