Adding and Removing Rows in DataFrame

Write a Pandas program to append a new row ‘k’ to DataFrame with given values for each column. Now delete the new row and return the original DataFrame.

Example 1:

Input: DataFrame 
Output: Original DataFrame after adding and then removing a row

Example 2:

Input: DataFrame 
Output: Original DataFrame after adding and then removing a row

Use pandas DataFrame loc[] function to add new row and drop() function to remove a row.

import pandas as pd

def manipulate_row(df, row_data):
    df.loc['k'] = row_data
    df = df.drop('k')
    return df

df1 = pd.DataFrame({'name': ['Tom', 'Jack', 'Steve', 'Ricky'], 'score': [85, 90, 87, 91]})
df2 = pd.DataFrame({'name': ['Adam', 'Eve', 'Stark', 'Rogers'], 'score': [88, 92, 95, 97]})

print(manipulate_row(df1, ['Sam', 89]))
print(manipulate_row(df2, ['Molly', 93]))

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!