返回由给定输入的序列重复最多的值

问题描述 投票:-1回答:1

我尝试用他的详细信息获得最受关注的新用户评级,例如年龄,gen,mar_sta和occ ......

数据集:

user    age gender  mar_sta occ rating
A   Young   M   married eng     PG13
B   adult   M   married doc      R
C   teen    M   single  clerk   NR
D   old     M   married retired  U
E   Young   F   married eng    PG13
F   adult   F   married doc     R
G   teen    F   single  clerk   NR
H   old     F   married retired U
I   Young   M   single  eng    PG13
J   adult   M   single  doc     R
K   teen    M   single  clerk   NR
L   old     M   single  retired U
M   Young   F   single  eng    PG13
N   adult   F   single  doc     R
O   teen    F   single  clerk   NR
P   old     F   single  retired U

这是我的数据库,我发送一个新用户的数据,并尝试按顺序找到最受关注的评级。

新用户:

user age gender mar_sta  occ rating
X   teen   M    single   clerk  ?
Y    Nan   F    single    eng    ?

我正在尝试使用我的数据集为新用户分配评级。数据中有空值,因此我必须忽略空值并考虑存在哪些值并指定评级。

对于用户Y,我有年龄的纳米..所以我的代码应该忽略年龄变量,只考虑gendermar_staocc,并找到most watched rating

预期产量:

X : NR
Y : PG13
python pandas pandas-groupby
1个回答
0
投票

此代码应为您尝试执行的操作提供基本的起点。它将根据其他列返回该用户的正确“最受关注的评级”。

df = < your dataframe >

age_val = 'teen'
gender_val = 'M'
mar_sta = 'single'
occ = 'clerk'

frames = []

if age_val != None:
    age = df.groupby(['age', 'rating']).rating.count()['teen']
    frames.append(age)

if gender_val != None:
    gender = df.groupby(['gender', 'rating']).rating.count()['M']
    frames.append(gender)

if mar_sta != None:
    mar_sta = df.groupby(['mar_sta', 'rating']).rating.count()['single']
    frames.append(mar_sta)

if occ != None:
    occ = df.groupby(['occ', 'rating']).rating.count()['clerk']
    frames.append(occ)

result_table = pd.concat(frames).groupby(level=0).sum().fillna(0)
result_rating = result_table.idxmax()

您需要添加代码以从表中的“用户X”中提取各个字段,并且如果它们是NaN /无效,则将开头的变量设置为“无”。然后,您需要使用result_rating中的值设置User X的评级字段。

© www.soinside.com 2019 - 2024. All rights reserved.