Changing data in a DataFrame column (Pandas) with a For loop
<p>I'm trying to take the data from "Mathscore" and convert the values into numerical values, all under "Mathscore."</p>

<p>strong =1
Weak = 0</p>

<p>I tried doing this via the function below using For loop but I can't get the code to run.  Is the way I'm trying to assign data incorrect?</p>

<p>Thanks! </p>

<pre><code>import pandas as pd

data = {'Id_Student' : [1,2,3,4,5,6,7,8,9,10],'Mathscore' :['Strong','Weak','Weak','Strong','Strong','Weak','Strong','Strong','Weak','Strong']}

df = pd.DataFrame(data)
df

# # Strong = 1 and Weak =0

##def tran_mathscore(x): if x == 'Strong': return 1 if x == 'Weak': return 0
##
##df['Trans_MathScore'] = df['Mathscore'].apply(tran_mathscore)
##df


##df.Mathscore[0]=["Weak"]

##print(df.columns)
##
##
##print(df.Mathscore)

def tran_mathscore():
    for i in df.Mathscore:
        if i == "Strong":
        df.Mathscore[i]= ['1']

    elif i == "Weak":
        df.Mathscore[i]= ['0']


tran_mathscore()
</code></pre>

<p>You could use:</p>

<pre><code>df['Mathscore'] = df['Mathscore'].str.replace('Strong','1')
df['Mathscore'] = df['Mathscore'].str.replace('Weak','0')
</code></pre>

<p>Returns:</p>

<pre><code>In [1]: df

Out[1]:

   Id_Student Mathscore
0           1         1
1           2         0
2           3         0
3           4         1
4           5         1
5           6         0
6           7         1
7           8         1
8           9         0
9          10         1
</code></pre>

python pandas dataframe