我有一个数据框df
first bar baz
second one two one two
A 0.487880 -0.487661 -1.030176 0.100813
B 0.267913 1.918923 0.132791 0.178503
C 1.550526 -0.312235 -1.177689 -0.081596
我想添加平均值列,然后将平均值移到最前面
df['Average'] = df.mean(level='second', axis='columns') #ERROR HERE
cols = df.columns.tolist()
df = df[[cols[-1]] + cols[:-1]]
我得到了错误:
ValueError: Wrong number of items passed 2, placement implies 1
也许我可以一次平均地将每一列df['Average', 'One'] = ...
添加一次,但这似乎很愚蠢,尤其是当现实生活中的索引更加复杂时。
编辑:(Frame Generation)
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
答案 0 :(得分:2)
我不确定您的目标输出。像这样吗?
df2 = df.mean(level='second', axis='columns')
df2.columns = pd.MultiIndex.from_tuples([('mean', col) for col in df2])
>>> df2
mean
one two
A -0.271148 -0.193424
B 0.200352 1.048713
C 0.186419 -0.196915
>>> pd.concat([df2, df], axis=1)
mean bar baz
one two one two one two
A -0.271148 -0.193424 0.487880 -0.487661 -1.030176 0.100813
B 0.200352 1.048713 0.267913 1.918923 0.132791 0.178503
C 0.186419 -0.196915 1.550526 -0.312235 -1.177689 -0.081596
由于mean
操作会导致一个数据帧(在这种情况下为两列),因此会出现错误。然后,您尝试将此结果分配到原始数据帧的一栏中。
答案 1 :(得分:1)
pandas.concat
df.join(pd.concat([df.mean(level='second', axis='columns')], axis=1, keys=['Average']))
first bar baz Average
second one two one two one two
A 0.255301 0.286846 1.027024 -0.060594 0.641162 0.113126
B -0.608509 -2.291201 0.675753 -0.416156 0.033622 -1.353679
C 2.714254 -1.330621 -0.099545 0.616833 1.307354 -0.356894
stack
/ unstack
不一定高效,但是很整齐
df.stack().assign(Average=df.mean(level='second', axis='columns').stack()).unstack()
first bar baz Average
second one two one two one two
A 0.255301 0.286846 1.027024 -0.060594 0.641162 0.113126
B -0.608509 -2.291201 0.675753 -0.416156 0.033622 -1.353679
C 2.714254 -1.330621 -0.099545 0.616833 1.307354 -0.356894