Convert Average of Python List Values to Another List(将 Python 列表值的平均值转换为另一个列表)
问题描述
我有这样的清单.
list = [["Joe", 5, 7], ["Joe", 6, 9], ["Mike", 1,4], ["Joe", 7,4], [迈克",5,7]]
如何将此列表转换为这样的列表:
list2 = [["Joe", 6.00, 6.66], ["Mike", 3.00, 5.50]]
list2[0][1] 和 list2[1][1] 是第一个列表中特定人的平均值(6.00 来自 (list[0][1]+list[1][1]+list[3][1])/3
我应该像这样使用迭代:
for i in range(len(list)):...
或者..类似的东西?因为我是从 SQLite 导入列表,而列表总是在变化.
既然你说你是从 sqlite 导入列表,你可能有兴趣使用现有的数据处理包,而不是逐个函数滚动你自己的函数.例如,在 pandas
中,您可以将数据加载到 DataFrame
中:
>>>df = pd.DataFrame(你的列表)>>>df0 1 20乔5 71乔6 92 迈克 1 43乔7 44 迈克 5 7[5 行 x 3 列]>>>df.groupby(0).mean()1 20乔 6 6.666667迈克 3 5.500000[2 行 x 2 列]
现在使用 pandas
单独解决问题会显得过于矫枉过正,但如果您要从数据库中提取数据,您可能会想要对数据执行多项操作.p>
I have lists like this.
list = [["Joe", 5, 7], ["Joe", 6, 9], ["Mike", 1,4], ["Joe", 7,4], ["Mike", 5,7]]
How can I convert this list to a list like this:
list2 = [["Joe", 6.00, 6.66], ["Mike", 3.00, 5.50]]
list2[0][1] and list2[1][1] are the average values from first list with spesific people (6.00 is coming from (list[0][1]+list[1][1]+list[3][1])/3
I should use iteration like this:
for i in range(len(list)):
...
or.. something like that? Because I'm importing list from SQLite and list is always changing.
Since you say you're importing the list from sqlite, you may be interested in using an existing data processing package rather than rolling your own function by function. For example, in pandas
, you could load the data into a DataFrame
:
>>> df = pd.DataFrame(yourlist)
>>> df
0 1 2
0 Joe 5 7
1 Joe 6 9
2 Mike 1 4
3 Joe 7 4
4 Mike 5 7
[5 rows x 3 columns]
>>> df.groupby(0).mean()
1 2
0
Joe 6 6.666667
Mike 3 5.500000
[2 rows x 2 columns]
Now using pandas
would be significant overkill for the problem in isolation, but if you're pulling data from a database you're probably going to want to do multiple things with the data.
这篇关于将 Python 列表值的平均值转换为另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 Python 列表值的平均值转换为另一个列表


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01