【问题标题】:Df groupby set comparisondf groupby 集比较
【发布时间】:2018-01-18 23:08:53
【问题描述】:

我有一个要测试字谜的单词列表。我想使用熊猫,所以我不必使用计算上的浪费循环。给定一个 .txt 的单词列表说:

"acb" “bca” “富” “钱币” “猎犬”

我想将它们放在一个 df 中,然后按它们的字谜列表对它们进行分组 - 我可以稍后删除重复的行。

到目前为止,我有代码:

import pandas as pd

wordlist = pd.read_csv('data/example.txt', sep='\r', header=None, index_col=None, names=['word'])
wordlist = wordlist.drop_duplicates(keep='first')
wordlist['split'] = ''
wordlist['anagrams'] = ''

for index, row in wordlist.iterrows() :
    row['split'] = list(row['word'])

wordlist = wordlist.groupby('word')[('split')].apply(list)
print(wordlist)

我如何按一个集合分组以便它知道

[[a, b, c]]
[[b, a, c]]

都一样吗?

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    我觉得你可以用sortedlists:

    df['a'] = df['word'].apply(lambda x: sorted(list(x)))
    print (df)
    
          word                      a
    0      acb              [a, b, c]
    1      bca              [a, b, c]
    2      foo              [f, o, o]
    3      oof              [f, o, o]
    4  spaniel  [a, e, i, l, n, p, s]
    

    查找字谜的另一种解决方案:

    #reverse strings
    df['reversed'] = df['word'].str[::-1]
    
    #reshape
    s = df.stack()
    #get all dupes - anagrams
    s1 = s[s.duplicated(keep=False)]
    print (s1)
    0  word        acb
       reversed    bca
    1  word        bca
       reversed    acb
    2  word        foo
       reversed    oof
    3  word        oof
       reversed    foo
    dtype: object
    
    #if want select of values by second level word
    s2 = s1.loc[pd.IndexSlice[:, 'word']]
    print (s2)
    0    acb
    1    bca
    2    foo
    3    oof
    dtype: object
    

    【讨论】:

    • 那么在你原来的例子中,为什么我不能在列表中使用 join() ?它不想让我!
    • 是的,这是不可能的,需要转换成元组。所以使用df['a'] = df['word'].apply(lambda x: tuple(sorted(list(x))))
    • 对不起,我真的很困惑 - 这也不起作用:anaglist = wordlist['anagrams'] = wordlist['word'].apply(lambda x: tuple(sorted(list(x )))) wordlist['anagrams'] = ''.join(anaglist)
    • 我想我明白了,使用df['word'].apply(lambda x: ''.join(sorted(list(x))))
    • 太棒了! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多