2016-11-10 45 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

相关问题