【问题标题】:Rearrange index of dataframe to move string to top重新排列数据框的索引以将字符串移动到顶部
【发布时间】:2017-08-10 15:53:39
【问题描述】:

我有一个这样的数据框:

    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

我想 groupby LC_REF 并将“Apple”移动到每个 groupby 的顶部,同时保留相同的顺序。所以最终的输出应该是这样的:

    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'])

但老实说,我不知道如何用这种语法来表达,或者我是否走在正确的轨道上。感谢观看

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    其中一种方法是使用双 .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 一个值 指数 0 DT 16 2C 乔恩,富,酒吧 1 DT 16 2C a Foo,bar,foobar,random,info 2 DT 16 2C 一个随机的、泰迪熊、罗斯福 3 DT 16 3C 一个苹果 4 DT 16 3C 填料,信息 5 DT 16 3C 一个 foobar,foo,bar 6 DT 16 3C 一个 foobar 7 DT 17 1C 一个苹果 8 DT 17 1C 随机,信息,待,被,移动 9 DT 17 1C a foo, aabr 10 DT 17 1C aabr,foo 11 DT 17 2C 敏感 12 DT 17 2C 一个 wtf 13 DT 17 2C 一个 foo,bar 14 DT 17 3C 做 15 DT 17 3C 俄罗斯方块

    希望对你有帮助

    【讨论】:

    • 漂亮,成功了,谢谢!关于 pandas 和 Python,我似乎还有很多东西要学
    猜你喜欢
    • 2019-12-20
    • 2016-11-07
    • 1970-01-01
    • 2014-06-23
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多