python - 使用 pandas apply with dates and dates shifted

标签 python pandas dataframe

我有一个日期如下的 DataFrame:

               Daycount   
Date                                                                       
2020-05-01         0      
2020-06-01         0        
2020-07-01         0          
2020-08-01         0         
2020-09-01         0            

我正在尝试使用以下公式提取一天到下一天的天数:

def days360(start_date, end_date, method_eu=False):
        start_day = start_date.day
    start_month = start_date.month
    start_year = start_date.year
    end_day = end_date.day
    end_month = end_date.month
    end_year = end_date.year

    if start_day == 31 or (method_eu is False and start_month == 2 and (start_day == 29 or (start_day == 28 and calendar.isleap(start_year) is False))):
        start_day = 30

    if end_day == 31:
        if method_eu is False and start_day != 30:
            end_day = 1

            if end_month == 12:
                end_year += 1
                end_month = 1
            else:
                end_month += 1
        else:
            end_day = 30

    return end_day + end_month * 30 + end_year * 360 - start_day - start_month * 30 - start_year * 360

但是,我尝试使用如下的应用函数,但我得到以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

当只在 DataFrame 中传递一组值时,它起作用了,所以我的公式绝对正确。创建日期偏移的另一列,然后应用公式确实有效,但我正在寻找一种更简洁的方法。我不确定应用功能。我应该得到 30 天的所有天数。

hypo["Daycount"] = hypo.apply(lambda x: days360(x.index,x.index.shift(-1)))

目标输出应该如下表:

        Date  Daycount
0 2020-05-01      30.0
1 2020-06-01      30.0
2 2020-07-01      30.0
3 2020-08-01      30.0
4 2020-09-01      30.0

最佳答案

使用,pd.to_datetime将系列转换为日期时间系列,然后使用 Series.dt访问系列的日期时间属性,然后使用 Series.diff在组件 yearmonthday 上获得所需的结果:

df = df.reset_index()
dates = pd.to_datetime(df['Date'])
df['Daycount'] = (
    (dates.dt.year.diff() * 360 + dates.dt.month.diff() * 30 + dates.dt.day.diff()).fillna(0)
)

# print(df)
         Date  Daycount
0  2020-05-01       0.0
1  2020-06-01      30.0
2  2020-07-01      30.0
3  2020-08-01      30.0
4  2020-09-01      30.0

考虑另一个具有更复杂数据框的示例:

# Given dataframe
# print(df)
            Daycount
Date                
2020-05-01         0
2020-06-03         0
2020-07-01         0
2021-07-02         0
2022-08-03         0

# Desired result
# print(df)
         Date  Daycount
0  2020-05-01       0.0
1  2020-06-03      32.0
2  2020-07-01      28.0
3  2021-07-02     361.0
4  2022-08-03     391.0

关于python - 使用 pandas apply with dates and dates shifted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62405054/

相关文章:

python - 将相同的 Pandas 数据帧存储到数据库后不相等

python - 使用 dictConfig 的 Python 日志记录问题

python - 数据框到python中的文本文件

pandas - 如何使用 pandas 根据一行标识符对合并列进行分组?

python - 为什么我在 pandas 的 apply/assign 函数中得到一个系列?想要使用每个值来查找字典

Python 嵌套 'while' 循环未正确执行

python - 在列表 python 上应用正则表达式模式列表

Python、Pandas将Excel文件合并为1,文件名为A列

python - 从 pandas.DataFrame 的每一列中获取最大的值

Python:读取没有默认分隔符且包含数百万条记录的文件并将其放入数据框( Pandas )时的效率?