python - 使用 NaN 的 DataFrame 逻辑运算

标签 python numpy pandas

我正在尝试在 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 之后,您的 col1float 类型,因此尝试与 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/

相关文章:

python - 将 Numpy 数组传递给 C 函数以进行输入和输出

python - 从逐笔报价数据到烛台

python - 导入模块 : __main__ vs import as module

python - 列的 Pandas 数据框总和并收集结果

python - 为什么 numba 在 numpy linspace 中引发类型错误

python - 仅通过 Pandas 数据框中的某些键聚合列?

python - Pandas 在 Groupby 中重新索引日期

python - 如何在 SQLite 数据库中存储 pandas DataFrame

python - 自动登录脚本需要使用存储在txt文件中的多个帐户登录

python - 使用PythonKit快速调用Python