python - 在熊猫读取csv中保存跳过行
问题描述
我有一个跳过行的列表(比如 [1,5,10] --> 行号),当我将它传递给pandas read_csv时,它会忽略这些行。但是,我需要将这些跳过的行保存在不同的文本文件中。
我浏览了 pandas read_csv 文档和其他几篇文章,但不知道如何将其保存到文本文件中。
例子 :
输入文件 :
a,b,c
# Some Junk to Skip 1
4,5,6
# Some junk to skip 2
9,20,9
2,3,4
5,6,7
代码 :
skiprows = [1,3]
df = pandas.read_csv(file, skip_rows = skiprows)
现在 output.txt :
# Some junk to skip 1
# Some junk to skip 2
提前致谢!
解决方案
def write_skiprows(infile, skiprows, outfile='skiprows.csv')
maxrow = max(skiprows)
with open(infile, 'r') as f, open(outfile, 'w') as o:
for i, line in enumerate(f):
if i in skiprows:
o.write(line)
if i == maxrow:
return
推荐阅读
- reverse-proxy - 定义 HAProxy ACL 以根据请求 URL 路由后端
- python - Django 迭代 zip 中的所有值
- java - 如何从 Ant 生成的战争中排除 java 源文件?
- javascript - 如何在没有过滤器的情况下在 ExtJS 中通过 ID 获取关联的模型数据?
- r-markdown - RMarkdown 代码块在预览中有效,但在使用 bookdown“构建”时无效
- python - 在地图上绘制经度和纬度并为每个子集创建线(DataFarame 中的每一行)
- javascript - R闪亮中的networkD3在Chrome,Firefox中无法正确显示,但在Safari中可以吗?
- sql - 如何在我的 ORDER BY 语法中解决与 CASE 语句相关的这个错误?
- python - 如何找出“*”运算符对某个库(cirq)中的两个对象的作用?
- javascript - jQuery 没有读取 .ejs 页面上的变量