温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Creating columns in df with day and hour of week based on value

python - 根据值在df中创建带有星期几和星期几的列

发布于 2020-03-27 15:51:54

我想基于包含数值的列创建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')

感谢您的光临!

查看更多

查看更多

提问者
Chris90
被浏览
22
jezrael 2020-01-31 16:44

我认为唯一值不是必需的,您可以将dt.strftime2列用于replace带有NaT值的2列

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