如果数据帧列中的第n个最大值是一个大于等于x的数字,如何返回“True”

2024-05-13 03:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下所示的数据帧:

   prod_id  Fac     demand_near_wh
0   45906   Fac-1   0
1   45906   Fac-2   51
2   45906   Fac-3   30
3   45906   Fac-4   10
4   45906   Fac-5   52
5   48402   Fac-1   0
6   48402   Fac-2   72
7   48402   Fac-3   39
8   48402   Fac-4   14
9   48402   Fac-5   6

我想创建四个标题为"2nd_wh""3rd_wh"、和"4th_wh"、和"5th_wh"的新列。对于这些新列中的每一列,如果"demand_near_wh"中的值是第n高的数字(即第3高、第4高、第5高),我想返回"True",对于给定的prod_id,否则返回"False"

例如,在"3rd_wh"列中,如果"demand_near_wh"中的值是给定产品id的第三高值并且是>=30,则返回"True",否则返回"False"。在"4th_wh"列中,如果给定prod_id"demand_near_wh"中的值是第四高的值并且是>=30,则返回"True",否则返回"False",以此类推

最终输出应如下所示:

   prod_id  Fac     demand_near_wh 1st_wh 2nd_wh 3rd_wh 4th_wh  5th_wh  
0   45906   Fac-1   0               False  False  False  False  True 
1   45906   Fac-2   51              False  True   False  False  False
2   45906   Fac-3   30              False  False  True   False  False
3   45906   Fac-4   10              False  False  False  True   False
4   45906   Fac-5   52              True   False  False  False  False
5   48402   Fac-1   0               False  False  False  False  True
6   48402   Fac-2   72              True   False  False  False  False
7   48402   Fac-3   39              False  True   False  False  False
8   48402   Fac-4   14              False  False  False  True   False
9   48402   Fac-5   6               False  False  False  True   False

我尝试了下面的代码,它适用于“1st_wh”列

df['1st_wh']=df.groupby(['prod_id'])['perc_dem_near_wh'].transform('max')==df['perc_dem_near_wh']
print(df.head(5))

   prod_id Facility  perc_dem_near_wh  1st_wh
0    45906    Fac-1                 0   False
1    45906    Fac-2                51   False
2    45906    Fac-3                30   False
3    45906    Fac-4                10   False
4    45906    Fac-5                52    True

然而,当我用下面的代码填充列“2nd_wh”时,我得到一个错误,它说"ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().我对Python非常陌生,不知道如何修复它。提前感谢任何能提供帮助的人

df['2nd_wh'] = df['perc_dem_near_wh'].apply(lambda x: 'True' if x >= 30 and df['perc_dem_near_wh'].nlargest(2) else'False')
print (df.head(15))

Tags: 数据代码idfalsetruedfprodhead
1条回答
网友
1楼 · 发布于 2024-05-13 03:21:31

我认为问题在于if语句期望df['perc_dem_near_wh'].nlargest(2)TrueFalse,但这应该是一列的两行。你是说像(x in df['perc_dem_near_wh'].nlargest(2).values )这样的东西来检查x是否在行中吗

相关问题 更多 >