簡體   English   中英

刪除Python列表中每個元組的第一項

[英]Delete first item of every tuples in a list in 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的意思是GROUP。 目標是計算每個小組的學生人數。 我認為我有正確的方法,即使有更簡單的方法也可以。

在此處輸入圖片說明

預先感謝您的幫助,即使我知道我的問題有點模棱兩可

建立在可維的答案之上:

使用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()應該足夠了。 它將計算數據框中您的GROUPE字母的出現次數。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM