假设我有一个csv文件,每个条目都有一个唯一的ID和一个类别名称。每个类别的条目至少会出现在标题中指定的k次。现在我想选择每个类别的前k个条目(我不知道有多少个类别)
示例
原始表
ID. category
1. apple
2. apple
3. apple
4. apple
5. orange
6. orange
7. orange
8. banana
9. banana
10. banana 设k= 2
期望输出表
ID. category
1. apple
2. apple
5. orange
6. orange
8. banana
9. banana 有没有办法在Python中做到这一点(比如使用熊猫等)?目前我还没有想出实现这一目标的主意.经过一群群的搜索,我没有找到解决办法。只有在数据库中使用SQL才能找到这些,这不是我想要的。谢谢!
发布于 2017-07-14 14:59:02
哦,刚刚找到这个,用熊猫,它有用!
import pandas as pd
df = pd.read_csv(f_dir)
fd = df.groupby('category').head(2)
print fd发布于 2017-07-14 14:46:09
使用字典来跟踪这些类别以及它们被发现的频率:
catsSeen = {}
returnList = []
for row in table:
if row[1] not in catsSeen:
catsSeen[row[1]] = 1
returnList.append(row)
else:
if catsSeen[row[1]] < 2:
returnList.append(row)
catsSeen[row[1]] += 1
print(returnList)发布于 2017-07-14 14:52:48
如果输入文件按这些类别排序,则可以使用itertools.groupby
from io import StringIO
from csv import DictReader, DictWriter
from itertools import groupby
txt = '''ID. category
1. apple
2. apple
3. apple
4. apple
5. orange
6. orange
7. orange
8. banana
9. banana
10. banana'''
k = 2
with StringIO(txt) as in_file, StringIO() as out_file:
data = DictReader(in_file, delimiter=' ', skipinitialspace=True)
out = DictWriter(out_file, delimiter=' ', fieldnames=data.fieldnames)
out.writeheader()
for key, items in groupby(data, key=lambda x: x['category']):
for item, _ in zip(items, range(k)):
out.writerow(item)
print(out_file.getvalue()) # this is just to print the result...这会导致
ID. category
1. apple
2. apple
5. orange
6. orange
8. banana
9. banana(您可能必须用输入/输出文件替换StringIO )
zip(items, range(k))在到达k items或items用尽后停止--以第一位为准。
https://stackoverflow.com/questions/45105728
复制相似问题