gpt4 book ai didi

python - 重新排列数据帧的索引以将字符串移至顶部

转载 作者:行者123 更新时间:2023-11-30 22:32:05 25 4
gpt4 key购买 nike

我有一个这样的数据框:

    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                        valsindex                                         0      DT 16 2C  a                 Jon,Foo,Bar1      DT 16 2C  a  Foo,bar,foobar,random,info2      DT 16 2C  a    random, teddy, roosevelt3      DT 16 3C  a                       apple4      DT 16 3C  a                filler, info5      DT 16 3C  a              foobar,foo,bar6      DT 16 3C  a                      foobar7      DT 17 1C  a                       apple8      DT 17 1C  a     random,info,to,be,moved9      DT 17 1C  a                   foo, aabr10     DT 17 1C  a                    aabr,foo11     DT 17 2C  a                      touchy12     DT 17 2C  a                         wtf13     DT 17 2C  a                     foo,bar14     DT 17 3C  a                          do15     DT 17 3C  a                      tetris

希望对你有帮助

关于python - 重新排列数据帧的索引以将字符串移至顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45618337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com