python - 查找数据框所有列的唯一值
问题描述
如何获取数据框中所有列的唯一值?到目前为止,我正在尝试做类似下面的事情。
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 - 函数 norm.pdf 的工作原理
- javascript - javascript函数后提交按钮未在asp.net中触发
- java - IntelliJ 中的 Spring 应用程序不适用于 tomcat
- java - SpockFramework Global Mocks 未按预期工作
- html - 在没有垂直移位的jupyter笔记本中使用html居中文本
- r - ggplot中缺少具有连续比例和远程桌面的颜色条
- opencart - 当 OpenCart 3.0.2.0 的购物篮至少为 10 美元时,如何下订单?
- python - 如何在 Robot Framework 中添加 Chrome 扩展
- excel - 对象分配问题——为什么 Sheets([SheetName]) 不起作用?
- javascript - JavaScript:如何组合 2 个数组并保持相同的索引