我试图基于包含数值的列创建2列。

  Value
    0
    4
    10
    24
    null
    49

Expected Output:
  Value           Day      Hour
    0           Sunday   12:00am
    4           Sunday   4:00am
    10          Sunday   10:00am
    24          Monday   12:00am
    null        No Day    No Time
    49          Tuesday   1:00am
    Continued.....


我正在尝试的代码:

    value = df.value.unique()
    Sunday_Starting_Point = pd.to_datetime('Sunday 2015')
    (Sunday_Starting_Point + pd.to_timedelta(Value, 'h')).dt.strftime('%A %I:%M%P')


感谢您的光临!

最佳答案

我认为没有必要使用唯一值,对于具有dt.strftime值的replace,您可以对2列使用2次NaT

Sunday_Starting_Point = pd.to_datetime('Sunday 2015')
x = pd.to_numeric(df.Value, errors='coerce')
s = Sunday_Starting_Point + pd.to_timedelta(x, unit='h')
df['Day'] = s.dt.strftime('%A').replace('NaT','No Day')
df['Hour'] = s.dt.strftime('%I:%M%p').replace('NaT','No Time')
print (df)
   Value      Day     Hour
0    0.0   Sunday  12:00AM
1    4.0   Sunday  04:00AM
2   10.0   Sunday  10:00AM
3   24.0   Monday  12:00AM
4    NaN   No Day  No Time
5   49.0  Tuesday  01:00AM

09-04 13:58