如何解决Excel 文件 - 如何提取多个键并将它们设为以“:”分隔的列和值作为行值
我正在阅读一个 Excel(xlsx),其中包含 Number 和 Info 列,其中 Info 包含简单的多行键:值。 我想提取特定的键(从键列表中)并将它们作为新列。
List of Keys = [Name,Age,Gender,Occupation]
棘手的部分是在几个地方提到了不同的键,如姓名/全名、性别/性别。序列不固定,如果键不可用,则将值单元格留空。
我正在使用熊猫来实现这一点。任何帮助在这里表示赞赏。
解决方法
首先从 Excel 文件中读取:
df = pd.read_excel (r'Path where the Excel file is stored\File name.xlsx')
然后迭代每一行并解析你想要的。下面是一个例子:
for row in df.iterrows():
info = row[1]["info"].split('\n')
name = info[0].split(": ")[1]
age = info[1].split(": ")[1]
最后,你可以用这些解析值制作df并保存为xlsx等
编辑
如果您想解析无序信息,此代码可能对您有所帮助:
listOfKeys = {"Name","Age","Gender","Occupation"}
for row in df.iterrows():
# Separate each items
info = row[1]["info"].split('\n')
# Remove unwanted spaces
info = [item.replace(" ","") for item in info]
items = {item.split(":")[0]: item.split(":")[1] for item in info}
emptyKeys = listOfKeys - set(items.keys())
for emptyKey in emptyKeys:
items[emptyKey] = ""
因此,每个信息都转换为上面命名为 items 的字典,并且所有未给定的功能都具有空值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。