下面是我的数据帧;我正试图针对两个现有日期列使用条件逻辑创建一个新列(Planned_Current_Month(:
数据帧示例
我曾尝试在Python中使用以下代码(使用Pandas&Numpy(:
__current_month = pd.datetime.now().month
__current_year = pd.datetime.now().year
df['Planned_Current_Month'] =
np.where(df.Date1.dt.month == __current_month
& df.Date1.dt.year == __current_year
& (df.Date2.dt.month.isnull()
| (df.Date2.dt.month >= __current_month
& df.Date2.dt.year == __current_year)), 1, 0)
我收到下面的错误:
TypeError:无法使用dtyped[foat64]数组和[bool]类型的标量执行"rand_">
它在抱怨什么?有没有更好、更有效的方法来创建此列?我对Python/Pandas/Numbery还比较陌生,所以希望能提供帮助、指导和技巧。
示例中使用八月作为当前月份。
根据要求添加数据集:
+-----------+-----------+-----------------------+
| Date1 | Date2 | Planned_Current_Month |
+-----------+-----------+-----------------------+
| 10-Aug-20 | | 1 |
| 29-Feb-20 | | 0 |
| 16-Mar-20 | 20-Apr-20 | 0 |
| 07-Aug-20 | 06-Jul-20 | 0 |
| 28-Aug-20 | 18-Aug-20 | 1 |
| 22-Jul-20 | 05-Aug-20 | 0 |
+-----------+-----------+-----------------------+
我在python 3.7.7中用numpy 1.19.1和您的示例数据集尝试了您的代码,它正在工作。但是,您需要添加一些括号:
df = pd.DataFrame([["10-Aug-20",""],
["29-Feb-20",""],
["16-Mar-20","20-Apr-20"],
["07-Aug-20","06-Jul-20"],
["28-Aug-20","18-Aug-20"],
["22-Jul-20","05-Aug-20"]], columns = ["Date1","Date2"])
df["Date1"] = pd.to_datetime(df["Date1"])
df["Date2"] = pd.to_datetime(df["Date2"])
__current_month = 8
__current_year = 2020
df['Planned_Current_Month'] =
np.where((df.Date1.dt.month == __current_month)
& (df.Date1.dt.year == __current_year)
& ((df.Date2.dt.month.isnull() )
| ((df.Date2.dt.month >= __current_month)
& (df.Date2.dt.year == __current_year))), 1, 0)
输出:
Date1 Date2 Planned_Current_Month
0 2020-08-10 NaT 1
1 2020-02-29 NaT 0
2 2020-03-16 2020-04-20 0
3 2020-08-07 2020-07-06 0
4 2020-08-28 2020-08-18 1
5 2020-07-22 2020-08-05 0