如何获取数据框中所有列的唯一值?
到目前为止,我正在尝试做类似下面的事情。
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 。
最佳答案
您可以申请 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
>>>
关于python - 查找数据框所有列的唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63101261/