简体   繁体   English

如何获取熊猫中两列的组合唯一值的数量

[英]How to get the number of combined unique values for two columns in pandas

Suppose I have a pandas data frame with 2 columns. 假设我有一个2列的pandas数据框。

I want to count the distinct or unique values for both columns - ie col1 having 1,3 and col2 having 2,4 ( 1 was already counted in col1 ). 我想计算两列的不同值或唯一值-即col1具有1,3和col2具有2,4( 1已在col1进行计数)。 My final output should be 4. 我的最终输出应该是4。

How can I achieve this? 我该如何实现?

tr=pd.DataFrame({"Col1":[1,1,1,1,3,3],"Col2":[1,2,2,2,4,4]})
print (tr)

As per @Vaishali's comment, you need: 根据@Vaishali的评论,您需要:

import pandas as pd

tr = pd.DataFrame({"Col1":[1,1,1,1,3,3],"Col2":[1,2,2,2,4,4]})

Out = tr.stack().nunique()
print(Out)
4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM