【发布时间】:2018-04-21 17:42:26
【问题描述】:
这似乎是一种奇怪且违反直觉的行为。谁能解释一下为什么会这样设计?
lkup = pd.Series({'fred':'Fred','amy':'Amy'})
for n in lkup:
print(n,' --> ',n in lkup)
>>>
Amy --> False
Fred --> False
为什么它给我 Values 而不是键?
'fred' in lkup, 'amy' in lkup
>>>> True, True
我问的原因是,在将值从 DataFrame 映射到 Series 中的值时,这实际上弄乱了我的程序
df = pd.DataFrame([['fred',1,2,3],['amy',3,4,5],['john',5,6,7],['Fred',11,12,33]], columns=['name','c1','c2','c3'])
df
>>>
name c1 c2 c3
0 fred 1 2 3
1 amy 3 4 5
2 john 5 6 7
3 Fred 11 12 33
df.name.map(lkup)
>>>
0 Fred
1 Amy
2 NaN
3 NaN
很棒 - 正如预期的那样:
lkup.to_dict()
>>> {'amy': 'Amy', 'fred': 'Fred'}
但是当我这样做时
df[df.name.isin('lkup')].name
>>> 3 Fred
使用 DataFrames 我没有这个问题。
for n in df:
print(n,' --> ',n in df)
>>>
name --> True
c1 --> True
c2 --> True
c3 --> True
这种矛盾逻辑的原因是什么?
【问题讨论】:
-
对 Series 的迭代会遍历这些值。对 DataFrame 的迭代会遍历列名。
-
in的行为更加一致:item in series等价于item in series.index,item in df等价于item in df.columns。