我有一些代码,例如,下面是我的 df 的列。
df.columns = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2', 'E1', 'E2']
list = df.columns.str[:1]
list = np.unique(list)
我正在尝试获取字母和数字的唯一值,但顺序正确。
我的代码不维护顺序,我不知道该怎么做。
谢谢
预期输出:
letters = [A, B, C, D, E]
numbers = [1, 2]
最佳答案
假设您的示例具有代表性,您可以使用我从 Raymond Hettinger 获得的巧妙小技巧.在 python 3.6 及更高版本中,字典是有序的,因此您可以将它们的键用作高效的有序集。
list(dict.fromkeys(c[0] for c in df.columns))
# --> ['A', 'B', 'C', 'D', 'E']
list(dict.fromkeys(int(c[1]) for c in df.columns))
# --> [1, 2]
关于python - 在 python 中使用 unique 函数时保持顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52061661/