python - 在 python 中使用 unique 函数时保持顺序

标签 python pandas numpy dataframe indexing

我有一些代码,例如,下面是我的 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/

相关文章:

python - 将类别列转换为 Python 中的一个字符串列

python - 在Python中将300个CSV文件转换为一个二维数组

python - 在Python中将小于某个阈值的相对频率标记为异常值

python - 从 numpy 数组中删除 "nan"值

python - 如何修复属性错误: 'Web3' object has no attribute 'toChecksumAddress' ?

python - 插入 MySQL 时出现 Unicode 错误

python - 读取包含特定列的 CSV 并保留到最后一列

python - 如何从 matplotlib 中的 AxesSubplot 对象获取 BarContainer 对象?

python - 如何将 IP 转换为向量值

python - Pandas 重新映射到列中的范围