我有一个具有多个行和列的pandas数据框,其中每个单元格都包含一个值列表。我想分别计算每一行的值平均值(在列表中)。
数据框如下所示:
l1 = [[1,2,4,3],[1,2,4,3], [1,2,4,3]]
l2 = [[8,2,6,4],[1,2,4,3],[1,2,4,3]]
l3 = [[1,2,4,9],[1,2,4,3],[1,2,4,3]]
df = pd.DataFrame([l1, l2, l3], columns=list('xyz'))
df:
x y z ...
x [1,2,4,3] [1,2,4,3] [1,2,4,3]
y [8,2,6,4] [1,2,4,3] [1,2,4,3]
z [1,2,4,9] [1,2,4,3] [1,2,4,3]
我想要这样的结果:
x y z MEAN
x [1,2,4,3] [1,2,4,3] [1,2,4,3] 2.50000
y [8,2,6,4] [1,2,4,3] [1,2,4,3] 3.33333
z [1,2,4,9] [1,2,4,3] [1,2,4,3] 3.00000
有什么建议吗?
答案 0 :(得分:5)
您可以将numpy.concatenate
的每行值展平为numpy数组,然后调用mean
:
df['MEAN'] = [np.concatenate(x).mean() for x in df.to_numpy()]
#for oldier pandas versions
#df['MEAN'] = [np.concatenate(x).mean() for x in df.values]
print (df)
x y z MEAN
x [1, 2, 4, 3] [1, 2, 4, 3] [1, 2, 4, 3] 2.500000
y [8, 2, 6, 4] [1, 2, 4, 3] [1, 2, 4, 3] 3.333333
z [1, 2, 4, 9] [1, 2, 4, 3] [1, 2, 4, 3] 3.000000