python删除txt指定列,从python3中的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)

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

解决方案

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.

Consider the following example:

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

Code:

import pandas as pd

df = pd.read_csv('./Sample.csv')

To delete columns:

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

df contents:

col1 col2 col4

0 1 2 4

1 5 6 8

2 9 10 12

3 13 14 16

4 17 18 20

To delete rows:

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

df contents:

col1 col2 col4

0 1 2 4

2 9 10 12

3 13 14 16

Finally to save the edited csv file:

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值