首页 > 解决方案 > 无法使用熊猫从 .csv 列中删除重复项

问题描述

我正在尝试对包含地址的 .csv 做一些非常简单的事情。如果它们在单个列(['Addresses'])中包含重复值,我想使用 pandas 函数 drop_duplicates() 删除任何行。

每当我尝试使用 drop_duplicates() 并将我的数据框打印或保存到新的 .csv 时,重复的行/值仍然存在。


data = pandas.read_csv(r"C:\Users\markbrd\Desktop\PalmAveAddresses.csv",
encoding = "ISO-8859-1")

data.drop_duplicates(subset=['Addresses'], keep='first')

print(data['Addresses'])

结果:

0             4834Via Estrella
1             5244Via Patricia
2        11721HIDDEN VALLEY RD
3                  30GARDEN CT
4      1999Fremont Blvd. Bldg.
5          8316Fountainhead Ct
6          8312Fountainhead Ct
7               1013Adella Ave
8               1005Adella Ave
9                 1520Tenth St
10                1536Tenth St

                ...           

607              847Florida St
608                 81212th St
609                 81212th St
610                 81212th St
611                 81212th St
612                 81212th St
613                 81212th St
614                 81212th St
615                 81212th St
616                 81212th St
617                 81212th St
618                 81212th St
619                 81212th St

如您所见,地址中仍有几行包含重复项(请参见第 609-619 行)。任何帮助将不胜感激!

标签: pythonpython-3.xpandas

解决方案


您需要就地分配或使用。

data.drop_duplicates(subset=['Addresses'], keep='first', inplace=True)

推荐阅读