首页 > 解决方案 > 如何将格式错误的 excel 文件放入 pandas 数据帧

问题描述

我有一个结构非常糟糕的学校俱乐部的 Excel 文件。它看起来像这样:

ClubName    ClubID  DateFormed  Participant1    Participant2    Participant..100  
Band    123 1/1/2016    "Student ID: abc\nClub Officer: President\nStudent Name: John Smith" "Student ID: def\nStudent Name: Joe Doe"   "Student ID: ghi\nStudent Name: Sarah Jones"  
Drama   456 3/4/2015    "Student ID: xyz\nStudent Name: Mary Young" "Student ID: ghi\nClub Officer: Director\nStudent Name: Sarah Jones"    

我想将其展平并将其放入两个单独的数据框中,以便我可以回答有关数据的一些基本问题。我正在尝试访问两个这样的数据框:

俱乐部名称 ClubID 成立日期

和:

ClubID ParticipantStudentID ParticipantClubOfficer ParticipantStudentName

第一个很容易,但第二个我很挣扎。我很确定我让这种方式太复杂了,但我尝试了以下方法:

#read in data
df = pd.read_excel(studentclubs.xlsx)

#get all the columns with participant data
participant_cols = [col for col in df if col.startswith('Participant')]

#add the ClubID
particpant_cols.append('ClubID')

#make a df with just participant information
participants_df = df[participant_cols]

#convert it to a dictionary
data = participants_df._to_dict('records')

#iterate over my dictionary to get a list out of each excel cell
result= []  
for line in data:  
    for key in line:  
        if type(line[key]) == str:  
           result.append((line['ClubID'], line[key]))    

结果如下所示:

[('123', 'Student ID: abc\nClub Officer: President\nStudent Name: John Smith')
 ('123', 'Student ID: def\nStudent Name: John Doe')]

问题是当我尝试将学生信息块转换为字典时:

my_dict = {}

for x in result:
    y = x[1].split('\n')
    for a in y:
        a_split = a.split(':')
        my_dict[a_split[0]] = a_split[1].strip

给我错误 IndexError: list index out of range

我是一个 python 新手,所以这可能是解决一个似乎很常见的问题的最愚蠢的方法,但我一直无法找到一种可行的方法。如果有更清洁的方法,我根本不会接受上述方法。感谢帮助。

标签: python

解决方案


该代码与您提供的内容运行良好。错误IndexError: list index out of range可能是 here y = x[1].split('\n'),其中x没有第二个元素,也可能是 here a_split[1].stripwhere adoes not contain :soa.split(':')有一个元素。

为避免错误,您需要检查leny决定a_split当它们只有 1 个元素时要做什么。


推荐阅读