简体   繁体   中英

Pandas : new column with index of unique values of another column

My dataframe:

ID       Name_Identify  ColumnA  ColumnB  ColumnC
1        POM-OPP        D43      D03      D59
2        MIAN-ERP       D80      D74      E34
3        POM-OPP        E97      B56      A01
4        POM-OPP        A66      D04      C34
5        DONP28         B55      A42      A80
6        MIAN-ERP       E97      D59      C34

Expected new dataframe:

ID       Name_Identify ColumnA  ColumnB  ColumnC    NEW_ID
1        POM-OPP       D43      D03      D59        1
2        MIAN-ERP      D80      D74      E34        2
3        POM-OPP       E97      B56      A01        1
4        POM-OPP       A66      D04      C34        1
5        DONP28        B55      A42      A80        3
6        MIAN-ERP      E97      D59      C34        2

您可以使用pandas.Categorical

df["NEW_ID"] = pd.Categorical(df["Name_Identify"], ordered=False).codes + 1

You can use pandas.groupby :

df['NEW_ID'] = df.groupby('Name_Identify', sort=False).ngroup() + 1
print(df)

Prints:

   ID Name_Identify ColumnA ColumnB ColumnC  NEW_ID
0   1       POM-OPP     D43     D03     D59       1
1   2      MIAN-ERP     D80     D74     E34       2
2   3       POM-OPP     E97     B56     A01       1
3   4       POM-OPP     A66     D04     C34       1
4   5        DONP28     B55     A42     A80       3
5   6      MIAN-ERP     E97     D59     C34       2
convert = {k: v for v, k in enumerate(df.Name_Identify.unique(), start=1)}
df["NEW_ID"] = df.Name_Identify.map(convert)

The explanation:

In the first command we select unique names from the Name_Identify column

In[23]: df.Name_Identify.unique()
 array(['POM-OPP', 'MIAN-ERP', 'DONP28'], dtype=object)

and then create a dictionary from the enumerated sequence of them (the enumeration starts with 1 ):

In[24]: convert = {k: v for v, k in enumerate(df.Name_Identify.unique(), start=1)}
In[25]: convert
 {'POM-OPP': 1, 'MIAN-ERP': 2, 'DONP28': 3}

In the second command we use this dictionary for creating a new column by converting all names in the Name_Identify column to appropriate numbers:

In[26]: df["NEW_ID"] = df.Name_Identify.map(convert)
In[27]: df
 D Name_Identify ColumnA ColumnB ColumnC NEW_ID 0 1 POM-OPP D43 D03 D59 1 1 2 MIAN-ERP D80 D74 E34 2 2 3 POM-OPP E97 B56 A01 1 3 4 POM-OPP A66 D04 C34 1 4 5 DONP28 B55 A42 A80 3 5 6 MIAN-ERP E97 D59 C34 2

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM