2016-03-31 11 views
2

df(Apple_farm)があり、2つの列(Good_applesおよびTotal_apples)にある値に基づいてパーセンテージを計算し、結果をApple_ファーム内の新しい列に追加する必要があります。 「Perc_Good」と呼ばれています。2つの列から割合の列を計算して作成する

私が試してみました:

Apple_farm['Perc_Good'] = (Apple_farm['Good_apples']/Apple_farm['Total_apples']) *100 

しかし、これは、このエラーが発生:

Print Apple_farm['Good_apples']Print Apple_farm['Total_apples']

を行う

TypeError: unsupported operand type(s) for /: 'str' and 'str'

は、しかし、それらを分割する数値でリストを生成しますそれらがcになるように思われる文字列に変換されますか?

私はまた、新しい関数を定義しようとしている:

def percentage(amount, total): 
    percent = amount/total*100 
    return percent 

をこれを使用する方法について不明な点があります。

私はPythonとpandasにはかなり新しいので、助けてください!

答えて

2

私はあなたが彼らのtypestringである(ただし、数字のように見える)ので、floatまたはintstring列を変換する必要があると思う:

Apple_farm['Good_apples'] = Apple_farm['Good_apples'].astype(float) 
Apple_farm['Total_apples'] = Apple_farm['Total_apples'].astype(float) 

Apple_farm['Good_apples'] = Apple_farm['Good_apples'].astype(int) 
Apple_farm['Total_apples'] = Apple_farm['Total_apples'].astype(int) 

はサンプル:

import pandas as pd 

Good_apples = ["10", "20", "3", "7", "9"] 
Total_apples = ["20", "80", "30", "70", "90"] 
d = {"Good_apples": Good_apples, "Total_apples": Total_apples} 
Apple_farm = pd.DataFrame(d) 
print Apple_farm 
    Good_apples Total_apples 
0   10   20 
1   20   80 
2   3   30 
3   7   70 
4   9   90 

print Apple_farm.dtypes 
Good_apples  object 
Total_apples object 
dtype: object 

print Apple_farm.at[0,'Good_apples'] 
10 

print type(Apple_farm.at[0,'Good_apples']) 
<type 'str'> 
Apple_farm['Good_apples'] = Apple_farm['Good_apples'].astype(int) 
Apple_farm['Total_apples'] = Apple_farm['Total_apples'].astype(int) 

print Apple_farm.dtypes 
Good_apples  int32 
Total_apples int32 
dtype: object 

print Apple_farm.at[0,'Good_apples'] 
10 

print type(Apple_farm.at[0,'Good_apples']) 
<type 'numpy.int32'> 
Apple_farm['Perc_Good'] = (Apple_farm['Good_apples']/Apple_farm['Total_apples']) *100 

print Apple_farm 
    Good_apples Total_apples Perc_Good 
0   10   20  50.0 
1   20   80  25.0 
2   3   30  10.0 
3   7   70  10.0 
4   9   90  10.0 
関連する問題