Built with Tutify.io

    AIStudyLabs

    Pandas Drop Last Column From DataFrame

    Pandas Drop Last Column From DataFrame

    To drop the last column from a DataFrame in Pandas, you can use the iloc[] method to select all rows and all columns except the last one. Additionally, you have several other options such as the drop(), pop(), and del functions. This article will explain the method of dropping the last column from a Pandas DataFrame.

    Key Points –

    <a id="h-quick-examples-of-drop-last-column"></a>

    Quick Examples of Drop Last Column

    Below are some quick examples of how to drop the last column from DataFrame.

    
    # Quick examples of drop last column from dataframe
    
    # Example 1: Drop last column of dataframe 
    # Using iloc[]
    df2 = df.iloc[: , :-1]
    
    # Example 2: By using iloc[] 
    # To select all columns
    # Except the last column
    df2 = df[df.columns[:-1]]
    
    # Example 3: Drop last column of dataframe using drop()
    df.drop(columns=df.columns[-1],  axis=1,  inplace=True)
    
    # Example 4: Using drop() function to delete last column
    df.drop(df.columns[len(df.columns)-1], axis=1, inplace=True)
    
    # Example 5: Using DataFrame.drop() function 
    # To drop last column
    df2 = df.drop(df.columns[-1],axis=1)
    
    # Example 6: Drop last column of dataframe 
    # Using pop()
    df.pop(df.columns[-1])
    
    # Example 7: Use del keywords
    del df[df.columns[-1]]
    

    <a id="h-usage-of-drop-last-column-from-pandas-dataframe"></a>

    Usage of Drop Last Column From Pandas DataFrame

    To drop the last column from a DataFrame in Pandas, you can use indexing along with the drop() method or slicing.

    To run some examples of dropping the last column from DataFrame. Now, Let’s create a Pandas DataFrame using data from a dictionary.

    
    # Create DataFrame
    import pandas as pd
    import numpy as np
    technologies= ({
        'Courses':["Spark","PySpark","Hadoop","Pandas"],
        'Fee': [22000,25000,30000,35000],
        'Duration':['30days','50days','40days','35days'],
        'Discount':[1000,2000,2500,1500]
                  })
    index_labels=['r1','r2','r3','r4']
    df = pd.DataFrame(technologies,index=index_labels)
    print("Create DataFrame:\n",df)
    

    Yields below output.

    <a id="h-pandas-drop-last-column-using-iloc"></a>

    Pandas Drop Last Column using iloc[]

    To drop the last column of a Pandas DataFrame, utilize iloc[] by specifying all rows (:) and all columns except the last one.

    
    # Drop last column of dataframe 
    # Using iloc[]
    df2 = df.iloc[:, :-1]
    print("Dropping last column:\n", df2)
    
    # By using iloc[] to select all columns
    # Except the last column
    df2 = df[df.columns[:-1]]
    print("Dropping last column:\n", df2)
    

    In the above example, In the iloc[:, :-1] part, : selects all rows, and :-1 selects all columns up to (but not including) the last one. This effectively drops the last column from the DataFrame.

    <a id="h-using-drop-to-drop-the-last-column"></a>

    Using drop() To Drop the Last Column

    Alternatively, remove the last column from a DataFrame with the drop() method, specify the label of the last column along with axis=1.

    
    # Using DataFrame.drop() function 
    # To drop last column
    df2 = df.drop(df.columns[-1],axis=1)
    print("Dropping last column:\n", df)
    
    # Drop last column of dataframe using drop()
    df.drop(columns=df.columns[-1],  axis=1,  inplace=True)
    print("Dropping last column:\n", df)
    
    # Using drop() function to delete last column
    df.drop(df.columns[len(df.columns)-1], axis=1, inplace=True)
    print("Dropping last column:\n", df)
    

    In the above example, df.columns[-1] gets the label of the last column, and axis=1 specifies that we want to drop a column. The resulting DataFrame (df) will have the last column removed. df.columns[-1] returns Duration which is the last column from our DataFrame.

    <a id="h-drop-last-column-using-pop"></a>

    Drop Last Column using pop()

    Utilize the pop() function to remove the last column of the DataFrame and return the deleted column as a Series. To specifically select the last column of a DataFrame, you can use df.columns[-1], which selects all columns except the last one.

    
    # Drop last column of dataframe 
    # Using pop()
    df.pop(df.columns[-1])
    print("Dropping last column:\n", df)
    

    In the above example, df.columns[-1] gets the label of the last column, and df.pop() removes and returns that column. The resulting DataFrame (df) will no longer contain the last column.

    <a id="h-use-del-keyword-to-drop-last-column-of-pandas-dataframe"></a>

    Use del Keyword to Drop Last Column of Pandas DataFrame

    Similarly, you can use the del keyword to remove the last column from a Pandas DataFrame.

    
    # Use del keywords
    del df[df.columns[-1]] 
    print(df)
    

    In the above examples, df.columns[-1] gets the label of the last column, and del df[df.columns[-1]] removes that column from the DataFrame. The resulting DataFrame (df) will no longer contain the last column. Note that this modifies the original DataFrame in place.

    <a id="h-complete-example-for"></a>

    Complete Example For

    
    import pandas as pd
    import numpy as np
    technologies= ({
        'Courses':["Spark","PySpark","Hadoop","Pandas"],
        'Fee': [22000,25000,30000,35000],
        'Duration':['30days','50days','40days','35days'],
        'Discount':[1000,2000,2500,1500]
                  })
    index_labels=['r1','r2','r3','r4']
    df = pd.DataFrame(technologies,index=index_labels)
    print(df)
    
    # Drop last column of dataframe 
    # Using iloc[]
    df2 = df.iloc[: , :-1]
    print(df2)
    
    # By using iloc[] 
    # To select all columns
    # Except the last column
    df2 = df[df.columns[:-1]]
    print(df2)
    
    # Drop last column of dataframe
    # Using drop()
    df.drop(columns=df.columns[-1],  axis=1,  inplace=True)
    print(df)
    
    # Using drop() function 
    # To delete last column
    df.drop(df.columns[len(df.columns)-1], axis=1, inplace=True)
    print(df)
    
    # Using DataFrame.drop() function 
    # To drop last column
    df2 = df.drop(df.columns[-1],axis=1)
    print(df2)
    
    # Drop last column of dataframe 
    # Using pop()
    df.pop(df.columns[-1])
    print(df)
    
    # Use del keywords
    del df[df.columns[-1]] 
    print(df)
    

    <a id="h-faq-on-pandas-drop-last-column-from-dataframe"></a>

    FAQ on Pandas Drop Last Column From DataFrame

    You can drop the last column using the drop() method. For instance, df = df.drop(df.columns[-1], axis=1)

    You can use the index-based approach by selecting the last column with df.columns[-1], as shown above. This way, you don't need to know the column's name.

    By default, drop() returns a new DataFrame without modifying the original. If you want to modify the original DataFrame in place, set the inplace parameter to True.

    You can use the pop() method to remove the last column from a DataFrame, and it will also return the removed column. Unlike the drop() method, pop() directly modifies the original DataFrame by removing the column in place.

    Dropping columns will shift the remaining column positions, but the index rows will remain unchanged. If you need to reset the column index positions, you can reassign or reset the index.

    <a id="h-conclusion"></a>

    Conclusion

    In this article, you have learned how to drop the last column from Pandas DataFrame by using iloc[], drop(), pop(), and del Keyword with examples.

    Happy Learning !!

    Related Articles

    References