我有一个字典,其中值是列表:
dict = {1: ['a','b'], 2:['c', 'd']}
我想将字典映射到我的数据框的col1列上。
col1
a
c
如果 col1 的值在我的字典值之一中,那么我想用字典键的值替换 col1 的值。
像这样,我的数据框将变成:
col1
1
2
thanks in advance
我有一个字典,其中值是列表:
dict = {1: ['a','b'], 2:['c', 'd']}
col1
a
c
col1
1
2
thanks in advance
mapping = {}
for key, values in D.items():
for item in values:
mapping[item] = key
然后
df['col1'] = df['col1'].map(mapping)
stack
+reset_index
和set_index
与map
。d = pd.DataFrame({1: ['a','b'], 2:['c', 'd']})
mapping = d.stack().reset_index().set_index(0)["level_1"]
s = pd.Series(['a', 'c'], name="col1")
s.map(mapping)
0 1
1 2
Name: col1, dtype: int64
d.stack()
0 1 a
2 c
1 1 b
2 d
dtype: object
d.stack().reset_index()
level_0 level_1 0
0 0 1 a
1 0 2 c
2 1 1 b
3 1 2 d
d.stack().reset_index().set_index(0)
level_0 level_1
0
a 0 1
c 0 2
b 1 1
d 1 2
level_1
列作为我们传递给map
函数的映射。你是指像这样吗?
D = {1 : ['a', 'b'], 2 : ['c', 'd']}
for key, value in D.items():
for each in value:
if each in D[key]:
print(each, "is in D[%s]" % key)
输出:
a is in D[1]
b is in D[1]
c is in D[2]
d is in D[2]