从python3中的csv文件中删除特定的列 [英] Delete specific columns from csv file in python3

查看:3296
本文介绍了从python3中的csv文件中删除特定的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要删除多个csv文件的某些特定列和行(按索引),而无需创建新文件.

Need to delete some specific column and rows(by index) of multiple csv files, without creating new files.

对于下面的代码,它在每行之后提供带有新空白行的输出.

For the code below, it is giving output with new blank rows after each row.

import csv

with open('file.csv') as fd:
   reader = csv.reader(fd)
   valid_rows = [row for idx, row in enumerate(reader) if idx != 0]

with open('file.csv', 'w') as out:
   csv.writer(out).writerows(valid_rows)

执行此操作的更简单方法是什么(可能由其他python库执行)?

What is the simpler way to do this(might be by other python libraries)?

推荐答案

由于您不希望生成任何新的csv文件,并且希望该数据执行操作,因此建议您使用 drop 函数

Since you wish not to generate any new csv files and would like the data to perform operations, I would suggest you to make use of Pandas Framework. Make use of drop function in this framework.

请考虑以下示例:

Sample.csv:

Sample.csv:

col1,col2,col3,col4
1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16
17,18,19,20

代码:

import pandas as pd
df = pd.read_csv('./Sample.csv')

要删除列:

df.drop('col3', axis = 1, inplace = True)

df内容:

   col1     col2    col4
0   1   2   4
1   5   6   8
2   9   10  12
3   13  14  16
4   17  18  20

要删除行:

df.drop(df.index[[1,4]], inplace = True)

df内容:

   col1     col2    col4
0   1   2   4
2   9   10  12
3   13  14  16

最后保存编辑的csv文件:

Finally to save the edited csv file:

df.to_csv('new_sample.csv', index = False)

这篇关于从python3中的csv文件中删除特定的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆