简体   繁体   中英

Collecting all values within the dictionary in Python?

Given df_dict :

{1:
pair1          pair2          ref          value
A              B              r1           0.7
A              B              r2           0.5
A              C              r1           0.4
B              C              r1           0.2
B              C              r3           0.9
...

2:
pair1          pair2          ref          value
A              B              r6           0.3
A              B              r9           0.1
A              C              r6           0.2
A              D              r7           0.8
B              D              r8           0.2       
...

3:
pair1          pair2          ref          value
A              B              r12          0.1
A              C              r12          0.2
A              E              r12          0.1
B              C              r13          0.1
C              D              r12          0.5
}    

I would like to get all ref s and value s for each pair of pair1 and pair2 throughout the entire df_dict . For example, (pair1, pair2) = (A,B) should return the collection of ref of ['r1', 'r2', 'r6', 'r9', 'r12'] , and the collection of value of ['0.7', '0.5', '0.3', '0.1', '0.1'] from the case above.

If I understand you correctly, you have a multiple data sets looking similar to this:

d1 = {'pair1':['A', 'A', 'A', 'B', 'B'],
      'pair2':['B', 'B', 'C', 'C', 'C'],
      'ref':['r1', 'r2', 'r1', 'r1', 'r3'],
      'value':[0.7, 0.5, 0.4, 0.2, 0.9]}

You have taken them in a Pandas DataFrame and added them again to a dictionary, similar to this:

df1 = pd.DataFrame(data=d1)
df_dict = {1:df1}

Consider then this:

values = []
for key in df_dict.keys():
    df = df_dict[key]
    df = df.loc[df['pair1'] == 'A',:]
    df = df.loc[df['pair2'] == 'B', 'value']
    for elem in list(df):
        values.append(elem)

print(values)

Out: [0.7, 0.5]

Is this what you were looking for? If so I think you'll find any expansion to cover your requirements fully to be trivial.

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