I have 2 columns: one is the Pandas DateTime Dataframe (data["start"]
) and the second is the tags, data["parallels"]
for example. So i’m going to create a dictionary, like this:
a = [] pl = [] pl1 = [] for i in list(data.index): a.append(data["parallels"][i].astype(str)) if a[i] != 'nan': pl1.append(i) pl.append(a[i]) if i > list(data.index)[i]: break parl1 = dict(zip(pl1,pl))
So, the output dictionary is: {3: '1.0', 5: '1.0'}
How can i check this dictionary if the values is equal (in the example both are) and after checking write down keys. The output keys i’m going to use as index by making equal column data["start")[5] == data["start][3]
I wonder how to do it automatically, if there are {2: '2.0', 3: '1.0', 4: '2.0', 5: '1.0'}
dict for example.
Advertisement
Answer
Reverse the dictionary so that keys can be grouped together
v = {} for key, value in d.items(): v.setdefault(value, set()).add(key) print(v) import pandas as pd print(pd.DataFrame({'val': list(v.keys()), 'equal_keys': list(v.values())}))
{'2.0': {2, 4}, '1.0': {3, 5}} val equal_keys 0 2.0 {2, 4} 1 1.0 {3, 5}
Other than this, maybe you want to use pandas groupby and aggregate all indices
# just an example did not check for errors df.groupby('parallel').index.agg(list)