2016-12-05 109 views
2

不知道爲什麼.dropnan()不會刪除帶有NaN值的單元格?在熊貓蟒蛇中掉落NaN

請幫忙,我已經通過了熊貓文檔,不知道我在做什麼錯?

import pandas as pd 
import quandl 

import pandas as pd 

df = quandl.get("GOOG/NYSE_SPY") 
df2 = quandl.get("YAHOO/AAPL") 

date = pd.date_range('2010-01-01', periods = 365) 

df3 = pd.DataFrame(index = date) 

df3 = df3.join(df['Open'], how = 'inner') 

df3.rename(columns = {'Open': 'SPY'}, inplace = True) 

df3 = df3.join(df2['Open'], how = 'inner') 

df3.rename(columns = {'Open': 'AAPL'}, inplace = True) 

df3['Spread'] = df3['SPY']/df3['AAPL'] 

df3 = df3/df3.ix[0] 

df3.dropna(how = 'any') 

df3.plot() 

print(df3) 
+0

它不是就地操作。無論是'df3.dropna(how ='any',inplace = True)'或'df3 = df3.dropna(how ='any')'都可以工作。 – ayhan

回答

2

變化df3.dropna(how = 'any')df3 = df3.dropna(how = 'any')

1

我試圖用一個簡單的csv文件來複制你的問題:

In [6]: df 
Out[6]: 
    a b 
0 1.0 3.0 
1 2.0 NaN 
2 NaN 6.0 
3 5.0 3.0 

兩個df.dropna(如何= '任何')以及DF1 = df.dropna(how ='any')的工作。即使只是df.dropna()的作品。我想知道你的問題是否是因爲你在前面的線進行劃分:

df3 = df3/df3.ix[0] 
df3.dropna(how = 'any') 

舉例來說,如果我通過df.ix [1]劃分,因爲元素之一是NaN,將其轉換將結果中的所有元素都納入NaN,然後​​如果使用dropna刪除NaN,則會刪除所有行:

In [17]: df.ix[1] 
    Out[17]: 
    a 2.0 
    b NaN 
    Name: 1, dtype: float64 

    In [18]: df2 = df/df.ix[1] 
    In [19]: df2 
    Out[19]: 
     a b 
    0 0.5 NaN 
    1 1.0 NaN 
    2 NaN NaN 
    3 2.5 NaN 

    In [20]: df2.dropna() 
    Out[20]: 
    Empty DataFrame 
    Columns: [a, b] 
    Index: []