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
# 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']}
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.