簡體   English   中英

將唯一 ID 分配給 Pandas 數據框中兩列的組合,按其順序獨立

[英]Assign unique ID to combination of two columns in pandas dataframe independently on their order

我有一個這樣的數據框

col1 col2
1    2
2    1
2    3
3    2
3    4
4    3

我想為每一行分配一個基於 col1 和 col2 但獨立於它們的順序的唯一數據集

col1 col2 id
1    2    1
2    1    1
2    3    2
3    2    2
3    4    3
4    3    3

我怎樣才能做到這一點?

一種方法:

df["id"] = df.groupby(df[["col1", "col2"]].apply(frozenset, axis=1)).ngroup() + 1
print(df)

輸出

   col1  col2  id
0     1     2   1
1     2     1   1
2     2     3   2
3     3     2   2
4     3     4   3
5     4     3   3

使用np.unique + np.sort替代方法:

_, indices = np.unique(np.sort(df.values, axis=1), return_inverse=True, axis=0)
df["id"] = indices + 1
print(df)

輸出

   col1  col2  id
0     1     2   1
1     2     1   1
2     2     3   2
3     3     2   2
4     3     4   3
5     4     3   3

你可以apply它:

import pandas as pd

df = pd.DataFrame(data={"col1":[1,2,3,1,2,3], "col2":[3,2,1,3,2,1]})
df['id'] = df.apply(lambda row: min(row.col1, row.col2), axis=1)
print(df)

輸出:

   col1  col2  id
0     1     3   1
1     2     2   2
2     3     1   1
3     1     3   1
4     2     2   2
5     3     1   1

試試np.sort

a = np.sort(df, axis=1)
df['id'] = df.groupby([a[:,0],a[:,1]]).ngroup() + 1

輸出:

   col1  col2  id
0     1     2   1
1     2     1   1
2     2     3   2
3     3     2   2
4     3     4   3
5     4     3   3

還可以使用:

df['mask'] = df.apply(lambda x:','.join(map(str, x.sort_values())), axis=1)
df['id'] = (df['mask'] != df['mask'].shift()).cumsum()
df.drop(columns=['mask'], inplace=True)

輸出:

   col1  col2  id
0     1     2   1
1     2     1   1
2     2     3   2
3     3     2   2
4     3     4   3
5     4     3   3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM