Jef*_*ist 2 python dictionary pandas
我有字典
d = {1:a,2:a}
Run Code Online (Sandbox Code Playgroud)
我也有一个熊猫框架“df”
0 x y
1 1 10
2 2 56
Run Code Online (Sandbox Code Playgroud)
出于某种原因,我无法将 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"
Run Code Online (Sandbox Code Playgroud)
我得到的只是“找不到匹配项”。有什么我做错了吗?pandas系列中的数据是“float64”,字典中的key是“int”,但是我把pandas系列转为int,还是无法匹配到这些项。任何帮助表示赞赏。
谢谢
如果要根据字典创建新列,可以使用pandas.Series.map:
>>> df['n'] = df['x'].map(d)
>>> df
x y n
1 1 10 val1
2 10 56 NaN
Run Code Online (Sandbox Code Playgroud)