Add & Delete
Lesson 10 of 19 in Coddy's Pandas Analytics course.
To add a new column, specify the new column name and a value dataframe:
df["new_column"] = valuevalue can hold a single value like "string", 5, etc; this will fill the whole column with the same value for all rows. Or it can hold a list, dictionary, or series with the same number of rows in the dataframe, like [1, 2, 3, ...].
It is not recommended to add new rows to a dataframe because it is slow. Instead, it would be better to add the data to the CSV file or the dictionary you are working with and then convert it to a dataframe.
If there is no other way, add a row to the end of the dataframe:
df.loc[len(df)] = ["string", 1, 2, ...]There is no built-in option to insert a row into a specific index. If you'll write this:
df.loc[0] = ["string", 1, 2, ...]It will modify the first row completely.
To delete a column, use axis=1:
df = df.drop('column_name', axis=1)
df = df.drop(['column1_name', 'column2_name'], axis=1) # Multipe columnsTo delete a row, use axis=0
df = df.drop(index, axis=0)Challenge
EasyThe CSV file stats.csv contains information about stats.
Here is the first 5 lines of the file:
ID,COUNTRY,COLOR,SKILL,SKILL_POINTS,UTILIZATION,IS_VALID,CATEGORY
1,France,Signal violet,marksmanship,14,0.1924,1,SHOW
2,Solomon Islands,Pearl violet,crocheting,4,0.6108,1,TREE
3,Germany,Bottle green,calligraphy,12,0.88646,0,SHOW
4,Mauritania,Fawn brown,paper cutting,9,0.058,1,JAPE- Add a column named
SINGLE_VAlUEwith the value0. - Drop the columns
COUNTRYandCOLOR. - Add another row with the following values at the end of the dataframe:
{"ID": 21, "SKILL": "Craft", "SKILL_POINTS": 13, "UTILIZATION": 0.1352, "IS_VALID": 1, "CATEGORY": "SHOW", "SINGLE_VALUE": 0}. - Drop the first row.
Store the result in the df variable.
Try it yourself
# pandas as pd is already imported
df = pd.read_csv("./stats.csv")
# Write your code below
All lessons in Pandas Analytics
4Data Analysis with Pandas
Descriptive StatisticsGrouping and Aggregating DataDifferent AggregationsMerge & Concat2Working with the DataFrame
Understanding DataFramesAccessing DataData Cleaning - Missing dataData Cleaning - More tools3Data Manipulation with Pandas
Return Requested ResultFilter DataAdd & DeleteModify DataModify StringsCustom Modifications