如何根据工作日对 pandas 中的行进行会话化? [英] How can I Sessionize rows in pandas based on week days?

查看:83
本文介绍了如何根据工作日对 pandas 中的行进行会话化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的熊猫数据框

I have a pandas data frame it looks like this

 0  1   2   3   4   5   6   7   8   9   ... 253 254 255 256 257 258 259 260 261 262
0       30  84  126 135 137 179 242 342 426 ... None    None    None    None    None    None    None    None    None    None
1       24  53  75  134 158 192 194 211 213 ... None    None    None    None    None    None    None    None    None    None
2       51  143 173 257 446 491 504 510 559 ... None    None    None    None    None    None    None    None    None    None
3       1   20  22  92  124 149 211 335 387 ... None    None    None    None    None    None    None    None    None    None 

我想根据工作日对每一行进行会话化 我尝试了for循环,但是在时间和内存方面遇到了问题

I want to sessionize each row based on week days I tried a for loop but I'm getting problems in time and memory

所以基本上我想要的是用这样的大小为7的步骤在每一行上循环

so basically what I want is to loop over each row with a step of size seven like this

range(1,1001,7)

检查电话号码是否在我当前的范围内

check if the number is in my current range

如果它不为零,

如果在我的范围内,请返回我的电话号码%7 +1,

if it's in my range return my number % 7 +1,

然后将属于同一范围的数字连接到一个列表中

then concatenate the numbers which fall in the same range into one list

所以我应该以143列结尾.

so I should end up with 143 columns.

第一行应该是这样

0 0 0 3 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 [3,5] 0 0 0 0 and so on

推荐答案

IIUC:

您可以只设置要过滤的数据框

You could just setup your dataframe to be filtered

如果您有这样的数据框

df = pd.DataFrame(np.random.randint(0,30,(10,10)))

    0   1   2   3   4   5   6   7   8   9
0   2  11  28  20  22   9  20  15   1  28
1   2   8  10   9  16   3   7   1  13  28
2   6   9  14  20  23   3   6   5  29   6
3  21  25  11  10  20  15  10  11  21   9
4   5  14  11  19   5   1  23   0   1   3
5  13  18  21   4  26   5  18   6  29  20
6   6   6  22   7  29  18  12  17   4   2
7   0  26  26   3  22  21  11  15  29  21
8   9  28  29   0  24  24  13   4   9  20
9   5  18   7  13  17   0  22  19  12  19


df['bottom'] = np.arange(0,len(df)) // 7 #set groups

df.iloc[:,:-1] = df.iloc[:,:-1]%7+1 #set values
df[(df <= df['bottom']+1) | (df >= df['bottom']+7)].fillna(0).astype(int) #filter

给予

   bottom  0  1  2  3  4  5  6  7  8  9
0       0  0  0  1  0  0  0  0  2  2  1
1       0  0  0  0  0  0  0  1  2  0  1
2       0  0  0  1  0  0  0  0  0  2  0
3       0  1  0  0  0  0  0  0  0  1  0
4       0  0  1  0  0  0  0  0  1  2  0
5       0  0  0  1  0  0  0  0  0  2  0
6       0  0  0  0  1  0  0  0  0  0  0
7       0  1  0  0  0  0  1  0  2  2  1
8       0  0  1  0  1  0  0  0  0  0  0
9       0  0  0  1  0  0  1  0  0  0  0

这篇关于如何根据工作日对 pandas 中的行进行会话化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆