python - openpyxl 数据框过滤
问题描述
我刚刚开始使用 python,在使用各自的值过滤 F 和 I 列之后,我需要将列 K 中的所有内容放入列表中。
所以基本上当列 F 匹配stringA
并且列 I 匹配stringC
时,然后将列 K 的所有值保存到列表中。我的代码已经用于导入正确的模块、打开和保存工作表,我只需要这部分的帮助。
我确信有不同的方法可以实现它。
l = []
for icol in sheet1.columns:
coll = icol[0].column
for cell in icol:
if(coll == 'F' and cell.value == 'stringA' or coll == 'I' and cell.value == 'stringC'):
print(coll, cell.value)
if (coll == 'K'):
l.append(cell.value)
print(l)
我真正需要的只是在附加行中指定单元格名称。也许有一种非常pythonic的方式来做到这一点。如果我弄清楚了,我会分享。
解决方案
假设你已经安装了pandas
,这将起作用:xlrd
openpyxl
import pandas as pd
# this example data should result in a list with only 'value 1' and 'value 6'
df = pd.DataFrame([
[None, None, None, None, None, 'stringA', None, None, 'stringC', None, 'value 1'],
[None, None, None, None, None, 'stringX', None, None, 'stringC', None, 'value 2'],
[None, None, None, None, None, 'stringA', None, None, 'stringX', None, 'value 3'],
[None, None, None, None, None, None , None, None, 'stringC', None, 'value 4'],
[None, None, None, None, None, 'stringA', None, None, None , None, 'value 5'],
[None, None, None, None, None, 'stringA', None, None, 'stringC', None, 'value 6'],
])
# just writing the file, so you can verify it matches your input data
df.to_excel('test.xlsx', header=False, index=False)
# As @JiWei suggests, but using the column index instead of the name
print(df[(df[5] == 'stringA') & (df[8] == 'stringC')][10].tolist())
结果:
['value 1', 'value 6']
所以,如果你已经有一个类似的文件test.xlsx
,你只需要:
import pandas as pd
df = pd.read_excel('test.xlsx', header=None)
print(df[(df[5] == 'stringA') & (df[8] == 'stringC')][10].tolist())
推荐阅读
- css - 小荧光笔效果
- html - 网格响应性问题
- swift - 我需要构建 pdf 查看器,但有 2 个 urls 到 pdfs 文件
- mongodb - MongoDB atlas 错误:uncaughtException:(未授权)管理员未授权执行命令
- javascript - Phaser 3:更改场景的大小而不影响其下方的较大场景
- java - 尝试调用虚拟方法 'void android.widget.GridView.setAdapter(android.widget.ListAdapter
- android - 如何从画廊添加视频并在 android studio 的 videoview 上播放?
- google-sheets - GoogleSheet 求和直到空行并按“个人”分组
- dokku - 部署在 dokku-ubuntu-s-1vcpu-1gb-nyc1-01 上时如何访问 Dokku 上的应用程序?
- amazon-web-services - DynamoDB flush latency