V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
kayseen
V2EX  ›  Python

使用 Python 对列表中包含的多个列表的列求平均值

  •  1
     
  •   kayseen · 2019-09-20 19:30:05 +08:00 · 12655 次点击
    这是一个创建于 1673 天前的主题,其中的信息可能已经有所发展或是发生改变。
    数据结构是列表中嵌套列表的形式;
    比如:
    list = [[1,2,3,4],[3,4,5,6],[6,7,8,9]]
    对列表中的每一列求平均值,
    比如求 1,3,6 的平均值,4,6,8 的平均值,
    
    请教下这种用 pandas 可以实现吗?
    
    这种求平均值的话,在 python 中使用什么方法实现比较好?
    
    
    先忽略使用 for 循环吧...
    
    9 条回复    2019-09-27 17:09:06 +08:00
    ZRS
        1
    ZRS  
       2019-09-20 19:39:00 +08:00   ❤️ 1
    import numpy as np

    sample = np.array([[1,2,3,4],[3,4,5,6],[6,7,8,9]])

    res = sample.mean(axis=1)
    ZRS
        2
    ZRS  
       2019-09-20 19:46:27 +08:00
    列表生成式也可以做 不过可读性不太好
    sample = [[1,2,3,4],[3,4,5,6],[6,7,8,9]]

    res = [sum([i[ind] for i in sample])/len(sample) for ind in range(len(sample[0]))]
    zzzbkl
        3
    zzzbkl  
       2019-09-20 19:48:37 +08:00 via Android
    numpy 转置再求均值试试看
    tennc
        4
    tennc  
       2019-09-20 19:59:32 +08:00
    ```python
    import numpy as np

    lista = [[1,2,4,6],[2,5,6,7],[5,4,6,7],[6,8,2,9]]

    a = np.array(lista)

    print(np.mean(a,axis=1))

    [3.25 5. 5.5 6.25]

    ```
    kayseen
        5
    kayseen  
    OP
       2019-09-20 20:19:47 +08:00 via Android
    @tennc
    谢谢哈,刚刚试了下,感觉这个返回值有点奇怪啊,竟然没有逗号间隔。。。
    kayseen
        6
    kayseen  
    OP
       2019-09-20 20:20:32 +08:00 via Android
    @zzzbkl
    @ZRS
    谢谢哈,用 numpy 实现了
    SlipStupig
        7
    SlipStupig  
       2019-09-20 20:44:00 +08:00
    @ZRS python 有统计库

    ```python
    >>> import statistics
    ... p = [[1,2,3], [3,4,5]]
    >>> print([statistics.mean(g) for g in p])
    [2, 4]
    ```
    necomancer
        8
    necomancer  
       2019-09-22 16:45:04 +08:00
    In [1]: import numpy as np
    In [2]: a = np.ones(3)
    In [3]: a
    Out[3]: array([1., 1., 1.])

    In [4]: print(a)
    [1. 1. 1.]

    In [5]: a.__repr__()
    Out[5]: 'array([1., 1., 1.])'

    In [6]: a.__str__()
    Out[6]: '[1. 1. 1.]'
    lyang
        9
    lyang  
       2019-09-27 17:09:06 +08:00   ❤️ 1
    @ZRS
    可以这样
    ```
    [sum(i)/len(i) for i in zip(*list)]
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2273 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:57 · PVG 08:57 · LAX 17:57 · JFK 20:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.