Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas: concise way of finding and writing unique occurrences

For a dataframe such as this:

Col1 Col2
1 A D
2 B A
3 C B

Desired outcome:

Unique occurrences of values in Col1 and Col2 in order of appearance by row

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

i.e. unique_list = [A, D, B, C]

Problem

Way to minimise iteration and processing due to number and size of dataframes

>Solution :

Use DataFrame.iloc for select first 2 columns, reshape by DataFrame.stack and get unique values in Series.unique:

unique_list = df.iloc[:, :2].stack().unique().tolist()
print (unique_list)
['A', 'D', 'B', 'C']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading