python迭代循环遍历datafram的列

2024-09-28 17:21:55 发布

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

在处理一个问题时,我用python编写了以下数据帧

    week    hour    week_hr     store_code  baskets
0   201616  106     201616106   505         0
1   201616  107     201616107   505         0
2   201616  108     201616108   505         0
3   201616  109     201616109   505         18
4   201616  110     201616110   505         0
5   201616  106     201616108   910         0
6   201616  107     201616106   910         0
7   201616  108     201616107   910         2
8   201616  109     201616108   910         3
9   201616  110     201616109   910         10

这里“hour”变量是“weekday”和“hour of shop”的concat,例如weekday是monday=1,hour of shop是6am,那么hour variable=106,同样的,cal_hr是一个周和小时的concat。我想得到那些我认为没有篮框趋势的行,即滚动3周的0篮数。在上面的例子中,我只得到前3行。i、 e.对于存储505,从106到108有1个篮子的连续循环。但我不想要第4、5、6行,因为即使连续3个小时有0个篮子,但这些小时实际上不是连续的。110->;106->;107。对于连续的小时数,它们应该在106-110的范围内。基本上,我想要所有的商店和相应的行,如果它有0篮子连续3小时在任何一天。虚拟输出

^{pr2}$

我可以在python中使用pandas和loops来完成这个任务吗?数据集需要按存储和小时进行排序。完全不熟悉python(


Tags: of数据storegthrcodeshop小时
2条回答

执行以下操作:

  1. 按门店代码、周/小时排序
  2. 按0筛选
  3. 将减法存储在df['week_hr'][1:]之间。值df['week_hr'][:-1]。值之间,这样您就可以知道它们是否连续。在
  4. 现在,您可以将组设置为连续,并根据需要进行过滤。在

    import numpy as np
    import pandas as pd
    
    # 1
    t1 = df.sort_values(['store_code', 'week_hr'])
    
    # 2
    t2 = t1[t1['baskets'] == 0]
    
    # 3
    continuous = t2['week_hr'][1:].values-t2['week_hr'][:-1].values == 1
    groups = np.cumsum(np.hstack([False, continuous==False]))
    t2['groups'] = groups
    
    # 4
    t3 = t2.groupby(['store_code', 'groups'], as_index=False)['week_hr'].count()
    t4 = t3[t3.week_hr > 2]
    print pd.merge(t2, t4[['store_code', 'groups']])
    

不需要循环!在

您可以解决:

  1. 按门店代码、周/小时排序
  2. 按0筛选
  3. 按门店代码分组
  4. 找到连续的

代码:

t1 = df.sort_values(['store_code', 'week_hr'])

t2 = t1[t1['baskets'] == 0]

grouped = t2.groupby('store_code')['week_hr'].apply(lambda x: x.tolist())    

for store_code, week_hrs in grouped.iteritems():
    print(store_code, week_hrs)
    # do something

相关问题 更多 >