[英]Is there a way to combine the 1st index of a list if the 0 values in the list are the same?
import csv
import pandas as pd
from matplotlib import pyplot as plt
# Declaring workout data to df variable
df = pd.read_csv('workout.csv')
# Declaring name variable and storing name data into it
name = df['name']
# Calculating the mass moved
moved_mass_data = df['sets'] * df['reps'] * df['weight']
# storing mass moved data into the df data frame
df['mass moved'] = moved_mass_data
# turning moved mass data frame into a list
moved_mass = moved_mass_data.to_list()
# turning exercise name data frame into a list
exercise_name = name.to_list()
# zip names and mass moved together
exercise_moved_mass = zip(exercise_name, moved_mass)
# converting the zip into a list
exercise_moved_mass_list = list(exercise_moved_mass)
# exercise_moved_mass_list prints
[('Facepull', 480), ('Lat Pull Down', 600), ('Dumbbell Bench', 720), ('Dumbbell Bench', 1200), ('Dumbbell Bench', 2880), ('Dips', 3780), ('Incline Fly', 720), ('Incline Fly', 800), ('Incline Fly', 1200), ('Incline Fly', 800)]
#How could I make a function that would turn list to this
[('Facepull', 480), ('Lat Pull Down', 600), ('Dumbbell Bench', 4,800), ('Dips',3780), ('Incline Fly', 2800)]
In the expected output the Incline Fly should be ('Incline Fly',3520), if yes,在预期的 output 中,Incline Fly 应该是('Incline Fly',3520),如果是,
This code should work->这段代码应该可以工作->
b = {}
for i in exercise_moved_mass_list:
try:
b[i[0]]+=i[1]
except:
b[i[0]]=i[1]
c = [(x, y) for x, y in b.items()]
Output: Output:
[('Facepull', 480),
('Lat Pull Down', 600),
('Dumbbell Bench', 4800),
('Dips', 3780),
('Incline Fly', 3520)]
Another method using your dataframe df
:使用 dataframe
df
的另一种方法:
>>> df[["name", "mass moved"]].groupby("name").sum().to_records().tolist()
[('Dips', 3780),
('Dumbbell Bench', 4800),
('Facepull', 480),
('Incline Fly', 3520),
('Lat Pull Down', 600)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.