2 回答
TA贡献1827条经验 获得超9个赞
利用:
#extract numbers from id and compare by % 2 == 0
mask = df['id'].str.extract('(\d+)', expand=False).astype(int) % 2 == 0
#lambda function for change order
f = lambda x: x.iloc[::-1]
#apply only for groups match condition
df[mask] = df[mask].groupby(df['id']).transform(f)
print (df)
name id description
0 a String 1 lion
1 b String 1 snake
2 c String 1 bear
3 d String 1 tiger
4 e String 1 dog
5 j String 2 rhino
6 i String 2 eagle
7 h String 2 whale
8 g String 2 bird
9 f String 2 cat
10 k String 3 monkey
11 l String 3 lamb
12 m String 3 horse
13 n String 3 goat
14 o String 3 rabbit
15 t String 4 beaver
16 s String 4 sloth
17 r String 4 fox
18 q String 4 jaguar
19 p String 4 frog
20 u String 5 parrot
21 v String 5 dolphin
22 w String 5 seal
23 x String 5 spider
24 y String 5 panda
TA贡献1828条经验 获得超13个赞
(
df.groupby('id')
.apply(lambda x: x.iloc[::-1] if int(x.id.iloc[0].strip('String '))%2==0 else x)
.reset_index(drop=True)
)
添加回答
举报