cut columns in python

To cut columns in Python, you can use the following methods depending on the data structure you are working with:

  1. If you have a DataFrame using pandas:
main.py
import pandas as pd

# Create a sample DataFrame
data = {'A': [1, 2, 3],
        'B': [4, 5, 6],
        'C': [7, 8, 9]}

df = pd.DataFrame(data)

# To select specific columns by their names
selected_columns = df[['A', 'B']]

# To drop specific columns by their names
columns_to_drop = ['B', 'C']
remaining_columns = df.drop(columns=columns_to_drop, axis=1)
358 chars
16 lines
  1. If you have a list of lists or a NumPy array:
main.py
import numpy as np

# Create a sample list of lists
data = [[1, 4, 7],
        [2, 5, 8],
        [3, 6, 9]]

# To select specific columns
selected_columns = np.array(data)[:, [0, 1]]

# To drop specific columns
columns_to_drop = [1, 2]
remaining_columns = np.delete(np.array(data), columns_to_drop, axis=1)
308 chars
14 lines

These examples demonstrate selecting and dropping columns in pandas DataFrames and NumPy arrays.

related categories

gistlibby LogSnag