Python数据帧中列的子集的分组依据和均值

时间:2018-09-09 03:54:20

标签: python python-3.x pandas dataframe pandas-groupby

如果我有这两栏:

dat=[['yes','dog', 20,4,60,400],['yes','dog', 20,4,60,300],['yes','cat', 20,10,10,float('nan')]]
df_dat= pd.DataFrame(dat,columns = ["Time","animal", "val", "val2", "val3", "val4"])

我想获得一个使用“时间”和“动物”分组的数据框。然后,它采用其他列的组合方式。一个子集是[“ val”,“ val3”]和[“ val2”,“ val4”]。

基本上,某些东西可以利用df_dat.groupby([“ Time”,“ animal”])。mean()的值列子集的结果

我正在寻找的输出看起来像(但采用数据帧格式):

[Index , 'val'/'val3','val2/val4'] 
[('yes','dog'),40,177]
[('yes','cat'),15,10]

2 个答案:

答案 0 :(得分:1)

我相信您需要

ndf = df_dat.groupby(['Time', 'animal']).mean()
ndf['v1v3'], ndf['v2v4'] = ndf[['val', 'val3']].mean(1), ndf[['val2', 'val4']].mean(1)

输出

                val val2    val3    val4    v1v3    v2v4
Time    animal                      
yes     cat     20  10     10       NaN     15.0    10.0
        dog     20  4      60      350.0    40.0    177.0

当然可以选择均值列

ndf[['v1v3', 'v2v4']]

                v1v3    v2v4
Time    animal      
yes     cat     15.0    10.0
        dog     40.0    177.0

答案 1 :(得分:1)

设置

df = df_dat.groupby(['Time', 'animal']).mean()
subsets = [["val","val3"], ["val2","val4"]]

使用字典理解和 assign

df.assign(**{'/'.join(cols): df[cols].mean(1) for cols in subsets})

             val  val2  val3   val4  val/val3  val2/val4
Time animal
yes  cat      20    10    10    NaN      15.0       10.0
     dog      20     4    60  350.0      40.0      177.0

如果您只想要子集列:

pd.DataFrame({'/'.join(cols): df[cols].mean(1) for cols in subsets})

             val/val3  val2/val4
Time animal
yes  cat         15.0       10.0
     dog         40.0      177.0