Blue Moon
Blue Moon

Reputation: 4651

How to match dictionary values to pandas Data Frame values?

I have one dictionary:

dictionary = {"A": [1, 2, 3, 4, 5, 6, 7, 8], 
"B": [1, 2, 3, 4,], "C": [1, 2, 3, 4, 5, 6, 7],
"D": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 
"E": [1, 2, 3, 4, 5, 6]}

and one pandas dataframe:

    name  value
0    one      1
1    two      2
2  three      3
3   four      4
4   five      5
5    six      6
6  seven      7
7  eight      8
8   nine      9
9    ten     10

What I need to do is to "match" the values inside each key in the dictionary with the values in the "value" column of the pandas dataframe and then substitute the values inside the dictionary with those corresponding to the column name.

Any idea how to get there?

Many thanks

Upvotes: 0

Views: 3437

Answers (1)

Jianxun Li
Jianxun Li

Reputation: 24742

# your data
# ===================================
dictionary = {"A": [1, 2, 3, 4, 5, 6, 7, 8], 
"B": [1, 2, 3, 4,], "C": [1, 2, 3, 4, 5, 6, 7],
"D": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 
"E": [1, 2, 3, 4, 5, 6]}

df

    name  value
0    one      1
1    two      2
2  three      3
3   four      4
4   five      5
5    six      6
6  seven      7
7  eight      8
8   nine      9
9    ten     10

# processing
# ===================================
df1 = df.set_index('value')

for key in dictionary.keys():
    dictionary[key] = df1.loc[dictionary[key]].values.ravel().tolist()

print(dictionary)


{'A': ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'], 'B': ['one', 'two', 'three', 'four'], 'E': ['one', 'two', 'three', 'four', 'five', 'six'], 'D': ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'], 'C': ['one', 'two', 'three', 'four', 'five', 'six', 'seven']}

Upvotes: 2

Related Questions