在Python中删除列表中每个元组的第一项

2024-06-11 22:04:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表,格式如下:

[(“25.00”,u“A”),(“44.00”,u“X”),(“17.00”,u“E”),(“34.00”,u“Y”)]

我想数一数我们收到每封信的时间。 我已经创建了一个包含所有字母的排序列表,现在我想对它们进行计数。你知道吗

首先,在每个元组的第二个项目之前,我有一个u的问题,我不知道如何删除它,我猜这是关于重唱的东西。你知道吗

这是我的密码

# coding=utf-8
from collections import Counter 
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile

df = pd.read_excel('test.xlsx', sheet_name='Essais', skiprows=1)
groupes = [] 
students = [] 
group_of_each_letter = [] 
number_of_students_per_group = []
final_list = []

def print_a_list(list):
    for items in list:
        print(items)


for i in df.index:
    groupes.append(df['GROUPE'][i]) 
    students.append(df[u'ÉTUDIANT'][i]) 

groupes = groupes[1:] 
students = students[1:] 

group_of_each_letter = list(set(groupes)) 
group_of_each_letter = sorted(group_of_each_letter) 

z = zip(students, groupes) 
z = list(set(z)) 

final_list = list(zip(*z)) 

for j in group_of_each_letter:
    number_of_students_per_group.append(final_list.count(j))

print_a_list(number_of_students_per_group)

每个字母的组是一个包含组字母的列表,没有重复。你知道吗

问题是我在for循环的末尾得到了正确的值,但是列表中填充了“0”。你知道吗

下面的屏幕截图是excel文件的示例。“ETUDIANT”一栏的意思是“学生号”,但是我不能编辑这个文件,我必须处理它。GROUPE的意思很明显。目标是统计每个小组的学生人数。我认为我走的是对的,即使有更简单的方法。你知道吗

enter image description here

即使我知道我的问题有点模棱两可,也要提前感谢你的帮助


Tags: offromimportnumberpandasdf列表for
2条回答

基于柯维的回答:

使用groupby(),然后使用nunique()

这将为您提供每个组中唯一的学生ID的数量。你知道吗

import pandas as pd

df = pd.read_excel('test.xlsx', sheet_name='Essais', skiprows=1)
# Drop the empty row, which is actually the subheader
df.drop(0, axis=0, inplace=True)
# Now we get a count of unique students by group
student_group = df.groupby('GROUPE')[u'ÉTUDIANT'].nunique()

我认为groupby.count()就足够了。它将统计您的组字母在数据帧中出现的次数。你知道吗

import pandas as pd

df = pd.read_excel('test.xlsx', sheet_name='Essais', skiprows=1)
# Drop the empty row, which is actually the subheader
df.drop(0, axis=0, inplace=True)
# Now we get a count of students by group
sub_student_group = df.groupby(['GROUPE','ETUDIANT']).count().reset_index()

>>>sub_student_group
   GROUPE  ETUDIANT
0       B        29
1       L        88
2       N        65
3       O        27
4       O        29
5       O        34
6       O        35
7       O        54
8       O        65
9       O        88
10      O        99
11      O       114
12      O       122
13      O       143
14      O       147
15      U       122

student_group = sub_student_group.groupby('GROUPE').count()

>>>student_group
        ETUDIANT
GROUPE
B              1
L              1
N              1
O             12
U              1

相关问题 更多 >