【发布时间】:2017-05-17 04:53:50
【问题描述】:
我正在尝试向具有多索引的 Pandas GroupBy DataFrame 添加一列。该列是分组后公共键的最大值和平均值之间的差异。
这是输入数据帧:
Main Reads Test Subgroup
0 1 5 54 1
1 2 2 55 1
2 1 10 56 2
3 2 20 57 3
4 1 7 58 3
代码如下:
import numpy as np
import pandas as pd
df = pd.DataFrame({'Main': [1, 2, 1, 2, 1], 'Reads': [5, 2, 10, 20, 7],\
'Test':range(54,59), 'Subgroup':[1,1,2,3,3]})
result = df.groupby(['Main','Subgroup']).agg({'Reads':[np.max,np.mean]})
这是result在计算diff之前的变量:
Reads
amax mean
Main Subgroup
1 1 5 5
2 10 10
3 7 7
2 1 2 2
3 20 20
接下来,我计算diff 列:
result['Reads']['diff'] = result['Reads']['amax'] - result['Reads']['mean']
但这里是输出:
/home/userd/test.py:9: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/
...stable/indexing.html#indexing-view-versus-copy
...result['Reads']['diff'] = result['Reads']['amax'] - result['Reads']['mean']
我希望diff 列与amax 和mean 处于同一级别。
有没有办法将一列添加到 Pandas 中多索引 GroupBy() 对象的最内(底部)列索引?
【问题讨论】:
标签: python pandas dataframe group-by