【发布时间】:2016-05-11 23:44:33
【问题描述】:
我正在尝试在 pandas DataFrame 中进行一些比较。
# create simple DataFrame
df = pd.DataFrame(['one', 'two', 'three'], range(1,4), columns=['col1'])
#df:
# col1
#1 one
#2 two
#3 three
# assign one col1 value to be NAN
df.loc[1, 'col1'] = np.nan
# this comparison works
print(df['col1'] == 'three')
# assign all col1 values to NAN
df.loc[:, 'col1'] = np.nan
# this comparison fails
print(df['col1'] == 'three')
第一个比较(列中只有一个 NAN 值)按预期工作,但第二个比较(列中所有 NAN 值)产生此错误:TypeError: invalid type comparison
这里发生了什么?
我看到了这个question,它为这个问题提出了一些可能但有点破解的解决方案。
但为什么会发生这种行为呢?不知何故,这个限制有用吗?我可以在比较之前使用df.fillna('') 来修复它,但这看起来很笨拙且令人恼火。
所以我的问题是:
1. 解决这个问题最干净的方法是什么?
2. 为什么这是默认行为?
【问题讨论】: