gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:33:45 25 4
gpt4 key购买 nike

我找不到自动获取前 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)

关于Python使用其他列值创建具有最高值(%)的新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41237756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com