在python pandas

时间:2018-04-18 23:55:49

标签: python pandas numpy dataframe

我知道如何使用shift来移动行。

df.shift(2)  # periods = 2

我知道如何按步骤选择所有偶数行

 df.iloc[1::2]  # all even rows

但是如何在原始数据集中以特定周期向下移动所有这些偶数行?

import pandas as pd

d = {'ID': [ "A1","A1", "A2","A2","A3","A3","B1","B1","B2","B2","B3","B3","C1",
             "C1","C2","C2","C3","C3"],

     'value': [11,12,13,14,15,16,21,22,23,24,25,26,31,32,33,34,35,36]}

df = pd.DataFrame(data=d)
  ID  value
0   A1     11
1   A1     12
2   A2     13
3   A2     14
4   A3     15
5   A3     16
6   B1     21
7   B1     22
8   B2     23
9   B2     24
10  B3     25
11  B3     26
12  C1     31
13  C1     32
14  C2     33
15  C2     34
16  C3     35
17  C3     36

最终的数据框将是这样的,

 ID  value
0   A1     11
1   A2     13
2   A3     15     #  all even rows shifted 2 units down
3   A1     12    #  ↓
4   A2     14    #  ↓
5   A3     16    #  ↓
6   B1     21
7   B2     23
8   B3     25
9   B1     22    #  ↓
10  B2     24    #  ↓
11  B3     26    #  ↓
12  C1     31
13  C2     33
14  C3     35
15  C1     32    #  ↓
16  C2     34    #  ↓
17  C3     36    #  ↓

2 个答案:

答案 0 :(得分:2)

我认为你没有描述过你正在做的事情。

然而,IIUC

def shifty(d):
    return d.iloc[(np.arange(len(d)) % 2).argsort(kind='mergesort')]

df.groupby(df.ID.str[0], group_keys=False).apply(shifty)

    ID  value
0   A1     11
2   A2     12
4   A3     13
1   A1     11
3   A2     12
5   A3     13
6   B1     21
8   B2     22
10  B3     23
7   B1     21
9   B2     22
11  B3     23
12  C1     31
14  C2     32
16  C3     33
13  C1     31
15  C2     32
17  C3     33

答案 1 :(得分:2)

我不确定这是你需要的,但这是实现偶数的转换

s=df[np.arange(len(df))%2==0]
s.index=s.index+2

df=s.combine_first(df)

更新

df['key1']=np.arange(len(df))%2

df['key2']=np.arange(len(df))//6

df.sort_values(['key2','key1'])
Out[770]: 
    ID  value  key1  key2
0   A1     11     0     0
2   A2     13     0     0
4   A3     15     0     0
1   A1     12     1     0
3   A2     14     1     0
5   A3     16     1     0
6   B1     21     0     1
8   B2     23     0     1
10  B3     25     0     1
7   B1     22     1     1
9   B2     24     1     1
11  B3     26     1     1
12  C1     31     0     2
14  C2     33     0     2
16  C3     35     0     2
13  C1     32     1     2
15  C2     34     1     2
17  C3     36     1     2