【发布时间】: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