我有一只熊猫数据格式df
of shape (100, 10)
(100行,10 cols),我想从df
生成一个数据格式df_summary
,它:
(1, 4)
形状,列名为“col1”、“col2”、“col3”、“col4”mean
‘s of df
's 1 cols、2-4 cols (这3列的所有行的平均数)、5-8 cols和9-10 cols variance
s of df
s、2-4 cols、5-8 cols和9-10 colsh 215f 216/code>。
我做了我的研究,但仍然不知道如何有效地做到这一点。任何帮助都将不胜感激。
发布于 2020-12-04 12:34:33
以下是2种解决方案,第一种是列表中指定的范围,由stack
重塑,由Series.agg
通过pass到concat
进行聚合。
np.random.seed(2020)
df = pd.DataFrame(np.random.randint(10, size=(100, 10)))
L = [[0], range(2, 4), range(5, 8), range(8, 10)]
cols = ['col1', 'col2', 'col3', 'col4']
out = pd.concat([df[x].stack().agg(['mean','var']) for x in L], axis=1, keys=cols)
print (out)
col1 col2 col3 col4
mean 4.120000 4.270000 4.580000 4.405000
var 8.793535 8.298593 7.963478 9.418065
或者对于范围使用cut
,由DataFrame.melt
取消枢轴,然后用var
聚合mean
。
cols = ['col1', 'col2', 'col3', 'col4']
df.columns = pd.cut(df.columns, [0,1,5,8,11], labels=cols, include_lowest=True, right=False)
df = df.melt().groupby('variable')['value'].agg(['mean','var']).T
print (df)
variable col1 col2 col3 col4
mean 4.120000 4.482500 4.580000 4.405000
var 8.793535 8.611222 7.963478 9.418065
https://stackoverflow.com/questions/65143301
复制相似问题