gpt4 book ai didi

python - 使用 Python 删除 CSV 文件中的行

转载 作者:太空宇宙 更新时间:2023-11-03 19:51:02 24 4
gpt4 key购买 nike

我想删除与参数匹配的特定行并从 CSV 文件中删除该行。我似乎找不到解决方案。

示例 CSV 数据如下:

Apple, 1.0, 1.0
Banana, 2.1, 2.1
Carrot, 3.2, 3.2

假设我只想删除 banana 行,可以吗?

def delete_place(name):
file = open('data/db.csv', 'r')
reader = csv.reader(file)

for row in reader:
if name != row[0]:
return 'Place not found.', 400
else:
# todo: delete line in csv
return 'Place with name {} deleted.'.format(name), 200

最佳答案

您可以将 csv 文件读取到 pandas dataframe 中,然后应用选择/删除操作。稍后将修改后的数据帧转储到 csv 文件中

import pandas as pd
df = pd.read_csv('data/db.csv')
df = df[df['1']!='Banana'] # I am assuming the csv file had no header, hence by default it used 1 as the header of first column
df.to_csv('data/db_modified.csv', header=False, index=False)

关于python - 使用 Python 删除 CSV 文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59842731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com