2016-12-20 4 views
1

Ich konnte Funktion nicht finden, um Top n% automatisch zu bekommen, also sortierte ich größte und kleinste Werte und berechnete Zahlen zu Top 25% und Minimum 25% Bereiche. Ich möchte eine Flagge in einer neuen Spalte erstellen, die besagt, dass dieser Kunde in den oberen 25% des Umsatzes liegt.Python erstellen neue Spalte mit Top-Werten (%) mit anderen Spaltenwerte

from heapq import nsmallest 
top_max = avg_cust_data.nlargest(10806, ['user_spendings']) 
top_min = avg_cust_data.nsmallest(10806, ['user_spendings']) 

avg_cust_data['spendings_flag'] = np.where(avg_cust_data['user_spendings'] = top_max, 'Top Max', 
            np.where(avg_cust_data['user_spendings'] = top_min, 'Top Min', 'AVG')) 
+0

Was 'avg_cust_data' ist? Wenn es Pandas DataFrame ist, versuchen Sie 'avg_cust_data ['user_sendings']. Describe()' – ArunDhaJ

+0

Ja, es ist ein DataFrame, aber ich möchte ein Flags in neue Spalte 'spendings_flag' erstellen und Werte 'top max', 'top min 'oder' avg 'basierend auf Werten von' user_spendings '. – user2702405

Antwort

2

Verwendung pd.qcut

np.random.seed([3,1415]) 
avg_cust_data = pd.DataFrame(np.random.random((16,1)), columns=['user_spendings']) 
avg_cust_data['quartiles'] = pd.qcut(
    avg_cust_data.user_spendings, 4, 
    ['Quartile %s' %i for i in range(1, 5)] 
) 
avg_cust_data 

enter image description here


Sie können sogar die Behälterkanten durch Perzentil anpassen und die entsprechenden Etiketten

np.random.seed([3,1415]) 
avg_cust_data = pd.DataFrame(np.random.random((16,1)), columns=['user_spendings']) 
avg_cust_data['quartiles'] = pd.qcut(
    avg_cust_data.user_spendings, [0., .25, .75, 1.], 
    ['Bottom 25%', 'Middle', 'Top 25%'] 
) 
avg_cust_data 

enter image description here

5

können Sie verwenden:

np.random.seed(100) 
avg_cust_data = pd.DataFrame(np.random.random((40,1)), columns=['user_spendings']) 
print (avg_cust_data) 


top_max = avg_cust_data['user_spendings'].nlargest(10) 
top_min = avg_cust_data['user_spendings'].nsmallest(10) 


avg_cust_data['spendings_flag'] = 
np.where(avg_cust_data.index.isin(top_max.index) , 'Top Max', 
np.where(avg_cust_data.index.isin(top_min.index), 'Top Min', 'AVG')) 

Eine andere Lösung:

df1 = avg_cust_data.describe() 
top_max_treshold = df1.loc['25%', 'user_spendings'] 
top_min_treshold = df1.loc['75%', 'user_spendings'] 
print (top_max_treshold) 

avg_cust_data = avg_cust_data.sort_values('user_spendings') 
avg_cust_data['spendings_flag1'] = 
np.where(avg_cust_data['user_spendings'] <= top_max_treshold , 'Top Min', 
np.where(avg_cust_data['user_spendings'] >= top_min_treshold, 'Top Max', 'AVG')) 


print (avg_cust_data) 
+0

Vielen Dank! – user2702405

Verwandte Themen