如何得到Pandas中所有重复的链接元素(行)?

iyzzxitl  于 2023-01-01  发布在  其他
关注(0)|答案(1)|浏览(82)

我试图得到所有的food-id,它已经被一个顾客消费过了,如果我给予一个customerId = C15,那么它应该返回所有的food_id,顾客有一个链接,我尝试了一些方法。

import datetime
import random
import pandas as pd

pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)

df = pd.DataFrame({
'food_id':['B1', 'CF', 'C1', 'CF', 'B1', 'IO', 'B1', 'FT', 'BR','CF', 'C1', 'SM', 'IC','B1', 'SM'],
'purch_amt':[150.5, 270.65, 65.26, 110.5, 948.5, 2400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6, 500, 500, 250],
'ord_date': ['05-10-2022','09-10-2022','05-10-2022','08-17-2022','10-09-2022','07-27-2022','10-09-2022','10-10-2022','10-10-2022','06-17-2022','07-08-2022','04-25-2022','02-08-2022','08-08-2022','07-09-2022'],
'customer_id':['C31','C31','D35','D31','C35','D31','C35','D31','D35','C31','D35','D35','D35','C35','C38']})

def get_mostly_ordered_food_id():
    print('Max food_id ordered')
    result = df['food_id'].value_counts().rename_axis('food_id').reset_index(name='counts')
    df2 = pd.DataFrame(result)
    print(df2.head(3))

def show_data():
    result = df.groupby(['customer_id'])
    print(result.first())

def test_add_data():
    foodID = ['B1', 'CF', 'C1', 'IO', 'FT', 'BR', 'IC', 'SM']
    customerID = ['C31','D35','D31','C35','C38']
    date = 'Test-Data'
    for i in range(0,10):
        df.loc[len(df.index)] = [random.choice(customerID), random.choice(foodID), date, 500]
    print(df)
    get_mostly_ordered_food_id()

如果我给予一个值,比如说一个客户ID,那么它应该返回所有已经消费的食物ID,我也不应该重复。
尝试获取例如输入“C15”(即客户ID)
它应该返回例如“B1,C2”(这是食物id)没有重复。(如果有任何重复,它应该抛出警告。)
(* 注意:有关此分配的更多上下文,请参阅this related question。*)

lmvvr0a8

lmvvr0a81#

def foods_of_customer(df, customer_id):
   foods = df['food_id'].loc[df['customer_id'] == customer_id]
   return foods.values

df.loc[]方法返回满足条件的所有行,food.values方法将 Dataframe 转换为NunPy数组,然后可以应用np.unique以避免重复。

相关问题