2016-03-31 5 views
2

Ich habe eine df (Apple_farm) und müssen einen Prozentsatz basierend auf Werte in zwei der Spalten (Good_apples und) zu berechnen und dann die resultierenden Werte zu einer neuen Spalte in Apple_farm hinzufügen "Perc_Good" genannt.Berechnen und Erstellen von Prozent Spalte aus zwei Spalten

Ich habe versucht:

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

Dies führt jedoch zu diesem Fehler:

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

Doing

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

ergibt eine Liste mit numerischen Werten sie jedoch Dividieren scheint dazu zu führen, dass sie c sind auf Saiten umgestellt?

Ich habe auch versucht, eine neue Funktion zu definieren:

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

sind aber unsicher, wie diese zu verwenden.

Jede Hilfe würde geschätzt werden, da ich Python und Pandas ziemlich neu bin!

Antwort

2

Ich glaube, Sie string Spalten float oder int konvertieren müssen, weil ihre typestring ist (aber sieht aus wie Zahlen):

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) 

Probe:

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