Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.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 将数据帧格式化为等长时间序列格式_Python_Pandas_Outer Join - Fatal编程技术网

Python 将数据帧格式化为等长时间序列格式

Python 将数据帧格式化为等长时间序列格式,python,pandas,outer-join,Python,Pandas,Outer Join,我有一个数据帧 time. item. value1. value2 ----------------------------------- 1 1 3 4 2 1 2 5 1 2 3 5 3 2 2 1 2 3 3 6 3 3 2

我有一个数据帧

time.   item.   value1.   value2
-----------------------------------
1       1       3           4
2       1       2           5
1       2       3           5
3       2       2           1
2       3       3           6
3       3       2           5
我想把它转换成以下内容

time.   item.   value1.   value2
-----------------------------------
1       1       3           4
2       1       2           5
3       1       nan         nan
1       2       3           5
2       2       nan         nan
3       2       2           1
1       3       nan         nan
2       3       3           6
3       3       2           5
其中,所有项目的时间范围相同,如果不在原始数据帧中,则值1和值2为NaN。我用外接做了一些试验,但没有成功

有没有一种简单的方法呢?

您可以将时间、项目设置为索引,然后与一起使用

您可以将时间、项目设置为索引,然后与一起使用


您提供的输出与要求不匹配,例如item=2,time=2不在原始datframe中,因此输出中应为NaN。@Ch3ster取消删除您的解决方案,我认为它是正确的。@Ch3ster有一个解决方案。df.set_index['time.','item.].reindexpd.MultiIndex.from_product[df['time.].unique,df['item.].unique],name=['time.','item.].reset_index@ShubhamSharma我没有收到你给我贴标签的通知,我没有看到这个问题被编辑过。取消删除。@ScottBoston我没有收到你标记我的通知。感谢您抽出时间并将其发布在评论中。现在取消删除。您提供的输出与要求不匹配,例如item=2,time=2在原始datframe中不存在,因此输出中应该是NaN。@Ch3ster取消删除您的解决方案,我认为是正确的。@Ch3ster有一个解决方案。df.set_index['time.','item.].reindexpd.MultiIndex.from_product[df['time.].unique,df['item.].unique],name=['time.','item.].reset_index@ShubhamSharma我没有收到你给我贴标签的通知,我没有看到这个问题被编辑过。取消删除。@ScottBoston我没有收到你标记我的通知。感谢您抽出时间并将其发布在评论中。现在取消删除它。
time = df['time'].unique()
item = df['item'].unique()
idx = pd.MultiIndex.from_product([item, time],names=['item', 'time']).swaplevel(0,1)
df.set_index(['time', 'item']).reindex(idx).reset_index()

   time  item  value1  value2
0     1     1     3.0     4.0
1     2     1     2.0     5.0
2     3     1     NaN     NaN
3     1     2     3.0     5.0
4     2     2     NaN     NaN
5     3     2     2.0     1.0
6     1     3     NaN     NaN
7     2     3     3.0     6.0
8     3     3     2.0     5.0