【问题标题】:How to delete row data from a CSV file using pandas?如何使用熊猫从 CSV 文件中删除行数据?
【发布时间】:2019-11-14 16:56:53
【问题描述】:

我是 Pandas 的新手,想知道如何使用行 ID 删除特定行。目前,我有一个 CSV 文件,其中包含有关不同学生的数据。我的 CSV 文件中没有任何标题。

data.csv:

John    21 34 87 ........ #more than 100 columns of data
Abigail 18 45 53 ........ #more than 100 columns of data
Norton  19 45 12 ........ #more than 100 columns of data

data.py:

我有一个包含一些名字记录的列表。

names = ['Jonathan', 'Abigail', 'Cassandra', 'Ezekiel']

我在 Python 中打开了我的 CSV 文件并使用列表解析来读取第一列中的所有名称并将它们存储在分配了变量“student_list”的列表中。

现在,对于 student_list 中的所有元素,如果在 'names' 列表中没有看到该元素,我想在我的 CSV 文件中删除该元素。在此示例中,我想删除 John 和 Norton,因为它们没有出现在名称列表中。如何使用熊猫实现这一目标?或者,有没有比使用 pandas 解决这个问题更好的选择?

我尝试了以下代码:

csv_filename = data.csv
    with open(csv_filename, 'r') as readfile:
        reader = csv.reader(readfile, delimiter=',') 
        student_list = [row[0] for row in reader]  #returns John, Abigail and Norton.

        for student in student_list:
        if student not in names:
            id = student_list.index(student) #grab the index of the student in student list who's not found in the names list.

            #using pandas
            df = pd.read_csv(csv_filename) #read data.csv file
            df.drop(df.index[id], in_place = True) #delete the row id for the student who does not exist in names list.
            df.to_csv(csv_filename, index = False, sep=',')  #close the csv file with no index
        else:
            print("Student name found in names list")

我无法正确删除数据。谁能解释一下?

【问题讨论】:

  • 好的,我试一试。
  • @jezrael 我得到了我在 csv 文件中输入的所有数据的列表。
  • 那么print (df.index.tolist()[:5]) 是什么?有3 值吗?
  • @jezrael 只是问一下,在使用pandas时,索引是从0开始还是从1开始?是的,我觉得有一些索引问题。
  • 它从0开始,就像在python中一样。

标签: python-3.x pandas


【解决方案1】:

您可以只使用过滤器来过滤掉您不想要的 id。

例子:

import pandas as pd
from io import StringIO

data = """
1,John
2,Beckey
3,Timothy
"""

df = pd.read_csv(StringIO(data), sep=',', header=None, names=['id', 'name'])


unwanted_ids = [3]

new_df = df[~df.id.isin(unwanted_ids)]

您还可以使用过滤器并获取索引以删除原始数据框中的列。示例:

df.drop(df[df.id.isin([3])].index, inplace=True)

更新更新问题:

df = pd.read_csv(csv_filename, sep='\t', header=None, names=['name', 'age'])
# keep only names wanted and reset index starting from 0
# drop=True makes sure to drop old index and not add it as column
df = df[df.name.isin(names)].reset_index(drop=True)
# if you really want index starting from 1 you can use this
df.index = df.index + 1
df.to_csv(csv_filename, index = False, sep=',')

【讨论】:

  • 可以用我的 CSV 文件替换数据吗?
  • 我将格式更改为逗号分隔,因为这更适合从 SO 复制粘贴。但实际上,您可以只阅读制表符分隔的文件,例如:df = pd.read_csv('drop_columns.csv', sep='\t', header=None, names=['id', 'name', 'age'])
  • 是否可以读取和更改同一个 CSV 文件?你为什么在这里使用“drop_columns.csv”?
  • 我的错误,已修复。是的,您可以读取 csv_filename 然后覆盖同一个文件。
  • 我应该使用哪种方法?在您看来,我应该使用 drop 还是 filter 选项?删除后我不想在我的 CSV 文件中出现空白行,并且行 ID 的顺序应该没有任何间隙,即 1,2,3,4 而不是 1,4,5,6,9 等...
猜你喜欢
  • 2017-09-21
  • 1970-01-01
  • 2015-03-18
  • 2019-10-01
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 2018-02-16
  • 2018-07-01
相关资源
最近更新 更多