【问题标题】:New column value based on two columns in df and possible NaN Value基于 df 中的两列和可能的 NaN 值的新列值
【发布时间】:2019-09-04 21:20:26
【问题描述】:

我正在尝试根据以下两列时间戳的条件创建一个新列,

def time_delta(df):
if df['a_time'] > df['b_time']:
    res = 'Early'
else:
    res = 'Late'
return res 

df['new_col'] = np.where(df['a_time'] > df['b_time'], 'Early', 'Late')

但是 a_time 列有时具有 NaN 值,如果 a_time 为 NaN,我希望新列中的结果或值也为 NaN,我该如何执行此操作或调整我为此提供的内容?

期望的输出

     time_a           |         time_b          | new_column
2019-08-19 22:25:26.133   2019-08-19 23:00:00.000    Before_b
       NaN                2019-08-19 22:00:00.000     NaN
2019-08-19 23:00:00.000   2019-08-19 20:00:00.000    After_b

谢谢!

【问题讨论】:

  • 您好,请提供minimal reproducible example
  • @Yuca 谢谢!,我添加了所需的输出
  • df['new_col'] = np.where(df['a_time'] > df['b_time'], 'Early', 'Late').mask(df['time_a'].isna()) ?

标签: python python-3.x pandas data-science


【解决方案1】:

您可以使用numpy.isnat 来修复它。

df['new_col'] = np.where(df['a_time'] > df['b_time'], 'Early', 'Late')

df.loc[(np.isnat(df['a_time']) | np.isnat(df['b_time'])), 'new_col'] = np.NaN

【讨论】:

  • 感谢您的回复,所以运行我已经运行的代码然后运行您在下面的下一行中显示的代码?
【解决方案2】:

您可以使用np.select 进行操作

df['new_column'] = np.select([df.isna().any(1), df.time_a > df.time_b], [pd.NaT, 'Early'], 'Late')

Out[923]:
                   time_a              time_b new_column
0 2019-08-19 22:25:26.133 2019-08-19 23:00:00  Late
1 NaT                     2019-08-19 22:00:00  NaT
2 2019-08-19 23:00:00.000 2019-08-19 20:00:00  Early

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多