我有一个单词列表,我想测试字谜。我想使用熊猫,所以我不必使用计算浪费的循环。给定.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]]
是一样的吗?
答案 0 :(得分:1)
我认为您可以使用sorted
list
s:
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