I have a dataframe like below..
dish_quant_bought dish_name
20 A
18 B
20 A
18 B
20 A
18 B
10 C
18 B
10 C
18 B
20 D
20 D
20 D
20 D
I want to extract corresponding dish_quant_bought for given dish name.. So for dish A it should return only 20, for B is 18 ,C is 10 & for D is 20
I am trying with below code but it doesn't work..
df_['dish_quant_bought']['dish_name'] == 'A'
Please help..
Unclear why you have duplicates but you can use a boolean condition to mask the df and return the col of interest:
In [256]:
df = df.drop_duplicates()
df
Out[256]:
dish_quant_bought dish_name
0 20 A
1 18 B
6 10 C
10 20 D
In [257]:
df.loc[df['dish_name']=='A', 'dish_quant_bought']
Out[257]:
0 20
Name: dish_quant_bought, dtype: int64
The mask on your original df:
In [259]:
df['dish_name']=='A'
Out[259]:
0 True
1 False
2 True
3 False
4 True
5 False
6 False
7 False
8 False
9 False
10 False
11 False
12 False
13 False
Name: dish_name, dtype: bool
You can get the unique value by calling unique
after the filtering without calling drop_duplicates
first:
In [297]:
df.loc[df['dish_name']=='A', 'dish_quant_bought'].unique()
Out[297]:
array([20], dtype=int64)
Well, if they have the same quantity value, you could get by using groupby and then mean on the selected column, it will produce the same value
df.groupby(["dish_name"])["dish_quant_bought"].mean()
then just select whatever name you want
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.