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