在 Pandas 数据框中将元素设置为 None

use*_*737 2 python dataframe pandas

我不确定为什么会这样

>>> df = pd.DataFrame(np.arange(15).reshape(5,3),columns=list('ABC'))
>>> df
    A   B   C
0   0   1   2
1   3   4   5
2   6   7   8
3   9  10  11
4  12  13  14
Run Code Online (Sandbox Code Playgroud)

分配None给最后一行的元素将其变为NaN NaN NaN

>>> df.ix[5,:] = None
>>> df
    A   B   C
0   0   1   2
1   3   4   5
2   6   7   8
3   9  10  11
4  12  13  14
5 NaN NaN NaN
Run Code Online (Sandbox Code Playgroud)

将最后一列中的两个元素更改为“nan”

>>> df.ix[:1,2] = 'nan'
>>> df
    A   B    C
0   0   1  nan
1   3   4  nan
2   6   7    8
3   9  10   11
4  12  13   14
5 NaN NaN  NaN
Run Code Online (Sandbox Code Playgroud)

现在最后一行变成 NaN NaN None

>>> df.ix[5,:] = None
>>> df
    A   B     C
0   0   1   nan
1   3   4   nan
2   6   7     8
3   9  10    11
4  12  13    14
5 NaN NaN  None
Run Code Online (Sandbox Code Playgroud)

Max*_*axU 5

这是因为您的 dtypes 在每次分配后都会发生变化:

In [7]: df = pd.DataFrame(np.arange(15).reshape(5,3),columns=list('ABC'))

In [8]: df.dtypes
Out[8]:
A    int32
B    int32
C    int32
dtype: object

In [9]: df.loc[5,:] = None

In [10]: df.dtypes
Out[10]:
A    float64
B    float64
C    float64
dtype: object

In [11]: df.loc[:1,2] = 'nan'
Run Code Online (Sandbox Code Playgroud)

在最后一次赋值之后,该C列已隐式转换为object(string) dtype:

In [12]: df.dtypes
Out[12]:
A    float64
B    float64
C     object
dtype: object
Run Code Online (Sandbox Code Playgroud)

@ayhan 写了非常简洁的答案作为评论

我认为主要原因是数字列,当您插入 None 或 np.nan 时,它会转换为 np.nan 以具有类型为 float 的系列。对于对象,它接受传递的任何内容(如果 None,它使用 None;如果 np.nan,它使用 np.nan - docs

(c)艾汗

这是一个相应的演示:

In [39]: df = pd.DataFrame(np.arange(15).reshape(5,3),columns=list('ABC'))

In [40]: df.loc[4, 'A'] = None

In [41]: df.loc[4, 'C'] = np.nan

In [42]: df
Out[42]:
     A   B     C
0  0.0   1   2.0
1  3.0   4   5.0
2  6.0   7   8.0
3  9.0  10  11.0
4  NaN  13   NaN

In [43]: df.dtypes
Out[43]:
A    float64
B      int32
C    float64
dtype: object

In [44]: df.loc[0, 'C'] = 'a string'

In [45]: df
Out[45]:
     A   B         C
0  0.0   1  a string
1  3.0   4         5
2  6.0   7         8
3  9.0  10        11
4  NaN  13       NaN

In [46]: df.dtypes
Out[46]:
A    float64
B      int32
C     object
dtype: object
Run Code Online (Sandbox Code Playgroud)

现在我们可以同时使用Nonenp.nan用于objectdtype:

In [47]: df.loc[1, 'C'] = None

In [48]: df.loc[2, 'C'] = np.nan

In [49]: df
Out[49]:
     A   B         C
0  0.0   1  a string
1  3.0   4      None
2  6.0   7       NaN
3  9.0  10        11
4  NaN  13       NaN
Run Code Online (Sandbox Code Playgroud)

更新:从 Pandas 0.20.1 开始,不推荐使用 .ix 索引器,取而代之的是更严格的 .iloc 和 .loc 索引器