我试图循环使用熊猫中某列的值,并更改所有类似的值,使它们协调一致。我首先将该列提取为一个列表,并希望对每一行进行循环,在找到类似的值时将其替换为类似的值,然后将列表放回dataframe中替换该列。例如,一个列,如:
Cool
Awesome
cool
CoOl
Awesum
Awesome
Mathss
Math
Maths
Mathss
将成为:
CoOl
Awesome
coOol
CoOl
Awesome
Awesome
Mathss
Mathss
Mathss
Mathss
代码如下:
def matchbrands():
conn = sqlite3.connect('/Users/XXX/db.sqlite3')
c = conn.cursor()
matchbrands_df = pd.read_sql_query("SELECT * from removeduplicates", conn)
brands = [x for x in matchbrands_df['brand']]
i=1
for x in brands:
if fuzz.token_sort_ratio(x, brands[i]) > 85:
x = brands[i]
else:
i += 1
n = matchbrands_df.columns[7]
matchbrands_df.drop(n, axis=1, inplace=True)
matchbrands_df[n] = brands
matchbrands_df.to_csv('/Users/XXX/matchedbrands.csv')
matchbrands_df.to_sql('removeduplicates', conn, if_exists="replace")
但是,这根本不会更改列。我不知道为什么。任何帮助都将不胜感激
你的代码毫无意义
第一:使用
x =...
不能更改列表brands
上的值。你需要brands[index] = ...
第二:它需要嵌套的
for
-loop将x
与brands
中的所有其他单词进行比较最小工作代码
结果:
它不会将
Awesum
更改为Awesome
,因为它得到77
它不会将
Math
更改为Mathss
,因为它得到80
。但是Maths
会得到89
如果在
for
-循环中使用word = other_word
,那么它可以将Math
转换为Maths
(89
),然后将Maths
转换为Mathss
(91
)。但这样一来,它可能会改变很多次,最后它会变成一个单词,这个单词最初可以给出比85
小得多的值。您还可以为75
而不是85
获得预期结果但是这种方法得到的最后一个单词的值是
>85
,而不是最大的值-因此可以有更好的匹配单词,并且不会使用它。使用break-it获得第一个单词和>85
。也许它应该获取所有带有>85
的单词,并选择具有最大值的单词。它必须跳过相同但在不同行中的单词。但所有这些都会造成奇怪的情况在代码注释中,我保留了其他修改意见
编辑:
与{}和颜色相同
相关问题 更多 >
编程相关推荐