re.sub "Beklenen dize veya bayt benzeri nesne" ile hata veriyor;
Bu hatayla ilgili birden fazla yazı okudum, ancak hala anlayamıyorum. Fonksiyonum boyunca döngü yapmaya çalıştığımda:
def fix_Plan(location):
letters_only = re.sub("[^a-zA-Z]", # Search for all non-letters
" ", # Replace all non-letters with spaces
location) # Column and row to search
words = letters_only.lower().split()
stops = set(stopwords.words("english"))
meaningful_words = [w for w in words if not w in stops]
return (" ".join(meaningful_words))
col_Plan = fix_Plan(train["Plan"][0])
num_responses = train["Plan"].size
clean_Plan_responses = []
for i in range(0,num_responses):
clean_Plan_responses.append(fix_Plan(train["Plan"][i]))
İşte hata:
Traceback (most recent call last):
File "C:/Users/xxxxx/PycharmProjects/tronc/tronc2.py", line 48, in <module>
clean_Plan_responses.append(fix_Plan(train["Plan"][i]))
File "C:/Users/xxxxx/PycharmProjects/tronc/tronc2.py", line 22, in fix_Plan
location) # Column and row to search
File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python36\lib\re.py", line 191, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object
41
3
Yorumlarda belirttiğiniz gibi, bazı değerler string değil float olarak görünmektedir. Bunu
re.sub
a aktarmadan önce string olarak değiştirmeniz gerekecektir. En basit yolre.sub
kullanırkenlocation
değerinistr(location)
olarak değiştirmektir. Zaten birstr
olsa bile bunu yapmaktan zarar gelmez.Sanırım re.match() fonksiyonunu kullanmak daha iyi olacaktır. işte size yardımcı olabilecek bir örnek.
en basit çözüm, döngüye sokmaya çalıştığınız sütuna python str işlevini uygulamaktır.
pandas kullanıyorsanız bu şu şekilde uygulanabilir
dataframe['column_name']=dataframe['column_name'].apply(str)