Skip to content
Advertisement

Convert a pandas df to defaultdict and look for matching positive and negative numbers

I have a dataframe like this:

JavaScript

What i want to do know i convert the df into a defaultdict and look for only the matching matching positive and negative numbers per id so i want my desired dict to look something like this:

JavaScript

I try to do this below but i get this error:

JavaScript

Any idea how to solve this would be very appreciated. Thanks!

Advertisement

Answer

In pandas iterrows is not recommneded, check this answer. Alternative pandas only solution with same logic like your solution – per groups test if at least one match, filter by boolean indexing and convert to dictioanry per id with DataFrame.to_dict:

JavaScript

Or is possible filter all duplicated with absolute amount, but also is necessary test if exist negative with DataFrameGroupBy.nunique per groups:

JavaScript

If small DataFrame and performance not important need test values per groups by id, for test use == with Series.any:

JavaScript

Performance in 10k rows and 1k groups, last solution is slowiest:

JavaScript

JavaScript

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement