这是我的数据格式df
1.1 1.2 1.3 2.1 ... 5.1 6.1 6.2. 6.3.
sample_a 1 1 2 4 2 3 4 2
sample_b 2 3 3 1 1 3 1 2
sample_c 2 4 3 1 1 3 2 2
我希望通过提取第一个列名(即从1.1中取1,从2.1中取2,从6.1中取6)对df
进行分组,并按中间值聚合df
。
这是我想要的输出:
1 2 ... 5 6
sample_a 1 4 2 3
sample_b 3 1 1 2
sample_c 3 1 1 2
例如,对于第一个元素(sample_a,1),1.1、1.2和1.3的中位数是1。
这是我目前的代码。
df.columns = df.columns.str.extract('([\d])\.\d+',expand=False)
df.groupby(df.columns, axis=1).median(axis=1)
我不确定axis应该是0还是1,但不管是哪种方式,我都得到了KeyError: 'axis'
当我尝试下面的代码时,它工作得很好。
df.columns = df.columns.str.extract('([\d])\.\d+',expand=False)
df.groupby(df.columns,axis=1).sum()
为什么中位数不起作用?
发布于 2019-10-17 10:29:15
在groupby
上使用axis=1
df.groupby(df.columns.str[0], axis=1).median()
1 2 5 6
sample_a 1 4 2 3
sample_b 3 1 1 2
sample_c 3 1 1 2
https://stackoverflow.com/questions/58438678
复制相似问题