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:
JavaScript
x
11
11
1
a = []
2
pl = []
3
pl1 = []
4
for i in list(data.index):
5
a.append(data["parallels"][i].astype(str))
6
if a[i] != 'nan':
7
pl1.append(i)
8
pl.append(a[i])
9
if i > list(data.index)[i]: break
10
parl1 = dict(zip(pl1,pl))
11
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
JavaScript
1
12
12
1
v = {}
2
3
for key, value in d.items():
4
v.setdefault(value, set()).add(key)
5
6
print(v)
7
8
import pandas as pd
9
10
print(pd.DataFrame({'val': list(v.keys()), 'equal_keys': list(v.values())}))
11
12
JavaScript
1
5
1
{'2.0': {2, 4}, '1.0': {3, 5}}
2
val equal_keys
3
0 2.0 {2, 4}
4
1 1.0 {3, 5}
5
Other than this, maybe you want to use pandas groupby and aggregate all indices
JavaScript
1
3
1
# just an example did not check for errors
2
df.groupby('parallel').index.agg(list)
3