【问题标题】:How to convert a for loop into an apply method in Python如何在 Python 中将 for 循环转换为 apply 方法
【发布时间】:2019-02-02 15:53:23
【问题描述】:

我正在尝试将此 for 循环更改为应用方法,因为 iterrows/itertuples 都太慢了。我有一个相当大的数据集。这可能吗?

for index, row in df2.iterrows():
    startDateString = str(row['Date'].replace("/",""))
    endDateString = str(row['Date'].replace("/",""))
    zipcode = str(row['Zip'])
    #startDateString = str(startDate)
    #endDateString = str(endDate)
    print("zip: " + "%s" %zipcode + ", daterange: " + startDateString + " - " + endDateString )

【问题讨论】:

  • 这里的目标是什么,只是为了在屏幕上打印一些东西?
  • 我正在使用循环信息插入 API 调用。
  • .apply 不会比itertuples 快得多。一般来说,pandas 的文本处理速度很慢,但您可以尝试使用矢量化操作(尽管使用 str 数据,矢量化的优势并不大)

标签: python pandas for-loop apply


【解决方案1】:

为什么 startDate 和 endDate 是同一列?

str 调用是无用的,因为格式说明符会这样做。删除它们会导致:

for index, row in df2.iterrows():
    startDate = row['Date'].replace("/","")
    endDate = row['Date'].replace("/","")
    zipcode = row['Zip']
    print("zip: %s, daterange: %s - %s" % (zipcode, startDate, endDate))

【讨论】:

  • 对于这种情况 - 我正在使用这些值插入 API 调用,并且我需要相同的开始日期和结束日期。谢谢你,我将删除 str 调用。
【解决方案2】:

apply() 是 pandas 库中最慢的方法之一。你可以用 str 属性调用做同样的事情。 您不需要创建所有变量。

    df2['new_column'] = f"""zip: {df2.Zip}, daterange: {df2['Date'].str.replace("/","")} - {df2['Date'].str.replace("/","")}"""
    for x in df2.new_column:
         print(x)

希望这适用于您的数据。

【讨论】:

  • F弦?应该至少需要一个特定的 Python 版本。
  • 使用 Python 3.6,因为 f 字符串很棒,新的字典速度也很棒。
猜你喜欢
  • 2017-06-02
  • 1970-01-01
  • 2021-12-27
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多