python - 如何将格式错误的 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 新手,所以这可能是解决一个似乎很常见的问题的最愚蠢的方法,但我一直无法找到一种可行的方法。如果有更清洁的方法,我根本不会接受上述方法。感谢帮助。
解决方案
该代码与您提供的内容运行良好。错误IndexError: list index out of range
可能是 here y = x[1].split('\n')
,其中x
没有第二个元素,也可能是 here a_split[1].strip
where a
does not contain :
soa.split(':')
有一个元素。
为避免错误,您需要检查len
并y
决定a_split
当它们只有 1 个元素时要做什么。
推荐阅读
- php - 使用 php 脚本导出 mysql db 仅适用于本地而不适用于实时服务器
- tomcat - web.xml 与 server.xml 中的 Tomcat RemoteIpFilter 配置
- azure - 每当将图像添加到另一个容器中时,触发 Azure Function App 以创建容器
- html - 将html表格导出为xlsx格式的excel时保持前导零
- python - Pandas 需要一个 Str 对象但收到一个浮点数
- python-3.x - 遍历字典以将字典键与值列表匹配并附加字典
- html - 用于匹配 HTML 标记之间块中的重复内容的正则表达式
- cross-platform - 如何以跨平台的方式高效执行不受信任的功能?
- office-ui-fabric - 单击 DetailsList 中的项目时的微调器
- javascript - 强制自动完成以填充 javascript 点击