我正在尝试找出将平均值插入到多级索引Pandas数据帧中的最佳方法。
假设我有一个像这样的数据框:
我想要得到以下结果:
请注意,我知道可以使用
我能够得到我想要的结果,但我觉得自己做错了/可能有一个一行代码的方法可以在没有昂贵的Python迭代的情况下完成此操作。以下是我的示例代码:
这将导致:
这个会将一些组的顺序翻转,但大体上来说是我想要的。
假设我有一个像这样的数据框:
metric 1 metric 2
R P R P
foo a 0 1 2 3
b 4 5 6 7
bar a 8 9 10 11
b 12 13 14 15
我想要得到以下结果:
metric 1 metric 2
R P R P
foo a 0 1 2 3
b 4 5 6 7
AVG 2 3 4 5
bar a 8 9 10 11
b 12 13 14 15
AVG 10 11 12 13
请注意,我知道可以使用
df.mean(level=0)
将第0级别的组平均值作为单独的数据框获取。但这不是我想要的--我想将组平均值作为行插入回组中。我能够得到我想要的结果,但我觉得自己做错了/可能有一个一行代码的方法可以在没有昂贵的Python迭代的情况下完成此操作。以下是我的示例代码:
import numpy as np
import pandas as pd
data = np.arange(16).reshape(4,4)
row_index = [("foo", "a"), ("foo", "b"), ("bar", "a"), ("bar", "b")]
col_index = [("metric 1", "R"), ("metric 1", "P"), ("metric 2", "R"),
("metric 2", "P")]
col_multiindex = pd.MultiIndex.from_tuples(col_index)
df = pd.DataFrame(data, index=pd.MultiIndex.from_tuples(row_index),
columns=col_multiindex)
new_row_index = []
data = []
for name, group in df.groupby(level=0):
for index_tuple, row in group.iterrows():
new_row_index.append(index_tuple)
data.append(row.tolist())
new_row_index.append((name, "AVG"))
data.append(group.mean().tolist())
print pd.DataFrame(data,
index=pd.MultiIndex.from_tuples(new_row_index),
columns=col_multiindex)
这将导致:
metric 1 metric 2
R P R P
bar a 8 9 10 11
b 12 13 14 15
AVG 10 11 12 13
foo a 0 1 2 3
b 4 5 6 7
AVG 2 3 4 5
这个会将一些组的顺序翻转,但大体上来说是我想要的。
transform
方法。 - Paul H