【问题标题】:More efficient way of appending dataframe附加数据框的更有效方式
【发布时间】:2020-05-29 18:51:59
【问题描述】:

我正在运行一些测试,发现这里的这段代码效率低下。在日期范围内循环,如果self.querydf 中,则附加该行,非常简单。但是我听到了很多意见,认为这样的附加效率不高,甚至会消耗资源。
我的镶木地板有 4 列数百万行 - query phone_count desktop_count total,下降 2 列,这意味着我有 indexquerytotal,然后奇迹发生了。

这段代码工作“很好”,但现在我正在寻找有经验的用户的意见,并可能得到一些提示。

有没有更有效的方法来做同样的事情?元组可能吗?

谢谢你们!

    for filename in os.listdir(directory):
        if filename.endswith(".parquet"):
            df = pd.read_parquet(directory).drop(["phone_count","desktop_count"], axis=1)
            df.set_index("query", inplace=True)

            if self.lowercase == "on":
                df.index = df.index.str.lower()
            else:
                pass
            if self.sensitive == "on":                            
                self.datafr = self.datafr.append(df.filter(regex=re.compile(self.query), axis=0))
            else:            
                self.datafr = self.datafr.append(df.filter(regex=re.compile(self.query, re.IGNORECASE), axis=0))            


self.datafr = self.datafr.groupby(['query']).sum().sort_values(by='total', ascending=False)

【问题讨论】:

  • 你能解释一下正则表达式在做什么吗?
  • 那里的第一个正则表达式:假设查询是“Facebook”。然后脚本只寻找“Facebook”而不是“facebook”。首先是对查询真正区分大小写,其次是忽略查询的大小写。你可以在那里有“FaCEboOk”作为查询,它也会找到“facebook”和“Facebook”。

标签: python pandas dataframe append concat


【解决方案1】:

每个循环都在重复一些事情:

  • 正则表达式模式不需要每次都重新编译
  • 重复DataFrame.appendpd.concat([frame1, frame2, ...])
  • list.appendDataFrame.append 快​​很多

试试这个:

option = re.IGNORECASE if self.lowercase == "on" else 0
pattern = re.compile(self.query, option)
subframes = []

for filename in os.listdir(directory):
    if filename.endswith(".parquet"):
        df = pd.read_parquet(directory).drop(["phone_count","desktop_count"], axis=1)
        df.set_index("query", inplace=True)

        # Not sure if this statement is necessary. The regex
        # is already IGNORECASE when lowercase == "on"
        if self.lowercase == "on":
            df.index = df.index.str.lower()

        # Multiple list.append
        subframes.append(df.filter(pattern, axis=0))

# But a single pd.concat
self.datafr = pd.concat([self.datafr] + subframes)

【讨论】:

  • 感谢您的回答!我将很快尝试,然后我会留下反馈。 :)
  • Getting TypeError: 're.Pattern' object is not iterable in the .append(df.filter(pattern, axis=0)) 看起来列表不喜欢它
  • 不,我只是个笨蛋。忘记了附件中的 df.filter(REGEX=pattern, axis=0)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 2020-08-24
  • 2021-05-28
  • 2013-06-06
  • 2017-06-12
相关资源
最近更新 更多