[英]How to create a DataFrame series as a sub-string of a DataFrame Index?
[英]Validation for repeated sub-string in a dataframe
假設我有一個這樣的數據框:
df = pd.DataFrame({'A': ["asdfg", "abcdef", "ababab", "ghhzgghz", "qwerty"], 'B': [1, 2, 3, 4, 5]})
df.head()
開/關:
A B
asdfg 1
abcdef 2
ababab 3
ghhzgghz 4
qwerty 5
如何驗證 A 列中是否有任何重復的子字符串?
A B C
asdfg 1 False
abcdef 2 False
ababab 3 True (matches for ab)
ghhzgghz 4 True (matches for gh)
qwerty 5 False
return s in (s + s)[1:-1]
的一般邏輯,但我希望針對這些行中的每一行中的任何一般子字符串重復進行簡化。
想法是創建所有可能的子字符串,然后通過Counter
對它們進行Counter
並檢查是否至少有一個計數>1
:
from collections import Counter
#modified https://stackoverflow.com/a/22470047/2901002
def test_substrings(input_string):
length = len(input_string)
s = [input_string[i:j+1] for i in range(length) for j in range(i,length)]
return any(x > 1 for x in Counter(s).values())
另一種修改測試字符串最小長度的簡單方法的解決方案:
from itertools import chain, combinations
#changed first word asdfg to asdfa
df = pd.DataFrame({'A': ["asdfa", "abcdef", "ababab", "ghhzgghz", "qwerty"],
'B': [1, 2, 3, 4, 5]})
def test_substrings(input_string, N):
s = chain(*[combinations(input_string,x) for x in range(N,len(input_string)+1)])
return any(x > 1 for x in Counter(s).values())
df['C'] = df['A'].apply(lambda x: test_substrings(x, 1))
df['D'] = df['A'].apply(lambda x: test_substrings(x, 2))
print (df)
A B C D
0 asdfa 1 True False
1 abcdef 2 False False
2 ababab 3 True True
3 ghhzgghz 4 True True
4 qwerty 5 False False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.