繁体   English   中英

使用多级索引将总行添加到 dataframe

[英]Add total row to dataframe with multi level index

考虑以下具有多级索引的 dataframe:

arrays = [np.array(['bar', 'bar', 'baz']),
          np.array(['one', 'two', 'one'])]

df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), 
                   columns=['a', 'b', 'c'],
                   index=arrays)

我要做的就是在底部添加一个“总计”行(12、15、18 将是这里的预期值)。 似乎我需要计算总数,然后将 append 计算到 dataframe,但在保留多级索引(我想做)的同时,我无法让它工作。 提前致谢!

这不会保留您的多级索引,但它会 append 一个名为“total”的新行包含列总和:

import pandas as pd
import numpy as np

arrays = [np.array(['bar', 'bar', 'baz']),
          np.array(['one', 'two', 'one'])]

df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), 
                   columns=['a', 'b', 'c'],
                   index=arrays)

df.append(df.sum().rename('total')).assign(total=lambda d: d.sum(1))

我想到了。 感谢您的回复。 这些加上更多关于 Python 中的索引的教育让我得到了一些有用的东西。

# Create df of totals
df2 = pd.DataFrame(df.sum())
# Transpose df
df2 = df2.T
# Reset index
df2 = df2.reset_index()
# Add additional column so the columns of df2 match the columns of df
df2['Index'] = "zTotal"
# Set indices to match df indices
df2 = df2.set_index(['index', 'Index'])
# Concat df and df2
df3 = pd.concat([df, df2])
# Sort in desired order
df3 = df3.sort_index(ascending=[False,True])

暂无
暂无

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

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