簡體   English   中英

按升序重命名唯一值 pandas 列

[英]Rename unique values pandas column in ascending order

我有一個 pandas DataFrame 看起來類似於下面的一個:

df = pd.DataFrame({
    'label': [0, 0, 2, 3, 8, 8, 9],
    'value1': [2, 1, 9, 8, 7, 4, 2],
    'value2': [0, 1, 9, 4, 2, 3, 1],
})
>>> df
   label  value1  value2
0      0       2       0
1      0       1       1
2      2       9       9
3      3       8       4
4      8       7       2
5      8       4       3
6      9       2       1

由於之前的切片, label列中的值不完整(不是range(0, n, 1) )。 我想重新排序這個 label 並分配一個連續的升序范圍,使其變為:

>>> df
   label  value1  value2
0      1       2       0
1      1       1       1
2      2       9       9
3      3       8       4
4      4       7       2
5      4       4       3
6      5       2       1

我目前使用下面的代碼。 因為我真正的 DataFrame 有數千個唯一值,所以任何建議更有效地執行此操作(不包括遍歷每個唯一值)都將不勝感激。

for new_idx, idx in enumerate(df.label.unique()):
     df.loc[df['label'] == idx, ['label']] = new_idx

提前致謝

使用factorize來提高性能:

df['label'] = pd.factorize(df['label'])[0] + 1
print (df)
   label  value1  value2
0      1       2       0
1      1       1       1
2      2       9       9
3      3       8       4
4      4       7       2
5      4       4       3
6      5       2       1

Series.rank的另一個想法:

df['label'] = df['label'].rank(method='dense').astype(int)
print (df)
   label  value1  value2
0      1       2       0
1      1       1       1
2      2       9       9
3      3       8       4
4      4       7       2
5      4       4       3
6      5       2       1

僅對相同的順序工作相同:

#dta changed for see difference
df = pd.DataFrame({
    'label': [0, 10, 10, 3, 8, 8, 9],
    'value1': [2, 1, 9, 8, 7, 4, 2],
    'value2': [0, 1, 9, 4, 2, 3, 1],
})

df['label1'] = pd.factorize(df['label'])[0] + 1
df['label2'] = df['label'].rank(method='dense').astype(int)
print (df)
   label  value1  value2  label1  label2
0      0       2       0       1       1
1     10       1       1       2       5
2     10       9       9       2       5
3      3       8       4       3       2
4      8       7       2       4       3
5      8       4       3       4       3
6      9       2       1       5       4

暫無
暫無

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

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