简体   繁体   中英

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

Suppose I have a pandas data frame with 2 columns.

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 ). My final output should be 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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