Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python一步从csv中删除特定的行和列_Python_Csv - Fatal编程技术网

使用Python一步从csv中删除特定的行和列

使用Python一步从csv中删除特定的行和列,python,csv,Python,Csv,我有一个csv文件,我需要删除第二行和第三行以及第三到第十八列。我能够通过两个步骤让它工作,这产生了一个临时文件。我认为必须有一种更好、更紧凑的方法来做到这一点。任何建议都将不胜感激 另外,如果要删除多个列范围,如何在代码中指定。例如,除了已经指定的第3列到第18列之外,如果我想删除第25列到第29列,我将如何添加到代码中?谢谢 remove_from = 2 remove_to = 17 with open('file_a.csv', 'rb') as infile, open('inter

我有一个csv文件,我需要删除第二行和第三行以及第三到第十八列。我能够通过两个步骤让它工作,这产生了一个临时文件。我认为必须有一种更好、更紧凑的方法来做到这一点。任何建议都将不胜感激

另外,如果要删除多个列范围,如何在代码中指定。例如,除了已经指定的第3列到第18列之外,如果我想删除第25列到第29列,我将如何添加到代码中?谢谢

remove_from = 2
remove_to = 17

with open('file_a.csv', 'rb') as infile, open('interim.csv', 'wb') as outfile: 

    reader = csv.reader(infile)
    writer = csv.writer(outfile)

    for row in reader:
        del row[remove_from : remove_to]
        writer.writerow(row)

with open('interim.csv', 'rb') as infile, open('file_b.csv', 'wb') as outfile:

    reader = csv.reader(infile)
    writer = csv.writer(outfile)

    writer.writerow(next(reader))  

    reader.next()
    reader.next()

    for row in reader: 
        writer.writerow(row)

以下是一种方法:

步骤1,创建示例数据帧 第二步,变魔术 证据是:


您是否愿意使用pandas?是的,我想知道如何在pandas和not pandas中都使用pandas。没有比使用临时文件然后覆盖原始文件更有效的方法了,但如果您坚持的话(还包括各种就地和临时文件方法以及综合基准测试的示例).非常感谢您的详细回答@如果你高兴,你可以接受答案。如果没有,你也许可以指出遗漏了什么:)哦,对不起,遗漏了。我通常只是投赞成票,现在我看到我需要绿色复选框。非常感谢。
import pandas as pd

# Create sample CSV-file (100x100)
df = pd.DataFrame(np.arange(10000).reshape(100,100))
df.to_csv('test.csv', index=False)
import pandas as pd
import numpy as np

# Read first row to determine size of columns
size = pd.read_csv('test.csv',nrows=0).shape[1]

#want to remove columns 25 to 29, in addition to columns 3 to 18 already specified,
# Ok so let's create an array with the length of dataframe deleting the ranges
ranges = np.r_[3:19,25:30]
ar = np.delete(np.arange(size),ranges)

# Now let's read the dataframe
# let us also skip rows 2 and 3
df = pd.read_csv('test.csv', skiprows=[2,3], usecols=ar)

# And output
dt.to_csv('output.csv', index=False)