【问题标题】:Pandas DataFrame group-by indexes matching list - indexes respectively smaller than list[i+1] and greater than list[i]Pandas DataFrame 分组索引匹配列表 - 索引分别小于 list[i+1] 和大于 list[i]
【发布时间】:2020-10-21 15:25:23
【问题描述】:

我有一个 DataFrame Times_df,时间在单列中,第二个 DataFrame End_df,每个组的特定结束时间都按组名索引。

Times_df = pd.DataFrame({'time':np.unique(np.cumsum(np.random.randint(5, size=(100,))), axis=0)})

End_df = pd.DataFrame({'end time':np.unique(random.sample(range(Times_df.index.values[0], Times_df.index.values[-1]), 10))})
End_df.index.name = 'group'

我想为 Times_df 中小于或等于 End_df 中每个连续结束时间但大于前一个的所有时间添加一个组索引

我现在只能用一个循环来做到这一点,这需要永远;(

lis = []
i = 1
for row in Times_df['time'].values:
while i <= row:
    lis.append((End_df['end time']==row).index)
    i +1

然后我将列表 lis 作为新列添加到 Times_df

Times_df['group']=lis 

可悲的是,另一个仍然使用循环的解决方案是:

test_df = pd.DataFrame()
for group, index in  End_df.iterrows():
    test = count.loc[count.index<=index['end time]][:]
    test['group']=group
    test_df = pd.concat([test_df,test], axis=0, ignore_index=True)

【问题讨论】:

    标签: python pandas indexing group-by


    【解决方案1】:

    我认为您正在寻找的是 pd.cut 将您的价值观分类到组中。

    bins = [0, 3, 10, 20, 53, 59, 63, 65, 68, 74, np.inf]
    groups = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    Times_df["group"] = pd.cut(Times_df["time"], bins, labels=groups)
    
    print(Times_df)
        time    group
    0   2   0
    1   3   0
    2   7   1
    3   11  2
    4   15  2
    5   16  2
    6   18  2
    7   22  3
    8   25  3
    9   28  3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2023-04-11
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 2016-11-22
      • 1970-01-01
      相关资源
      最近更新 更多