如何在python中为未来的输入变量创建条件



我有一个如下的数据帧:

df1:
Pan_no.     Last_broker_cat
Xxx             Mutual fund
Yyy            National distributor
ZZZ            National Distributor
Aaa              Debt champion
BBB            National distributor
Ccc              Debt champion

我将Last_broker_cat列的每个值映射到一个唯一的数字:

df1['Last_broker_cat] = df1['Last_broker_cat].map({'National distributor':1,'Mutual fund':2, 'debt_champion :3})

现在我的df1看起来如下:

df1
Pan_no.     Last_broker_cat
Xxx            2
Yyy            1
ZZZ            1
Aaa            3
BBB            1
Ccc            3

现在我有一个条件:

在未来的输入变量中,如果Last_broker_cat列中除了现有值之外还有任何新值,我需要为其分配唯一的编号,该编号已分配给数据帧中出现次数最少的值。例如,在我们的数据帧中,出现次数最少的值是2,因此将来出现的任何新值都应该分配最小的值。如何在python中编码此条件?

试试这个

df['Last_broker_cat'] = pd.factorize(df['Last_broker_cat'])[0]

但唯一值从0到n个唯一值开始。

最新更新