【问题标题】:Removal of rows containing a particular text in a csv file using Python使用 Python 删除 csv 文件中包含特定文本的行
【发布时间】:2023-01-19 22:01:05
【问题描述】:

我有一个包含 3500 多行的基因组数据集。我需要从中删除两列(“长度”和“蛋白质名称”)中的行。我如何为此目的指定条件。

import csv #importing the csv module or method

#opening a new csv file 
file = open('C:\\Users\\Admin\\Downloads\\csv.csv', 'r')
type(file)

#reading the csv file 
csvreader = csv.reader(file)
header = []
header = next(csvreader)
print(header)

#extracting rows from the csv file
rows = []
for row in csvreader:
    rows.append(row)
print(rows)

我是python生物信息学数据分析的初学者,没有尝试过任何广泛的方法。我不知道如何从这里开始。我已经完成了打开和读取 csv 文件的工作。我还提取了列标题。但我不知道如何从这里开始。请帮忙。

【问题讨论】:

  • 您需要从“长度”和“蛋白质名称”列中删除所有行吗?
  • 或者您是否需要从每一行中删除“长度”和“蛋白质名称”列?

标签: python dataframe csv row readfile


【解决方案1】:

尝试这个 :

csvreader= csvreader[csvreader["columnName"].str.contains("string to delete") == False]

【讨论】:

    【解决方案2】:

    最好在 pandas 中阅读 scv,因为你有很多行。这将是做出的明智决定。并设置一些您将用于执行操作的条件变量。如果这没有帮助。我建议您提供 scv 文件的示例数据。

    df = pd.read_csv('C:\Users\Admin\Downloads\csv.csv')
    
    length = 10
    protein_name = "replace with protain name"
    
    df = df[(df["Length"] > length) & (df["Protein Name"] != protein_name)]
    print(df)
    

    如果需要,您可以将 df 保存回 csv 文件:

    df.to_csv("'C:\Users\Admin\Downloads\new_csv.csv'", index=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多