我希望只选择列中元素的总重复数少于3次的行。具体来说,我有一个电话号码、名字和城市的大目录。我只想导出一个“小城市”的列表,这样,在文档中包含少于三个条目的城市的任何行都会被保留。所以,例如
Name, City, State
Foo, L.A., CA
Bar, L.A., CA
Sam, L.A., CA
Tricia, Kent, WA
Bob, Kent, WA
Ida, Boo, PA
Monster Mash, Whack, PA
Zoomacroom, L.A., CA
Otter Pop, Boo, PA
Snake, HP, WA
Ronnie the Bear, Boo, PA应成为:
Name, City, State
Tricia, Kent, WA
Bob, Kent, WA
Snake, HP, WA
Monster Mash, Whack, PA我也不需要使用熊猫-我可以使用csv一样容易,我只是碰巧已经在我的清洁脚本导入它。
发布于 2014-01-17 20:57:37
不如这样吧:
>>> small_cities = df.groupby(["City", "State"]).filter(lambda x: x.count() < 3)
>>> small_cities
Name City State
3 Tricia Kent WA
4 Bob Kent WA
6 Monster Mash Whack PA
9 Snake HP WA
[4 rows x 3 columns]发布于 2014-01-17 20:54:54
编辑:我认为在发布的前5分钟改变了所需的DataFrame。这个答案描述了如何删除所有列中的重复(不仅仅是在这个城市/州的具体例子中,在那里没有太多的意义)。
您可以对单个列执行此操作(删除3次以上的城市名称):
In [11]: g = df.groupby('City')
In [12]: g.filter(lambda x: len(x['City']) < 4)
Out[12]:
Name City State
5 Ida Boo PA
8 Otter Pop Boo PA
10 Ronnie the Bear Boo PA
9 Snake HP WA
3 Tricia Kent WA
4 Bob Kent WA
6 Monster Mash Whack PA在所有列中都这样做(这有点混乱!)但是,您可以为任意帧创建一个函数.):
In [13]: less_than_4 = ((df.groupby('City').City.transform(lambda x: len(x) < 4))
& (df.groupby('State').State.transform(lambda x: len(x) < 4))
& ((df.groupby('Name').Name.transform(lambda x: len(x) < 4))))
In [14]: df[less_than_4]
Out[14]:
Name City State
3 Tricia Kent WA
4 Bob Kent WA
9 Snake HP WA更优雅的是:
from operator import and_
df[reduce(and_, (df.groupby(col)[col].transform(lambda x: len(x) < 4)
for col in df.columns))]发布于 2014-01-17 20:55:20
与…有关的东西:
with open(filename) as f:
content = f.readlines()
for line in set(content):
if content.count([-2:]) < 4:
output.append(line[-2:])希望这能有所帮助
https://stackoverflow.com/questions/21195360
复制相似问题