如何计算列熊猫数据框中列表的平均值

我有数据看起来像这样

data={"col1":[ [(1,22),(1.5,20),(3,32),(2,21)],
              [(2,24),(2.5,22)],
      [(6,12),(1.3,18),(5,21)],
              [(4,25),(5,33),(7,21),(2,30)]],
"name":["A","B","C","F"]}
df=pd.DataFrame.from_dict(data)
print(df)

我想表示每行(列出)两个不同的 colls 中的第一个和第二个数字,因此对于第一个单元格,我将获得包含 (1+1.5+3+2)4 的新 coll 和一个具有 22 的 col +20+32+21/4

我做了类似的事情,但它的循环看起来很乱

for i in df["col1"]:
    mean_list = []
    for first_numb in i:
        mean_list.append(first_numb[0])

任何的想法?

回答

我们可以尝试exploding从爆炸列创建一个新的数据帧,然后计算meanlevel=0

e = df['col1'].explode()
df[['m1', 'm2']] = pd.DataFrame([*e], index=e.index).mean(level=0)

list理解的替代方法

df[['m1', 'm2']] = pd.DataFrame([[sum(t) / len(t) for t in zip(*l)]
                                 for l in df['col1']], index=df.index)

                                     col1 name     m1     m2
0  [(1, 22), (1.5, 20), (3, 32), (2, 21)]    A  1.875  23.75
1                    [(2, 24), (2.5, 22)]    B  2.250  23.00
2           [(6, 12), (1.3, 18), (5, 21)]    C  4.100  17.00
3    [(4, 25), (5, 33), (7, 21), (2, 30)]    F  4.500  27.25

性能检查

# Sample df with 40000 rows
df = pd.concat([df] * 10000, ignore_index=True)


%%timeit
e = df['col1'].explode()
pd.DataFrame([*e], index=e.index).mean(level=0)
# 107 ms ± 1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
pd.DataFrame([[sum(t) / len(t) for t in zip(*l)] for l in df['col1']], index=df.index)
# 50.5 ms ± 582 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)


以上是如何计算列熊猫数据框中列表的平均值的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>