通过ID和时间创建索引-熊猫

时间:2019-08-27 14:13:00

标签: pandas

我有带有ID和时间(日期和时间)的数据框。 我想按ID(已排序)和时间(已排序)对数据进行索引,其中日期和时间是分开的。 另外,要创建变量“ Weekend”,使其在周末(周六或周日)为1,否则为0。

数据帧演示:

ID  Date_n_time             X
1   08/27/2019 08:40:04     2
3   07/27/2019 08:40:04     1
1   08/27/2019 09:40:04     7
2   07/27/2019 08:50:00     3
3   07/29/2019 08:40:04     4
1   08/28/2019 07:40:03     5
3   07/29/2019 08:41:05     6

预期结果:

ID  Date        Time        X   Weekend
1   08/27/2019  08:40:04    2   0
                09:40:04    7   0
    08/28/2019  07:40:03    5   0
2   07/27/2019  08:50:00    3   1
3   07/27/2019  08:40:04    1   1
    07/29/2019  08:40:04    4   0
                08:41:05    6   0

2 个答案:

答案 0 :(得分:1)

这只是几次dt查找和排序。要查找周末,只需使用.dt.weekday和一些数学运算即可确定它是星期六还是星期日。


s = df['Date_n_time'].dt

d = dict(
    Date=s.date,
    Time=s.time,
    Weekend=(s.weekday // 5),
)

df.drop('Date_n_time', 1).assign(**d).set_index(['ID', 'Date', 'Time']).sort_index()

                        X  Weekend
ID Date       Time
1  2019-08-27 08:40:04  2        0
              09:40:04  7        0
   2019-08-28 07:40:03  5        0
2  2019-07-27 08:50:00  3        1
3  2019-07-27 08:40:04  1        1
   2019-07-29 08:40:04  4        0
              08:41:05  6        0

答案 1 :(得分:0)

如果尚未将列日期datetime数据类型转换为

df['Date_n_time'] = pd.to_datetime(df['Date_n_time'])

然后,您可以使用此处记录的Timestamp类的成员函数:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.html

您可能需要

df['Date'] = df['Date_n_time'].dt.date()
df['X'] = df['Date_n_time'].dt.weekday

,另外两个则需要您自己查找;)如果没有可用的函数,您可以随时使用strftime

指定自己的格式