简体   繁体   English

在python中删除CSV文件的特定行

[英]Deleting specific rows of CSV file in python

I have a CSV file, and i want to delete some rows of it based on the values of one of the columns. 我有一个CSV文件,并且我想根据其中一列的值删除它的某些行。 I do not know the related code to delete the specific rows of a CSV file which is in type pandas.core.frame.DataFrame . 我不知道删除pandas.core.frame.DataFrame类型的CSV文件特定行的相关代码。

I read related questions, and i found that people suggest writing every line that is acceptable in a new file. 我读了相关的问题,发现人们建议写一个新文件中可接受的每一行。 I do not want to do that. 我不想那样做。 The thing that i want is: 我想要的是:

1) to delete the rows that I know the index of them (number of the row) 1)删除我知道它们索引的行(行数)

or 要么

2) to make a new CSV in the memory of the python (not to write and again read it ) 2)在python的内存中创建一个新的CSV(不要写再读一次)

Here's an example of what you can do with pandas . 这是您可以对pandas做什么的示例。 If you need more detail, you might find Indexing and Selecting Data a helpful resource. 如果需要更多详细信息,可能会发现“ 索引编制和选择数据”是有用的资源。

import pandas as pd
from io import StringIO

mystr = StringIO("""speed,time,date
12,22:05,1
15,22:10,1
13,22:15,1""")

# replace mystr with 'file.csv'
df = pd.read_csv(mystr)

# convert time column to timedelta, assuming mm:ss
df['time'] = pd.to_timedelta('00:'+df['time'])

# filter for >= 22:10, i.e. second item
df = df[df['time'] >= df['time'].loc[1]]

print(df)

   speed     time  date
1     15 00:22:10     1
2     13 00:22:15     1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM