Методы добавления столбца в массив в Python: NumPy, Pandas и Pure Python

Чтобы добавить столбец в массив в Python, вы можете использовать различные методы в зависимости от используемой библиотеки или структуры данных. Вот несколько методов с примерами кода:

  1. Использование NumPy:

    import numpy as np
    # Create a 2D array
    arr = np.array([[1, 2, 3], [4, 5, 6]])
    # Create a new column
    new_col = np.array([7, 8])
    # Add the new column to the array
    new_arr = np.column_stack((arr, new_col))
    print(new_arr)

    Выход:

    [[1 2 3 7]
    [4 5 6 8]]
  2. Использование Pandas:

    import pandas as pd
    # Create a DataFrame
    df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
    # Create a new column
    new_col = pd.Series([7, 8])
    # Add the new column to the DataFrame
    df['C'] = new_col
    print(df)

    Выход:

    A  B  C
    0  1  4  7
    1  2  5  8
    2  3  6  NaN
  3. Использование чистого Python (вложенные списки):

    # Create a 2D array as a nested list
    arr = [[1, 2, 3], [4, 5, 6]]
    # Create a new column
    new_col = [7, 8]
    # Add the new column to each row of the array
    new_arr = [row + [col] for row, col in zip(arr, new_col)]
    print(new_arr)

    Выход:

    [[1, 2, 3, 7], [4, 5, 6, 8]]