我有以下df
>In [260]: df
>Out[260]:
size market vegetable confirm availability
0 Large ABC Tomato NaN
1 Large XYZ Tomato NaN
2 Small ABC Tomato NaN
3 Large ABC Onion NaN
4 Small ABC Onion NaN
5 Small XYZ Onion NaN
6 Small XYZ Onion NaN
7 Small XYZ Cabbage NaN
8 Large XYZ Cabbage NaN
9 Small ABC Cabbage NaN
1)如何获得大小最大的蔬菜的大小?
我在蔬菜和大小上使用groupby得到以下df但是我需要得到包含蔬菜最大数量的行
In [262]: df.groupby(['vegetable','size']).count()
Out[262]: market confirm availability
vegetable size
Cabbage Large 1 0
Small 2 0
Onion Large 1 0
Small 3 0
Tomato Large 2 0
Small 1 0
df2['vegetable','size'] = df.groupby(['vegetable','size']).count().apply( some logic )
要求的Df:
vegetable size max_count
0 Cabbage Small 2
1 Onion Small 3
2 Tomato Large 2
2)现在我可以说df中有大量的“小白菜”。所以我需要用所有卷心菜行填充确认可用性列如何做到这一点?
size market vegetable confirm availability
0 Large ABC Tomato Large
1 Large XYZ Tomato Large
2 Small ABC Tomato Large
3 Large ABC Onion Small
4 Small ABC Onion Small
5 Small XYZ Onion Small
6 Small XYZ Onion Small
7 Small XYZ Cabbage Small
8 Large XYZ Cabbage Small
9 Small ABC Cabbage Small
1)
required_df = veg_df.groupby(['vegetable','size'], as_index=False)['market'].count()\
.sort_values(by=['vegetable', 'market'])\
.drop_duplicates(subset='vegetable', keep='last')
2)
merged_df = veg_df.merge(required_df, on='vegetable')
cols = ['size_x', 'market_x', 'vegetable', 'size_y']
dict_renaming_cols = {'size_x': 'size',
'market_x': 'market',
'size_y': 'confirm_availability'}
merged_df = merged_df.loc[:,cols].rename(columns=dict_renaming_cols)
您可以将分组的数据框分配给另一个对象,然后您可以对“蔬菜”的索引进行其他分组以获得所需的最大值
d = df.groupby(['vegetable','size']).count()
d.groupby(d.index.get_level_values(0).tolist()).apply(lambda x:x[x.confirm == x.confirm.max()])
日期:
market confirm availability
vegetable size
Cabbage Cabbage Small 2 2 0
Onion Onion Small 3 3 0
Tomato Tomato Large 2 2 0
你可以用GroupBy
count
,然后排序和删除重复:
res = df.groupby(['size', 'vegetable'], as_index=False)['market'].count()\
.sort_values('market', ascending=False)\
.drop_duplicates('vegetable')
print(res)
size vegetable market
4 Small Onion 3
2 Large Tomato 2
3 Small Cabbage 2