繁体   English   中英

Pandas合并分层数据帧并维护层次结构

[英]Pandas merge hierarchical dataframes and maintain hierarchy

这个github问题描述了合并具有混合层次结构的数据帧,并给出了将层次结构扁平化为元组的解决方案。

df = pd.DataFrame([(1, 2, 3), (4, 5, 6)], columns=['a', 'b', 'c'])
new_df = df.groupby(['a']).agg({'b': [np.mean, np.sum]})
other_df = df = pd.DataFrame([(1, 2, 3), (7, 10, 6)], columns=['a', 'b', 'd'])
other_df.set_index('a', inplace=True)
print new_df
print other_df
p = pd.merge(new_df, other_df, left_index=True, right_index=True)
print p

输出:

      b     
   mean  sum
a           
1     2    2
4     5    5

    b  d
a       
1   2  3
7  10  6

   (b, mean)  (b, sum)  b  d
a                           
1          2         2  2  3

但是我想维护层次结构,结果如下:

       b        b  d
    mean  sum
x                           
y      .    .   .  .

我只是在这里制作了值点,因为它们在这种情况下并没有真正意义,但希望这个想法很明确......任何帮助都会感激不尽......

你在寻找这样的东西:

>>> other_to_tup = [(x, 'val') for x in other_df.columns]
>>> other_df.columns = pd.MultiIndex.from_tuples(other_to_tup)
>>> p = pd.merge(new_df, other_df, left_index=True, right_index=True)
>>> p
      b              d
   mean  sum  val  val
a
1     2    2    2    3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM