【问题标题】:add a new column in multi index from the others在其他索引中添加一个新列
【发布时间】:2021-12-17 16:20:46
【问题描述】:
In [151]: df
Out[151]: 
first        bar                 baz           
second       one       two       one       two 
A              1       2          3         4
B              5       6          7         8

我的问题很简单:从这个df中,如何创建一个新的第三列,其中一列和两列的总和即得到:

In [151]: df
Out[151]: 
first        bar                         baz           
second       one       two    three     one       two   three
A             1       2          3.        3.       4.     7. 
B             5       6          11.       7.       8.     15.  

谢谢。

【问题讨论】:

  • 请以字典形式提供您的数据:df.to_dict()
  • {('bar', 'one'): {0: 1, 1: 5}, ('bar', 'two'): {0: 2, 1: 6}, ( 'baz', 'one'): {0: 3, 1: 7}, ('baz', 'two'): {0: 4, 1: 8}}

标签: python pandas multi-index


【解决方案1】:

一种方法是:

df1 = df.join(df.sum(level=0, axis=1))

返回:

(bar, one)  (bar, two)  (baz, one)  (baz, two)  bar  baz
0           1           2           3           4    3    7
1           5           6           7           8   11   15

你也可以添加这个:

columns = [('bar', 'one'), ('bar', 'two'), ('bar', 'three'), ('baz', 'one'), ('baz', 'two'), ('baz', 'three')]
df1.columns = pd.MultiIndex.from_tuples(columns)
print(df1.sort_index(level=0))

按照您要求的格式:

bar           baz          
  one two three one two three
0   1   2     3   4   3     7
1   5   6     7   8  11    15

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-22
    • 2017-10-06
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多