我有一本字典:
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]}
和一个pandas数据帧:
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
我需要做的是"匹配"字典中每个键内的值,其值为"值" pandas数据帧的列,然后将字典中的值替换为与列名对应的值。
知道如何到达那里吗?
非常感谢
答案 0 :(得分:0)
# 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']}