python - 将多个单列 excel 文件与特定的嵌套列表/元组进行比较
问题描述
请给我一些建议。我有一个包含 30 个嵌套元素(从 json 响应转换而来)的元组,格式如下:
[('Group_1',['xyz123','str123','834hsj','nmp001','888tyu','abc123']),...('Group_30' ,['aaaa', 'bbb', 'fff'])
我有 5 个以元组中的 5 个相应组命名的 excel 文件加上它们的行如下:
Excel xls 文件 1: 名称:Group_1 内容:
Column: A
Row1: Group_1
Row2: xyz123
Row3: str123
Row4: 834hsj
Row5: nmp001
Row6: 888tyu
Row7: abc123
Excel xls 文件 2: 名称:Group_2 内容:
第 1 行:Group_2
等到 Group_5
目的是比较元组和excel文件中元素之间的组匹配值,以便元组加嵌套列表中的Group_1到Group_5匹配excel的内容及其列内容。如果相应的组有差异,则列出丢失或未完成的字符串及其位置。
您是否建议将 excel 文件(所有 1 列大小不同的长度)作为单独的数据帧导入 panda 并将元组分解为单独的列表,然后也分解为 panda 数据帧?或在数据框中导入 excel,然后转换为列表(每组 1 个)以与元组进行比较(必须将其分解为组列表。
谢谢
解决方案
最简单的方法是循环读取每个文件,将每个列表变成一个集合,然后变得疯狂。:
假设您在列表中有元组列表groups
:
groups
[('Group_1',['xyz123','str123','834hsj','nmp001','888tyu','abc123']),
('Group_30' ,['aaaa', 'bbb', 'fff'])]
你有这样的组名命名的文件:
Group_1.xls
Group_30.xls
首先,读取XLS,跳过第一行(即'A'),并将第二行设置为列名(即'Group_1')。
for group in groups:
df = pd.read_excel(group[0] + '.xls', header=0, skiprows=[0])
它应该如下所示:
df
Group_1
0 xyz123
1 str123
2 834hsj
3 nmp001
4 888tyu
5 abc123
然后,我们将文件和列表中的元素转换为集合并输出结果:
for group in groups:
df = pd.read_excel(group[0] + '.xls', header=0, skiprows=[0])
file_set = set(df[group[0]].to_list())
tup_set = set(group[1])
print()
print("In file and in tuple")
print(file_set.intersection(tup_set))
print("In file, but not in tuple")
print(file_set.difference(tup_set))
print("In tuple, but not in file")
print(tup_set.difference(file_set))
你应该得到这样的输出:
In file and in tuple
{'nmp001', '834hsj', '888tyu', 'str123', 'abc123', 'xyz123'}
In file, but not in tuple
set()
In tuple, but not in file
set()
In file and in tuple
set()
In file, but not in tuple
{'nmp001', '834hsj', '888tyu', 'str123', 'abc123', 'xyz123'}
In tuple, but not in file
{'bbb', 'fff', 'aaaa'}
PS。set()
是空集。
推荐阅读
- mongodb - 如何在 MongoDB 中按多个字段返回组结果?
- ionic-framework - Ionic V4 是否支持低于 7.0 的安卓版本?
- javascript - 如何使用 lodash 对对象进行分组并在列表上映射 -react
- macos - Mac 上 Minikube 中 ExternalName 的 DNS 解析
- amazon-web-services - 在 AWS DynamoDB 查询中,是否可以将字符串查询为数字?
- java - 是否可以使用基类(非单例类)继承单例类。如果是,这是一个好习惯吗?
- chatbot - 使用 Botium 进行语音机器人测试
- java - 使用 selenium C# 自动分页
- makefile - 不会触发重新编译的 Makefile 依赖项?
- ag-grid - ag-grid & 符号在表中未正确显示