2016-11-10 44 views
0

我有一個DataFrame(df)與各種列。在這項任務中,我必須找出每個國家使用奧運統計數據的夏季金牌和冬季金牌相對於總獎牌的差異。 我必須只包括那些至少有一枚金牌的國家。我試圖用dropna()不包括那些至少沒有一枚獎牌的國家。我當前的代碼:爲什麼我不能使用python3在pandas的列中刪除值?

def answer_three(): 
    df['medal_count'] = df['Gold'] - df['Gold.1'] 
    df['medal_count'].dropna() 
    df['medal_dif'] = df['medal_count']/df['Gold.2'] 
    df['medal_dif'].dropna() 
    return df.head() 
print (answer_three()) 

這將導致以下的輸出:

    # Summer Gold Silver Bronze Total # Winter Gold.1 \ 
Afghanistan  13  0  0  2  2   0  0 
Algeria   12  5  2  8  15   3  0 
Argentina   23 18  24  28  70  18  0 
Armenia    5  1  2  9  12   6  0 
Australasia   2  3  4  5  12   0  0 

      Silver.1 Bronze.1 Total.1 # Games Gold.2 Silver.2 Bronze.2 \ 
Afghanistan   0   0  0  13  0   0   2 
Algeria    0   0  0  15  5   2   8 
Argentina   0   0  0  41  18  24  28 
Armenia    0   0  0  11  1   2   9 
Australasia   0   0  0  2  3   4   5 

      Combined total ID medal_count medal_dif 
Afghanistan    2 AFG   0  NaN 
Algeria     15 ALG   5  1.0 
Argentina    70 ARG   18  1.0 
Armenia     12 ARM   1  1.0 
Australasia    12 ANZ   3  1.0 

我需要在「medal_count」和楠「medal_dif」擺脫這兩個「0」值。 我也知道我寫的代碼的數學/方法可能不正確,以解決問題,但我認爲我需要開始刪除這些值?任何幫助與上述任何非常感謝。

+1

'dropna()'是不是默認就地操作。應該是 - 'df ['medal_count'] .dropna(inplace = True)'和'df ['medal_dif']。dropna(inplace = True)' –

+0

爲了說明起見,df是從文件中讀取的。 – NamedN

+0

嗨尼爾,我嘗試過,但它導致完全相同的輸出? – NamedN

回答

-1

您需要通過一個軸,例如axis = 1進入拖放功能。 0 =>行,1 =>列的軸。 0似乎是默認值。

enter image description here

正如你可以看到整個列被丟棄對於軸= 1

+0

好吧,我試過「df ['medal_count']。dropna(axis = 0)」和「df ['medal_dif']。dropna(inplace = True,axis = 0)」不知道哪一個是正確的。不要改變輸出。 嘗試使用「axis = 1」會導致以下錯誤:ValueError:對於對象類型 NamedN

+0

注 - 系列對象默認在'axis = 0'上運行。在'DF'上提供'axis = 1'將會丟棄整個列,如果它包含任何'NaNs'。 –

+0

感謝您的解釋!不是我所追求的! – NamedN

相關問題