查找数据框所有列的唯一值

问题描述 投票:0回答:3

如何获取数据框中所有列的唯一值? 我现在正在尝试做如下的事情。

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。

python pandas dataframe
3个回答
4
投票

您可以通过转置将

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
>>> 

0
投票

您可以尝试

for loop
drop_duplicates()
来获得您想要的结果,无需使用任何复杂的功能。

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

for i in df.columns:
    print(f'{i} : {list(df[i].drop_duplicates())}')

输出如下:

A : [1, 3]
B : [4, 5, 6]
C : [7]

0
投票

使用

df.apply(pd.unique)
获得更易读的代码,其输出与 接受的答案相同,并且速度稍快

df.apply(pd.unique)

374 μs ± 3.53 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
# accepted answer
df.T.apply(lambda x: x.unique(), axis=1)

388 μs ± 3.72 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
© www.soinside.com 2019 - 2024. All rights reserved.