我的问题有点棘手 . 我已经分解了我的巨大数据文件并多次将模糊 - 模糊代码应用于每个块 . 之后,我将结果整理成一个文件 . 我想知道是否可以应用某种循环来重用代码而不是为每个变量编写代码 . 以下是示例 .
df = pd.read_csv('dec 10.csv')
df1 = df.iloc[0:20000]
df2 = df.iloc[20000:40000]
df3 = df.iloc[40000:60000]
match1 = df1['Customer Name'].map(lambda x: difflib.get_close_matches(x, df1['Customer Name'].values, n=2, cutoff=0.8)).apply(pd.Series).dropna(axis=0)
match2 = df2['Customer Name'].map(lambda x: difflib.get_close_matches(x, df2['Customer Name'].values, n=2, cutoff=0.8)).apply(pd.Series).dropna(axis=0)
match3 = df3['Customer Name'].map(lambda x: difflib.get_close_matches(x, df3['Customer Name'].values, n=2, cutoff=0.8)).apply(pd.Series).dropna(axis=0)
a = match1.append(match2, ignore_index =True)
b = a.append(match3, ignore_index =True)
我正在寻找一种优化的方法来编写匹配代码一次,而不是为每个数据块编写它,然后再进行整理 .
2 回答
首先,你可以将这些东西分成长度为
n
的组将
20000
替换为n
,你将得到每个最多20,000个的块 . 然后,您可以循环dfgroups
中每个项目的代码 . 此外,您还希望matches
成为您可以追加的自己的列表 . 最后,为了便于阅读,对于一个很长的行,你可能只想写一个mapper
函数而不是使用一个庞大的lambda .把这一切放在一起,你的代码就可以像这样重写 .
现在
matches
相当于[match1, match2, match3, ...]
,可以像matches[0]
matches[1]
等一样使用您可以循环遍历数据框列表,以便在每次迭代时只需引用
df
并避免重复代码: