如何重命名或标记具有与唯一编号相同值的 2 列的数据。例如
这是我的示例数据:
col1 col2
A1 B1
A1 C1
A1 B2
B1 C2
C2 D1
预期:
col1 col2 new_col1 new_col2
A1 B1 1 2
A1 C1 1 3
A1 B2 1 4
B1 C2 2 5
C2 D1 5 6
对于这种情况有什么指导方针吗?我正在考虑 np.random
但它只能定义一列
最佳答案
使用factorize
将 DataFrame reshape 为 MultiIndex Series
by DataFrame.stack
:
s = df.stack()
df = df.join(pd.Series(pd.factorize(s)[0] + 1, index=s.index).unstack().add_prefix('new_'))
print (df)
col1 col2 new_col1 new_col2
0 A1 B1 1 2
1 A1 C1 1 3
2 A1 B2 1 4
3 B1 C2 2 5
4 C2 D1 5 6
关于python - 如何将每一行中的数据重命名为pandas中的唯一编号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59728705/