我正在尝试在 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. 为什么这是默认行为?
最佳答案
在分配所有 np.nan
之后,您的 col1
是 float
类型,因此尝试与 string
进行比较抛出一个 TypeError
。 :
df = pd.DataFrame(['one', 'two', 'three'], range(1, 4), columns=['col1'])
df.loc[1, 'col1'] = np.nan
col1
1 NaN
2 two
3 three
将单个 np.nan
分配给包含 string
值的列会留下 dtype
对象:
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 1 to 3
Data columns (total 1 columns):
col1 2 non-null object
dtypes: object(1)
但所有 np.nan
值都会转换为 float
:
df.loc[:, 'col1'] = np.nan
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 1 to 3
Data columns (total 1 columns):
col1 0 non-null float64
dtypes: float64(1)
关于python - 使用 NaN 的 DataFrame 逻辑运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37175007/