【问题标题】:Splitting of a huge data and looping the same code for all chunks of data拆分大量数据并为所有数据块循环相同的代码
【发布时间】:2018-12-10 10:11:20
【问题描述】:

我的问题有点棘手。我已经将我的巨大数据文件分成几块,并多次对每个块应用模糊的代码。之后,我将结果整理到一个文件中。我想知道是否可以应用某种循环来重用代码,而不是为每个变量编写代码。下面是例子。

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)

我正在寻找一种优化的方式来编写一次匹配代码,而不是为每个数据块编写它,然后再进行整理。

【问题讨论】:

  • 这正是函数的用途。你熟悉函数的工作原理吗?在您的示例中,即使是一个简单的 for 循环也会有所帮助。
  • 是的,我可以编写直接代码,但不能编写函数。现在正在检查,并会试一试......

标签: python pandas loops


【解决方案1】:

那么首先你可以像这样将一些东西分成长度为n的组

dfgroups = [df[x:x+n] for x in range(0, len(df), n)]

20000 替换为n,您将获得最多20,000 个块。然后,您可以为dfgroups 中的每个项目循环代码。此外,您还希望 matches 成为您可以附加到的自己的列表。最后,为了可读性,对于这么长的一行,您可能只想编写一个 mapper 函数而不是使用大量的 lambda。

将所有这些放在一起,您的代码可以这样重写。

df = pd.read_csv('dec 10.csv')

# split df into groups of 20,000
dfgroups = [df[x:x+20000] for x in range(0, len(df), 20000)]
matches = [] # empty list to store matches

for dfgroup in dfgroups:

    # a function to replace that long line, more readable
    # this function will get redefined every loop, using the new `dfgroup` each iteration
    # this is optional, and you can instead keep that long line, replacing `df` with `dfgroup`
    def mapper(x):
        values = dfgroup['Customer Name'].values
        result = difflib.get_close_matches(x, values, n=2, cutoff=0.8))
        result = result.apply(pd.Series)
        result = result.dropna(axis=0)
        return result

    match = group['Customer Name'].map(mapper) # passing the function as an argument rather than using a lambda
    matches.append(match) # append it to the matches list

现在matches 等同于[match1, match2, match3, ...],可以像matches[0] matches[1] 等一样使用

【讨论】:

  • 感谢您的解释。
【解决方案2】:

您可以遍历数据框列表,这样每次迭代时您只需引用df 并避免重复代码:

match = pd.Dataframe()
for df in [df1,df2,df3]:
    match_ = df['Customer Name'].map(lambda x: difflib
                 .get_close_matches(x, df['Customer Name'].values, n=2, cutoff=0.8))
                 .apply(pd.Series).dropna(axis=0)
    match = match.append(match_, ignore_index =True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 2020-07-12
    相关资源
    最近更新 更多