【问题标题】:Reoder Series rows based on index of a value根据值的索引重新排序系列行
【发布时间】:2020-12-28 23:44:36
【问题描述】:

我有一个大熊猫系列,所以优化是关键

pd.Series(['I like apples', 'They went skiing vacation', 'Apples are tasty', 'The skiing was great'], dtype='string')

0                I like apples
1    They went skiing vacation
2             Apples are tasty
3         The skiing was great
dtype: string

考虑行是字符串列表,即第 0 行是 ['I', 'like', 'apples']。

我想获取“apples”的索引并根据该索引的值对行重新排序。在这个例子中,系列看起来像:

2             Apples are tasty
0                I like apples
1    They went skiing vacation
3         The skiing was great
dtype: string

因为“apples”的索引(忽略区分大小写)在第 2 行中为 0。

【问题讨论】:

    标签: pandas indexing series


    【解决方案1】:

    使用Series.str.contains

    #create DataFrame by split and reshape
    s1 = s.str.split(expand=True).stack()
    #filter only matched apple rows, sorting by second level (possition of apples)
    idx  = s1[s1.str.contains('apples', case=False)].sort_index(level=1).index
    
    #get original index by uion and select by loc for change ordering
    s = s.loc[idx.remove_unused_levels().levels[0].union(s.index, sort=False)]
    print (s)
    2             Apples are tasty
    0                I like apples
    1    They went skiing vacation
    3         The skiing was great
    dtype: string
    

    列表理解和枚举的另一个想法:

    a = [next(iter(i for i, j in enumerate(x.split()) if j.lower() == 'apples'), len(s)*10) for x in s]
    print (a)
    [2, 40, 0, 40]
    
    s = s.loc[np.array(a).argsort()]
    print (s)
    2             Apples are tasty
    0                I like apples
    1    They went skiing vacation
    3         The skiing was great
    dtype: string
    

    【讨论】:

    • 抱歉,jezrael,我的问题并不清楚。这些行由字符串列表组成。 (我已经相应地编辑了我的问题)
    • len(s) * 10 的原因是什么?
    • @user270199 为了正确的顺序,我需要一些大数字,而不是最大整数,我使用这个技巧
    猜你喜欢
    • 1970-01-01
    • 2021-12-24
    • 2017-03-27
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 2019-12-20
    相关资源
    最近更新 更多