Updating a dataframe

Posted under » Python Data Analysis on 10 Sep 2023

From Pandas Dataframe we learnt how to show a record in a column.

To recap, this is how we return 2 rows. When using [], the result is a Pandas DataFrame.

print(df.loc[[0, 1]])

     calories  duration
  0       420        50
  1       380        40

When you want to show only the `calories', we do the same but look at the placement of the square brackets.

print(df.loc[0, ['calories']]) 

     calories
  0       420

Let's say we have to update only the calories located in the row 0. We know it is currently 420 but, we have to update it to 450. Let’s do that.

df.loc[0, ['calories']] = [450]

print(df.loc[0, ['calories']])

     calories
  0       450

Next, we learn how to add new columns to your df. The simplest is to add after the last column

correct =  [0, 0, 0]
not_attempted = [0, 0, 0]

df['correct'] = correct
df['not_attempted'] = not_attempted

Now our df have 4 columns ie. calories, duration, correct, not_attempted

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data