附加两个多索引 pandas 数据帧
Append two multiindexed pandas dataframes
你能帮忙附加两个多索引 pandas 数据帧吗?尝试将 df_future 附加到 df_current。 COMPANY 和 DATE 是索引。
df_current
VALUE
COMPANY DATE
7/27/2015 1
A 7/28/2015 2
7/29/2015 3
7/30/2015 4
7/27/2015 11
B 7/28/2015 12
7/29/2015 13
7/30/2015 14
df_future
VALUE
COMPANY DATE
A 8/1/2015 5
8/2/2015 6
B 8/1/2015 15
8/2/2015 16
基于这些dfs,想看..
df_current_and_future
VALUE
COMPANY DATE
7/27/2015 1
7/28/2015 2
A 7/29/2015 3
7/30/2015 4
8/1/2015 5
8/2/2015 6
7/27/2015 11
7/28/2015 12
B 7/29/2015 13
7/30/2015 14
8/1/2015 15
8/2/2015 16
使用concat
连接两个DataFrame,sort_index
对第一个索引级别重新排序:
In [167]: pd.concat([df_current, df_future]).sort_index()
Out[167]:
VALUE
COMPANY DATE
A 7/27/2015 1
7/27/2015 11
7/28/2015 2
7/29/2015 3
7/30/2015 4
8/1/2015 5
8/2/2015 6
B 7/28/2015 12
7/29/2015 13
7/30/2015 14
8/1/2015 15
8/2/2015 16
注意:我原来的答案使用 sortlevel
,现在已弃用。作为 ,请改用 sort_index
。
在 pandas 中追加称为连接。并用 the pd.concat
function.
完成
无论您是否有多重索引,concat
函数都有效
df = pd.concat([df_current, future])
VALUE
COMPANY DATE
A 7/27/2015 1
7/28/2015 2
7/29/2015 3
7/30/2015 4
7/27/2015 11
B 7/28/2015 12
7/29/2015 13
7/30/2015 14
A 8/1/2015 5
8/2/2015 6
B 8/1/2015 15
8/2/2015 16
如果排序有问题,只需使用:
df.sort_index()
VALUE
COMPANY DATE
A 7/27/2015 1
7/27/2015 11
7/28/2015 2
7/29/2015 3
7/30/2015 4
8/1/2015 5
8/2/2015 6
B 7/28/2015 12
7/29/2015 13
7/30/2015 14
8/1/2015 15
8/2/2015 16
你能帮忙附加两个多索引 pandas 数据帧吗?尝试将 df_future 附加到 df_current。 COMPANY 和 DATE 是索引。
df_current
VALUE
COMPANY DATE
7/27/2015 1
A 7/28/2015 2
7/29/2015 3
7/30/2015 4
7/27/2015 11
B 7/28/2015 12
7/29/2015 13
7/30/2015 14
df_future
VALUE
COMPANY DATE
A 8/1/2015 5
8/2/2015 6
B 8/1/2015 15
8/2/2015 16
基于这些dfs,想看..
df_current_and_future
VALUE
COMPANY DATE
7/27/2015 1
7/28/2015 2
A 7/29/2015 3
7/30/2015 4
8/1/2015 5
8/2/2015 6
7/27/2015 11
7/28/2015 12
B 7/29/2015 13
7/30/2015 14
8/1/2015 15
8/2/2015 16
使用concat
连接两个DataFrame,sort_index
对第一个索引级别重新排序:
In [167]: pd.concat([df_current, df_future]).sort_index()
Out[167]:
VALUE
COMPANY DATE
A 7/27/2015 1
7/27/2015 11
7/28/2015 2
7/29/2015 3
7/30/2015 4
8/1/2015 5
8/2/2015 6
B 7/28/2015 12
7/29/2015 13
7/30/2015 14
8/1/2015 15
8/2/2015 16
注意:我原来的答案使用 sortlevel
,现在已弃用。作为 sort_index
。
在 pandas 中追加称为连接。并用 the pd.concat
function.
无论您是否有多重索引,concat
函数都有效
df = pd.concat([df_current, future])
VALUE
COMPANY DATE
A 7/27/2015 1
7/28/2015 2
7/29/2015 3
7/30/2015 4
7/27/2015 11
B 7/28/2015 12
7/29/2015 13
7/30/2015 14
A 8/1/2015 5
8/2/2015 6
B 8/1/2015 15
8/2/2015 16
如果排序有问题,只需使用:
df.sort_index()
VALUE
COMPANY DATE
A 7/27/2015 1
7/27/2015 11
7/28/2015 2
7/29/2015 3
7/30/2015 4
8/1/2015 5
8/2/2015 6
B 7/28/2015 12
7/29/2015 13
7/30/2015 14
8/1/2015 15
8/2/2015 16