简体   繁体   中英

In Pandas, how to create a unique ID based on the combination of many columns?

I have a very large dataset, that looks like

df = pd.DataFrame({'B': ['john smith', 'john doe', 'adam smith', 'john doe', np.nan], 'C': ['indiana jones', 'duck mc duck', 'batman','duck mc duck',np.nan]})

df
Out[173]: 
            B              C
0  john smith  indiana jones
1    john doe   duck mc duck
2  adam smith         batman
3    john doe   duck mc duck
4         NaN            NaN

I need to create a ID variable, that is unique for every BC combination. That is, the output should be

            B              C   ID
0  john smith  indiana jones   1
1    john doe   duck mc duck   2
2  adam smith         batman   3
3    john doe   duck mc duck   2 
4         NaN            NaN   0

I actually dont care about whether the index starts at zero or not, and whether the value for the missing columns is 0 or any other number. I just want something fast, that does not take a lot of memory and can be sorted quickly. I use:

df['combined_id']=(df.B+df.C).rank(method='dense')

but the output is float64 and takes a lot of memory. Can we do better? Thanks!

I think you can use factorize :

df['combined_id'] = pd.factorize(df.B+df.C)[0]
print df
            B              C  combined_id
0  john smith  indiana jones            0
1    john doe   duck mc duck            1
2  adam smith         batman            2
3    john doe   duck mc duck            1
4         NaN            NaN           -1

Making jezrael's answer a little more general (what if the columns were not string?), you can use this compact function:

def make_identifier(df):
    str_id = df.apply(lambda x: '_'.join(map(str, x)), axis=1)
    return pd.factorize(str_id)[0]

df['combined_id'] = make_identifier(df[['B','C']])

I have a very large dataset, that looks like

df = pd.DataFrame({'B': ['john smith', 'john doe', 'adam smith', 'john doe', np.nan], 'C': ['indiana jones', 'duck mc duck', 'batman','duck mc duck',np.nan]})

df
Out[173]: 
            B              C
0  john smith  indiana jones
1    john doe   duck mc duck
2  adam smith         batman
3    john doe   duck mc duck
4         NaN            NaN

I need to create a ID variable, that is unique for every BC combination. That is, the output should be

            B              C   ID
0  john smith  indiana jones   1
1    john doe   duck mc duck   2
2  adam smith         batman   3
3    john doe   duck mc duck   2 
4         NaN            NaN   0

I actually dont care about whether the index starts at zero or not, and whether the value for the missing columns is 0 or any other number. I just want something fast, that does not take a lot of memory and can be sorted quickly. I use:

df['combined_id']=(df.B+df.C).rank(method='dense')

but the output is float64 and takes a lot of memory. Can we do better? Thanks!

jezrael's answer is great. But since this is for multiple columns, I prefer to use .ngroup() since this way NaN could remain NaN.

df['combined_id'] = df.groupby(['B', 'C'], sort = False).ngroup()
df

在此处输入图像描述

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