我按照此处的建议过滤了我的数据:With Pandas in Python, select the highest value row for each group
author cat val
0 author1 category2 15
1 author2 category4 9
2 author3 category1 7
3 author3 category3 7
现在,我想只让作者出现在这个数据框中一次。我写了这个,但它不起作用:
def where_just_one_exists(group):
return group.loc[group.count() == 1]
most_expensive_single_category = most_expensive_for_each_model.groupby('author', as_index = False).apply(where_just_one_exists).reset_index(drop = True)
print most_expensive_single_category
错误:
File "/home/mike/anaconda/lib/python2.7/site-packages/pandas/core/indexing.py", line 1659, in check_bool_indexer
raise IndexingError('Unalignable boolean Series key provided')
pandas.core.indexing.IndexingError: Unalignable boolean Series key provided
我想要的输出是:
author cat val
0 author1 category2 15
1 author2 category4 9
2 author3 category1 7
3 author3 category3 7
答案 0 :(得分:4)
更容易
df.groupby('author').filter(lambda x: len(x)==1)
author cat val
id
0 author1 category2 15
1 author2 category4 9
答案 1 :(得分:1)
我的解决方案有点复杂但仍然有效
def groupbyOneOccurrence(df):
grouped = df.groupby("author")
retDf = pd.DataFrame()
for group in grouped:
if len(group[1]._get_values) == 1:
retDf = pd.concat([retDf, group[1]])
return retDf
author cat val
0 author1 category2 15
1 author2 category4 9