2017-03-16 109 views
0

我是一名Python初學者,已經在論壇中搜索了無法成功解決問題的答案。在Python中從2個數據框列中減去數字

我有一個矩陣,想從一列中減去另一列中的數字,然後用結果創建一個新列。

我想:

df['new column]=df['column 1']-df['column 2'] 

我的輸出是:TypeError: unsupported operand type(s) for -: 'str' and 'str'

所以後來我試着用下面的行執行減法之前,這些列整數轉換:

df['column 2']=df['column 2'].astype(int) 

我的輸出是:ValueError: cannot convert float NaN to integer

(我的數據框中有一些NaN)。然後,我嘗試使用下面的代碼與 全部更換與南空字符串:

def remove_nan(s): 
    import math 
    """ remove np.nan""" 
    if math.isnan(s) == True: 
     s.replace(np.nan,"") 
    else: 
     return s 

df['column 1'] = df.apply(remove_nan, axis=0) 

我的輸出是:類型錯誤:("cannot convert the series to <class 'float'>", 'occurred at index ID Number')

我將不勝感激,如果有人可以提供洞察到哪裏我犯了錯誤。

謝謝你的幫助。

+0

你可以尋找答案在這裏http://stackoverflow.com/questions/15118111/apply-function-to-each-row-of -pandas-數據幀,以創建兩新柱 – Afaq

回答

0

使用pd.to_numeric轉換爲數字與參數errors='coerce'nan當它是不是一個數字

考慮df

df = pd.DataFrame(dict(A=list('456 8'), B=list('1 345'))) 

print(df) 

    A B 
0 4 1 
1 5 
2 6 3 
3  4 
4 8 5 

pd.to_numeric

df = df.apply(pd.to_numeric, errors='coerce') 

print(df) 

    A B 
0 4.0 1.0 
1 5.0 NaN 
2 6.0 3.0 
3 NaN 4.0 
4 8.0 5.0 

現在我們能做的我們的專欄數學

df['C'] = df.A - df.B 

print(df) 

    A B C 
0 4.0 1.0 3.0 
1 5.0 NaN NaN 
2 6.0 3.0 3.0 
3 NaN 4.0 NaN 
4 8.0 5.0 3.0 

如果你不想承擔缺失值都爲零

df['C'] = df.A.sub(df.B, fill_value=0) 

print(df) 



    A B C 
0 4.0 1.0 3.0 
1 5.0 NaN 5.0 
2 6.0 3.0 3.0 
3 NaN 4.0 -4.0 
4 8.0 5.0 3.0