首页 > 解决方案 > 查找数据框所有列的唯一值

问题描述

如何获取数据框中所有列的唯一值?到目前为止,我正在尝试做类似下面的事情。

for col in train_features_df.columns:
    print(train_features_df.col.unique())

但这给了我错误AttributeError: 'DataFrame' object has no attribute 'col'

例如对于下面的数据框,我想要下面的输出

 df = pd.DataFrame({'A':[1,1,3],
               'B':[4,5,6],
               'C':[7,7,7]})

我希望 A 的输出为 1,3 , B 的输出为 4,5,6 , C 的输出为 7 。

标签: pythonpandasdataframe

解决方案


您可以unique通过转置来应用每个系列,

>>> df
   A  B  C
0  1  4  7
1  1  5  7
2  3  6  7
>>> df.T.apply(lambda x: x.unique(), axis=1)
A       [1, 3]
B    [4, 5, 6]
C          [7]
dtype: object
>>> 

推荐阅读