我正在尝试在 csv 中记录成功计数和失败计数。 我正在使用 python pandas 。
期望: 所有条目都应该是唯一的。 电子邮件列应该是唯一的,成功计数或失败计数应根据参数增加,
错误: 我在 csv 中收到重复的条目。 输出 csv 中存在具有相同电子邮件地址的多个条目。
我正在检查我的代码,如果条目中已存在电子邮件。 我仍然在 data.csv 中收到重复的条目
def save_data(email: str, is_success: int, is_failed: int) -> None:
csv_file_path = "data.csv"
# Check if the CSV file already exists and handle empty file case
try:
df = pd.read_csv(csv_file_path)
except FileNotFoundError:
df = pd.DataFrame(
columns=["email", "success_count", "failure_count", "last_updated_on"]
)
# Check for duplicates and update counts
if email in df["email"].values:
index = df[df["email"] == email].index[0]
df.at[index, "failure_count"] += is_failed
df.at[index, "success_count"] += is_success
df.at[index, "last_updated_on"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
else:
# Append new entry
new_entry = {
"email": email,
"success_count": is_success,
"failure_count": is_failed,
"last_updated_on": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
df = df._append(new_entry, ignore_index=True)
# Write to CSV file
try:
df.to_csv(csv_file_path, index=False)
except Exception as e:
print("Error occurred while writing to CSV file:", e)
您可以在末尾使用
pd.drop_duplicates()
到您的数据框
您可以使用一些参数指定更多详细信息,如
subset
、keep
等。