Pandas .fillna()没有在Python 3中填充DataFrame中的值

时间:2015-12-01 17:45:42

标签: python pandas

我在Python 3中运行Pandas,我注意到以下内容:

import pandas as pd
import numpy as np
from pandas import DataFrame
from numpy import nan

df = DataFrame([[1, nan], [nan, 4], [5, 6]])

print(df)

df2 = df
df2.fillna(0)

print(df2)

返回以下内容:

 0   1
0   1 NaN
1 NaN   4
2   5   6
    0   1
0   1 NaN
1 NaN   4
2   5   6

以下内容:

import pandas as pd
import numpy as np
from pandas import Series
from numpy import nan

sr1 = Series([1,2,3,nan,5,6,7])

sr1.fillna(0)

返回以下内容:

0    1
1    2
2    3
3    0
4    5
5    6
6    7
dtype: float64

当我使用.fillna()时,它填充了Series值,但没有填充0的DataFrame值。这是Python 3的问题吗?否则,我在这里缺少什么来代替DataFrames中的空值?谢谢!

2 个答案:

答案 0 :(得分:2)

正如您在documentation中所读到的那样,方法fillna(newValue)会返回另一个DataFrame,就像前一个nan一样,但df = DataFrame([[1, nan], [nan, 2], [3, 2]]) df2 = df.fillna(0) print(df2) # Outputs # 0 1 # 0 1 0 # 1 0 2 # 2 3 2 print(df) # Outputs (The previous one isn't modified) # 0 1 # 0 1 nan # 1 nan 2 # 2 3 2 值会替换为新值。< / p>

// For textbox       
$form->addText($field['name'], $field['label'])
     ->setRequired('Enter your ' . $field['label']);

// For Email
$form->addText($field['name'], $field['label'])
      ->setRequired('Enter your email')
      ->addRule(FORM::EMAIL, 'Enter a valid email');

答案 1 :(得分:2)

这与您调用fillna()功能的方式有关。

如果您执行inplace=True(请参阅下面的代码),它们将被填充并覆盖原始数据框。

In [1]: paste
import pandas as pd
import numpy as np
from pandas import DataFrame
from numpy import nan

df = DataFrame([[1, nan], [nan, 4], [5, 6]])
## -- End pasted text --

In [2]: 

In [2]: df
Out[2]: 
    0   1
0   1 NaN
1 NaN   4
2   5   6

In [3]: df.fillna(0)
Out[3]: 
   0  1
0  1  0
1  0  4
2  5  6

In [4]: df2 = df

In [5]: df2.fillna(0)
Out[5]: 
   0  1
0  1  0
1  0  4
2  5  6

In [6]: df2  # note how this is unchanged.
Out[6]: 
    0   1
0   1 NaN
1 NaN   4
2   5   6

In [7]: df.fillna(0, inplace=True)  # this will replace the values.

In [8]: df
Out[8]: 
   0  1
0  1  0
1  0  4
2  5  6

In [9]: