Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 更改熊猫的nan值_Python_Pandas - Fatal编程技术网

Python 更改熊猫的nan值

Python 更改熊猫的nan值,python,pandas,Python,Pandas,在我的代码中,当df.dropna()方法工作时,df.fillna()方法不工作。不过我不想放弃这个专栏。我能做些什么使fillna()方法工作 def preprocess_df(df): for col in df.columns: # go through all of the columns if col != "target": # normalize all ... except for the target itself! df

在我的代码中,当df.dropna()方法工作时,df.fillna()方法不工作。不过我不想放弃这个专栏。我能做些什么使fillna()方法工作

def preprocess_df(df):
    for col in df.columns:  # go through all of the columns
        if col != "target":  # normalize all ... except for the target itself!
            df[col] = df[col].pct_change()  # pct change "normalizes" the different currencies (each crypto coin has vastly diff values, we're really more interested in the other coin's movements)
            # df.dropna(inplace=True)  # remove the nas created by pct_change
            df.fillna(method="ffill", inplace=True)
            print(df)
            break
            df[col] = preprocessing.scale(df[col].values)  # scale between 0 and 1.

除非它不在循环内,否则它应该工作

您应该考虑在构建循环之前或在数据框架构建过程中填写:

下面的示例cleary显示了它的工作原理:

>>> df
  col1
0  one
1  NaN
2  two
3  NaN
按预期工作:

>>> df['col1'].fillna( method ='ffill')  # This is showing column specific to `col1`

0    one
1    one
2    two
3    two
Name: col1, dtype: object
其次,如果您希望更改几个选择性列,则使用以下方法:

假设您有3列,并且只想对2列使用
ffill
填充na

>>> df
  col1  col2 col3
0  one  test  new
1  NaN   NaN  NaN
2  two  rest  NaN
3  NaN   NaN  NaN
定义要更改的列

cols = ['col1', 'col2']

>>> df[cols] = df[cols].fillna(method ='ffill')
>>> df
  col1  col2 col3
0  one  test  new
1  one  test  NaN
2  two  rest  NaN
3  two  rest  NaN
如果您认为它会发生在整个数据帧中,则在以下过程中使用它:

>>> df
  col1  col2
0  one  test
1  NaN   NaN
2  two  rest
3  NaN   NaN

>>> df.fillna(method ='ffill')  # inplace=True if you considering as you wish for permanent change.
  col1  col2
0  one  test
1  one  test
2  two  rest
3  two  rest

第一个值是NaN,因此我必须使用bfill方法。谢谢大家

请分享您的数据样本。如果您
dropna
,NAs将消失。当然,
fillna
将无需填充任何内容……您的
df。fillna(method=“ffill”,inplace=True)
不需要在您的循环中,因为它作为一个整体作用于
df
,而不仅仅作用于列。@user9468014。