【问题标题】:Vectorising pandas dataframe apply function for user defined function in python向量化pandas数据框应用函数用于python中的用户定义函数
【发布时间】:2018-10-16 11:51:37
【问题描述】:

我想计算指定日期的月份周数。对于计算月份中的星期,我目前使用用户定义的函数。

输入数据框:

输出数据框:

这是我尝试过的:

from math import ceil
def week_of_month(dt):
    """ 
       Returns the week of the month for the specified date.
    """

    first_day = dt.replace(day=1)

    dom = dt.day
    adjusted_dom = dom + first_day.weekday()

    return int(ceil(adjusted_dom/7.0))

之后,

import pandas as pd

df = pd.read_csv("input_dataframe.csv")
df.date = pd.to_datetime(df.date)
df['year_of_date'] = df.date.dt.year
df['month_of_date'] = df.date.dt.month
df['day_of_date'] = df.date.dt.day


wom = pd.Series()

# worker function for creating week of month series
def convert_date(t):
    global wom
    wom = wom.append(pd.Series(week_of_month(datetime.datetime(t[0],t[1],t[2]))), ignore_index = True)

# calling worker function for each row of dataframe
_ = df[['year_of_date','month_of_date','day_of_date']].apply(convert_date, axis = 1)

# adding new computed column to dataframe
df['week_of_month'] = wom
# here this updated dataframe should look like Output data frame.

它的作用是对每一行数据框使用给定的函数计算每月的一周。随着数据框增长到更多行,它会使计算变慢。因为目前我有超过 10M+ 行。

我正在寻找一种更快的方法来执行此操作。我可以对此代码进行哪些更改以对所有行进行矢量化此操作?

提前致谢。

编辑:阅读答案后对我有用的代码如下,

first_day_of_month = pd.to_datetime(df.date.values.astype('datetime64[M]'))
df['week_of_month'] = np.ceil((df.date.dt.day + first_day_of_month.weekday) / 7.0).astype(int)

【问题讨论】:

    标签: python pandas date vectorization apply


    【解决方案1】:

    week_of_month 方法可以向量化。最好不要转换为 datetime 对象,而是使用 pandas only 方法。

    first_day_of_month = df.date.to_period("M").to_timestamp()
    df["week_of_month"] = np.ceil((data.day + first_day_of_month.weekday) / 7.0).astype(int)
    

    【讨论】:

    • 谢谢!您的解决方案给了我提示,我按照您的建议实施了,它奏效了! first_day_of_month = pd.to_datetime(data.date.values.astype('datetime64[M]')) data['week_of_month'] = np.ceil((data.date.dt.day + first_day_of_month.weekday) / 7.0).astype(int)
    【解决方案2】:

    直接开始,甚至无需进入您的代码并提及 X/Y 问题等:
    尝试获取唯一日期的列表,我敢肯定,在 10M 行中,您有不止一个是重复的。

    步骤:

    1. 创建第二个 df,其中仅包含您需要的列而不包含 重复(drop_duplicates)
    2. 在小型数据框上运行您的函数
    3. 合并大小dfs
    4. (可选)放下小号

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 2018-11-18
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      • 2020-08-03
      • 2016-06-04
      相关资源
      最近更新 更多