ifの使い方と条件式が良くないです。
Python
1# meal_idを5つに分類
2
3def meal_cluster(x):
4 if x["meal_id"] == "1558" or x["meal_id"] == "2581" or x["meal_id"] == "2707":
5 res = 1
6 elif x["meal_id"] == "1778" or x["meal_id"] == "1962" or x["meal_id"] == "1993":
7 res = 2
8 elif x["meal_id"] == "1109" or x["meal_id"] == "2290" or x["meal_id"] == "2664":
9 res = 3
10 elif x["meal_id"] == "1885" or x["meal_id"] == "2539":
11 res = 4
12 else:
13 res = 5
14 return res
15
16meal["meal_cluster"] = meal.apply(meal_cluster, axis=1)
17meal.head()
条件式を修正した場合でも、elifを使用しないとresが4と5のみになってしまいます。
ifの使い方と条件式の書き方を学びましょう。
Pythonのif文による条件分岐の書き方
【追記】
手元で試した結果を追記します。こちらでは問題なさそうです。
Python
1import pandas as pd
2
3meal = pd.DataFrame({'meal_id':['1558','1778','1109','1885','1000','2581','1962','2290','2539','2707','1993','2664']})
4print(meal)
5# meal_id
6#0 1558
7#1 1778
8#2 1109
9#3 1885
10#4 1000
11#5 2581
12#6 1962
13#7 2290
14#8 2539
15#9 2707
16#10 1993
17#11 2664
18
19def meal_cluster(x):
20 if x["meal_id"] == "1558" or x["meal_id"] == "2581" or x["meal_id"] == "2707":
21 res = 1
22 elif x["meal_id"] == "1778" or x["meal_id"] == "1962" or x["meal_id"] == "1993":
23 res = 2
24 elif x["meal_id"] == "1109" or x["meal_id"] == "2290" or x["meal_id"] == "2664":
25 res = 3
26 elif x["meal_id"] == "1885" or x["meal_id"] == "2539":
27 res = 4
28 else:
29 res = 5
30 return res
31
32meal["meal_cluster"] = meal.apply(meal_cluster, axis=1)
33print(meal)
34# meal_id meal_cluster
35#0 1558 1
36#1 1778 2
37#2 1109 3
38#3 1885 4
39#4 1000 5
40#5 2581 1
41#6 1962 2
42#7 2290 3
43#8 2539 4
44#9 2707 1
45#10 1993 2
46#11 2664 3