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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With