【问题标题】:Sort pandas list type column values based on another list type column根据另一个列表类型列对熊猫列表类型列值进行排序
【发布时间】:2021-05-25 10:41:24
【问题描述】:

我有一个这样的数据框,

df 
col1        col2                 col3
A       ['p', 'q', 'r']          ['x', 'r', 'p']
B       ['x', 'y']               ['y']
C       ['t', 'u', 'p']          ['u', 'p', 'x', 't']
D       ['a', 'b']               ['x', 'y']

现在我想根据 col3 序列对 col2 的值(列表)进行排序,以便最终的数据框看起来像,

 df
 
 col1        col2                 col3
 A       ['r','p', 'q']           ['x', 'r', 'p']
 B       ['y', 'x']               ['y']
 C       ['u', 'p','t']           ['u', 'p', 'x', 't']
 D       ['a', 'b']               ['x', 'y']

我可以使用 for 循环并比较两个列表来执行此操作,但执行需要更多时间,需要寻找一些 pandas 快捷方式来更有效地执行此操作。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    一个想法是使用带有列表推导的 cutom 函数来测试成员资格:

    def f(x):
        a = x['col2']
        b = x['col3']
        yes = [x for x in b if x in a]
        no =  [x for x in a if x not in out]
    
        return yes + no
        
        
    
    df['col2'] = df.apply(f, axis=1)
    print (df)
      col1       col2          col3
    0    A  [r, p, q]     [x, r, p]
    1    B     [y, x]           [y]
    2    C  [u, p, t]  [u, p, x, t]
    3    D     [a, b]        [x, y]
    

    熊猫解决方案:

    df['col2'] = (df['col3'].explode().reset_index()
                            .merge(df['col2'].explode().reset_index(), 
                                   left_on=['index','col3'],
                                   right_on=['index','col2'],
                                   how='outer')
                           .dropna(subset=['col2'])
                           .groupby('index')['col2']
                           .agg(list))
    print (df)
      col1       col2          col3
    0    A  [r, p, q]     [x, r, p]
    1    B     [y, x]           [y]
    2    C  [u, p, t]  [u, p, x, t]
    3    D     [a, b]        [x, y]
    

    【讨论】:

    • 你好 jazzy:你有答案吗:stackoverflow.com/q/66327954/6660373 只是想知道必须有一些更好的解决方案使用 pandas 函数(melt/pivot 等)。
    • @Pygirl - 在这里使用列表,熊猫不太喜欢 ;) 所以纯 python 是最好的(在我看来)。熊猫解决方案的第一个想法是不可能的,然后尝试爆炸和合并它工作。编辑答案。
    • 我要求上面发布的链接(问题):P。但是感谢您提供更多的方法,这将让您学到新的东西。
    猜你喜欢
    • 2021-07-30
    • 2021-05-02
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    相关资源
    最近更新 更多