尝试在DataFrame中针对两个现有日期列使用条件逻辑创建新列时出现Python类型错误
下面是我的数据框;我正在尝试对两个现有的日期列使用条件逻辑创建一个新列(计划的当前月份): 我尝试使用下面的代码在Python中执行此操作(使用Pandas和Numpy): 我得到以下错误: TypeError:无法使用数据类型为[float64]的数组和类型为[bool]的标量执行“rand_u2;” 它在抱怨什么?有没有更好、更有效的方法来创建此专栏?我对Python/Pandas/Numpy比较陌生,希望您能提供帮助、指导和提示 在示例中,八月用作当前月份 按要求添加数据集:尝试在DataFrame中针对两个现有日期列使用条件逻辑创建新列时出现Python类型错误,python,pandas,numpy,dataframe,Python,Pandas,Numpy,Dataframe,下面是我的数据框;我正在尝试对两个现有的日期列使用条件逻辑创建一个新列(计划的当前月份): 我尝试使用下面的代码在Python中执行此操作(使用Pandas和Numpy): 我得到以下错误: TypeError:无法使用数据类型为[float64]的数组和类型为[bool]的标量执行“rand_u2;” 它在抱怨什么?有没有更好、更有效的方法来创建此专栏?我对Python/Pandas/Numpy比较陌生,希望您能提供帮助、指导和提示 在示例中,八月用作当前月份 按要求添加数据集: +----
+-----------+-----------+-----------------------+
| 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 |
+-----------+-----------+-----------------------+
我用Python3.7.7和Numpy1.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
能否将数据集添加为纯文本而不是图像?非常感谢您的帮助:)。如果有更好/更有效的方法,请告诉我。祝你一切顺利。
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