gpt4 book ai didi

python - 检查日期是在 Pandas 的上半月还是下半月

转载 作者:行者123 更新时间:2023-12-03 19:02:46 26 4
gpt4 key购买 nike

我有一个由日期列组成的数据框,但日期列是字符串。
如何检查日期是在上半月还是下半月并添加另一列与开票日期
例如
如果日期是 08-10-2020(格式是 dd-mm-yyyy),那么 billing date 列将包含同月的 16 日,如果日期在 17-31 之间,则计费日期将包含下个月的第一天
数据:

print(df['dispatch_date'].head())

0 01-10-2020
1 07-10-2020
2 17-10-2020
3 16-10-2020
4 09-10-2020
Name: dispatch_date, dtype: object
示例输出:
                 billing date
0 01-10-2020 16-10-2020
1 07-10-2020 16-10-2020
2 17-10-2020 01-11-2020
3 16-10-2020 01-11-2020
4 09-10-2020 16-10-2020

最佳答案

你可以使用 apply 来做到这一点,如下所示 -

import pandas as pd
import datetime as dt

dates = ['01-10-2020', '07-10-2020', '17-10-2020', '15-12-2020', '19-12-2020']
df = pd.DataFrame(data=dates, columns=['dates'])

# if the billing data can still be string going ahead
print(df.dates.apply(lambda x: '16'+x[2:] if int(x[:2]) < 16 else '01-'+str(int(x[3:5])+1)+x[5:] if int(x[3:5]) != 12 else '01-'+'01-'+str(int(x[6:])+1)))
df['billing_date'] = df.dates.apply(lambda x: '16'+x[2:] if int(x[:2]) < 16 else '01-'+str(int(x[3:5])+1)+x[5:] if int(x[3:5]) != 12 else '01-'+'01-'+str(int(x[6:])+1))

# if billing date series is needed as a datetime object
print(df.dates.apply(lambda x: dt.date(int(x[-4:]), int(x[3:5]), 16) if int(x[:2]) < 16 else dt.date(int(x[-4:]), int(x[3:5])+1, 1) if int(x[3:5]) != 12 else dt.date(int(x[-4:])+1, 1, 1)))
df['billing_date'] = df.dates.apply(lambda x: dt.date(int(x[-4:]), int(x[3:5]), 16) if int(x[:2]) < 16 else dt.date(int(x[-4:]), int(x[3:5])+1, 1) if int(x[3:5]) != 12 else dt.date(int(x[-4:])+1, 1, 1))
输出
0    16-10-2020
1 16-10-2020
2 01-11-2020
3 16-12-2020
4 01-01-2021
Name: dates, dtype: object

0 2020-10-16
1 2020-10-16
2 2020-11-01
3 2020-12-16
4 2021-01-01
Name: dates, dtype: object
编辑:代码处理 12 月可能出现的边缘情况

关于python - 检查日期是在 Pandas 的上半月还是下半月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64292622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com