Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.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 将groupby系列与dataframe合并_Python_Pandas - Fatal编程技术网

Python 将groupby系列与dataframe合并

Python 将groupby系列与dataframe合并,python,pandas,Python,Pandas,您好,我有一个groupby系列,我想与一个数据帧合并,以便在数据帧中根据groupby值而不是零替换产品和时间列。知道怎么做吗?下面是系列和数据帧示例 原始groupby系列 Product time Product1 2017-01-14 00:45:00 1 2017-01-14 12:30:00 3 Product2 2017-01-14 00:45:00 7

您好,我有一个
groupby
系列,我想与一个数据帧合并,以便在数据帧中根据
groupby
值而不是零替换产品和时间列。知道怎么做吗?下面是系列和数据帧示例

原始
groupby
系列

Product       time           
Product1      2017-01-14 00:45:00       1
              2017-01-14 12:30:00       3
Product2      2017-01-14 00:45:00       7
              2017-01-14 12:30:00       3
原始数据帧

time                   Product1 Product2    
2017-01-14 12:30:00      0       0
2017-01-14 00:45:00      0       0
我想把这两者结合起来成为

time                   Product1 Product2    
2017-01-14 12:30:00      3       3
2017-01-14 00:45:00      1       7

您应该首先取消堆叠序列(我在这里称之为
s
):

其中:

Product              Product1  Product2
time                                   
2017-01-14 00:45:00         1         7
2017-01-14 12:30:00         3         3
离你的要求不远

如果您希望尊重原始数据帧的顺序和列名,则此一行程序将执行以下任务:

df.merge(s.rename(None).unstack(0),
         left_on='time', right_index=True, suffixes=('_x', ''))[df.columns]
按预期给予:

                  time  Product1  Product2
0  2017-01-14 12:30:00         3         3
1  2017-01-14 00:45:00         1         7

如果您的groupby对象名为
grouped
,这是如何工作的<代码>分组。取消堆栈(0)谢谢,但与取消堆栈合并时,它不会更改原始数据帧series@goerge:如果要更改数据帧,只需使用
df=df.merge(…)
                  time  Product1  Product2
0  2017-01-14 12:30:00         3         3
1  2017-01-14 00:45:00         1         7