Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按每6小时对数据帧进行分组并生成新列_Python_Pandas_Dataframe_Group By - Fatal编程技术网

Python 按每6小时对数据帧进行分组并生成新列

Python 按每6小时对数据帧进行分组并生成新列,python,pandas,dataframe,group-by,Python,Pandas,Dataframe,Group By,我有这个数据帧(类型可以是1或2): 我想按六个小时对数据进行分组,在进行分组时,我想将类型保持为: 1(如果在6小时内只有1个) 2(如果在6小时内只有2个)或 3(如果在6小时内同时有1和2) 以下是我的代码: df = df.groupby(['user_id', pd.TimeGrouper(freq=(6,'H'))]).mean() 产生: user_id | timestamp | type 1 | 2015-5-5 12:00 | 4 但是,我想得到

我有这个数据帧(类型可以是1或2):

我想按六个小时对数据进行分组,在进行分组时,我想将
类型
保持为:

  • 1
    (如果在6小时内只有1个)
  • 2
    (如果在6小时内只有2个)或
  • 3
    (如果在6小时内同时有1和2)
以下是我的代码:

df = df.groupby(['user_id', pd.TimeGrouper(freq=(6,'H'))]).mean()
产生:

user_id | timestamp      | type
1       | 2015-5-5 12:00 | 4
但是,我想得到
3
而不是4。我想知道如何替换我的
groupby
代码中的
mean()

In [54]: df.groupby(['user_id', pd.Grouper(key='timestamp', freq='6H')]) \
           .agg({'type':lambda x: x.unique().sum()})
Out[54]:
                             type
user_id timestamp
1       2015-05-05 12:00:00     3
PS它只适用于给定类型:(
1
2
),因为它们的总和是
3

另一个数据集:

In [56]: df
Out[56]:
   user_id           timestamp  type
0        1 2015-05-05 12:30:00     1
1        1 2015-05-05 14:00:00     1
2        1 2015-05-05 15:00:00     1
3        1 2015-05-05 20:00:00     1

In [57]: df.groupby(['user_id', pd.Grouper(key='timestamp', freq='6H')]).agg({'type':lambda x: x.unique().sum()})
Out[57]:
                             type
user_id timestamp
1       2015-05-05 12:00:00     1
        2015-05-05 18:00:00     1

好极了非常感谢。
In [56]: df
Out[56]:
   user_id           timestamp  type
0        1 2015-05-05 12:30:00     1
1        1 2015-05-05 14:00:00     1
2        1 2015-05-05 15:00:00     1
3        1 2015-05-05 20:00:00     1

In [57]: df.groupby(['user_id', pd.Grouper(key='timestamp', freq='6H')]).agg({'type':lambda x: x.unique().sum()})
Out[57]:
                             type
user_id timestamp
1       2015-05-05 12:00:00     1
        2015-05-05 18:00:00     1