Python比较特定行并组合

2024-04-26 22:08:40 发布

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

我有以下数据集:

Group   LowerTier    UpperTier   Value
  1         0           99         0    
  1         100         199        0
  1         200         299        10
  1         300         1000       20 
  2         0           249        0
  2         250         1000       5
(...)

我想用Python和pandas获得以下内容:

Group   LowerTier    UpperTier   Value
  1         0           199         0    
  1         200         299        10
  1         300         1000       20 
  2         0           249        0
  2         250         1000       5

换言之:我希望在得到双精度值的最小值和最大值的条件下(例如,第1组;值=0),合并一个组中具有相同值的所有行。你知道吗

我怎样才能弄到这张桌子?你知道吗

提前谢谢


Tags: 数据pandasvaluegroup精度条件桌子lowertier
1条回答
网友
1楼 · 发布于 2024-04-26 22:08:40

你用aggregate试过groupby吗?你知道吗

df.groupby(['Group','Value'],as_index=False).agg({'LowerTier':min,'UpperTier':max})

首先创建数据帧:

df = pd.DataFrame({'Group':[1,1,1,1,2,2],'LowerTier':[0,100,200,300,0,250],'UpperTier':[99,199,299,1000,249,1000],'Value':[0,0,10,20,0,5]})

然后用agg应用groupby

df.groupby(['Group','Value'],as_index=False).agg({'LowerTier':min,'UpperTier':max})

输出:

    Group   Value   UpperTier   LowerTier
0   1       0       199         0
1   1       10      299         200
2   1       20      1000        300
3   2       0       249         0
4   2       5       1000        250

相关问题 更多 >