繁体   English   中英

尝试使用条件逻辑针对两个现有日期列在 DataFrame 中创建新列时出现 Python 类型错误

[英]Python Type Error when trying to create new column in DataFrame using conditional logic against two existing date columns

下面是我的数据框 我正在尝试针对两个现有日期列使用条件逻辑创建一个新列(Planned_Current_Month):

数据帧示例

我尝试使用以下Python代码(使用PandasNumpy )来执行此操作:

__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)

我收到以下错误

类型错误:无法使用 dtyped [float64] 数组和 [bool] 类型的标量执行“rand_”

它在抱怨什么? 是否有更好、更有效的方法来创建此列? 我对 Python/Pandas/Numpy 比较陌生,因此将不胜感激帮助、指导和提示。

示例中使用 August 作为当前月份。

根据要求添加数据集:

+-----------+-----------+-----------------------+
|   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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM