我有一个这样的数据框:
LC_REF a vals
0 DT 16 2C a Jon,Foo,Bar
1 DT 16 2C a Foo,bar,foobar,random,info
2 DT 16 2C a random, teddy, roosevelt
3 DT 16 3C a filler, info
4 DT 16 3C a apple
5 DT 16 3C a foobar,foo,bar
6 DT 16 3C a foobar
7 DT 17 1C a random,info,to,be,moved
8 DT 17 1C a apple
9 DT 17 1C a foo, aabr
10 DT 17 1C a aabr,foo
11 DT 17 2C a touchy
12 DT 17 2C a wtf
13 DT 17 2C a foo,bar
14 DT 17 3C a do
15 DT 17 3C a tetris
我想对 LC_REF 进行分组,并将“Apple”移动到每个分组的顶部,同时保留相同的顺序。所以最终的输出希望如下所示:
LC_REF a vals
0 DT 16 2C a Jon,Foo,Bar
1 DT 16 2C a Foo,bar,foobar,random,info
2 DT 16 2C a random, teddy, roosevelt
4 DT 16 3C a apple
3 DT 16 3C a filler, info
5 DT 16 3C a foobar,foo,bar
6 DT 16 3C a foobar
8 DT 17 1C a apple
7 DT 17 1C a random,info,to,be,moved
9 DT 17 1C a foo, aabr
10 DT 17 1C a aabr,foo
11 DT 17 2C a touchy
12 DT 17 2C a wtf
13 DT 17 2C a foo,bar
14 DT 17 3C a do
15 DT 17 3C a tetris
我尝试了一些 groupby 和 reindex 的变体,但没有成功:
df.groupby('LC_REF').reindex(['apple'])
但老实说,我不知道如何表达这个语法,或者我是否走在正确的轨道上。感谢您的浏览
最佳答案
其中一种方法是使用索引值的双 .loc
递增和递减,即
df = df.reset_index()
df.loc[df.loc[df['vals'].str.contains('apple'),'index']-1,'index']+=1
df.loc[df['vals'].str.contains('apple'),'index']-=1
df = df.set_index('index',drop=True).sort_index()
输出:
LC_REF a vals index 0 DT 16 2C a Jon,Foo,Bar 1 DT 16 2C a Foo,bar,foobar,random,info 2 DT 16 2C a random, teddy, roosevelt 3 DT 16 3C a apple 4 DT 16 3C a filler, info 5 DT 16 3C a foobar,foo,bar 6 DT 16 3C a foobar 7 DT 17 1C a apple 8 DT 17 1C a random,info,to,be,moved 9 DT 17 1C a foo, aabr 10 DT 17 1C a aabr,foo 11 DT 17 2C a touchy 12 DT 17 2C a wtf 13 DT 17 2C a foo,bar 14 DT 17 3C a do 15 DT 17 3C a tetris
希望对你有帮助
关于python - 重新排列数据帧的索引以将字符串移至顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45618337/