Pandas - 将列值与字典中的值进行比较

时间:2016-12-23 21:56:42

标签: python pandas dictionary

我有一本字典

d = {1:a,2:a}

我还有一个熊猫框架“df”

0 x y
1 1 10
2 2 56

由于某种原因,我无法将x值与字典键匹配:

for index, row in df.iterrows():
    for x,y in d.items():
        if row['x'] == x:
            print "Got a Match"
        else:
            print "No Match Found"

我得到的只是“找不到匹配”。有什么我做错了吗?大熊猫系列中的数据是“float64”,字典中的键是“int”,但我将pandas系列转换为int,但仍然无法匹配这些项目。任何帮助表示赞赏。

由于

2 个答案:

答案 0 :(得分:3)

如果要根据字典创建新列,可以使用pandas.Series.map

>>> df['n'] = df['x'].map(d)
>>> df
    x   y     n
1   1  10  val1
2  10  56   NaN

答案 1 :(得分:0)

考虑这个df

   x   y
0       
1  1  10
2  2  56
3  3  11

和字典

d = {1: 'a', 2: 'a'}

当您使用pd.Series.map时,它会填充它可以的位置并返回NaN,其中不存在密钥。这对于识别x匹配的位置以及稍后替换值非常有用。

df.x.map(d)

0
1      a
2      a
3    NaN
Name: x, dtype: object
d_ = {k: 'Match!' for k, _ in d.items()}
df.x.map(d_).fillna('No Match :-(')

0
1          Match!
2          Match!
3    No Match :-(
Name: x, dtype: object
相关问题