Skip to main content
 首页 » 编程设计

Python使用其他列值创建具有最高值(%)的新列

2025年05月04日13lexus

我找不到自动获取前 n% 的函数,因此我对最大值和最小值进行了排序,并计算了数字以形成前 25% 和最小 25% 的范围。我想要做的是在新列中创建一个标志,表明该客户的收入排名前 25%。

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')) 

请您参考如下方法:

您可以使用:

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')) 

另一种解决方案:

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)