Вставить заданный столбец в определенное место в фрейме данных Pandas
В этой статье мы будем использовать метод Dataframe.insert () в Pandas, чтобы вставить новый столбец по определенному индексу столбца в фрейм данных.
Syntax: DataFrame.insert(loc, column, value, allow_duplicates = False)
Return: None
Code: Let’s create a Dataframe.
Python3
# Importing pandas libraryimport pandas as pd # dictionaryvalues = {"col2": [6, 7, 8, 9, 10], "col3": [11, 12, 13, 14, 15]} # Creating dataframedf = pd.DataFrame(values) # show the dataframedf |
Выход:

Example 1: Inserting column at the beginning of the dataframe.
Python3
# Importing pandas libraryimport pandas as pd # dictionaryvalues = {"col2": [6, 7, 8, 9, 10], "col3": [11, 12, 13, 14, 15]} # Creating dataframedf = pd.DataFrame(values) # New column to be addednew_col = [1, 2, 3, 4, 5] # Inserting the column at the# beginning in the DataFramedf.insert(loc = 0, column = "col1", value = new_col)# show the dataframedf |
Выход:

Example 2: Inserting column in the middle of the dataframe
Python3
# Importing pandas libraryimport pandas as pd # dictionaryvalues = {"col2": [6, 7, 8, 9, 10], "col3": [11, 12, 13, 14, 15]} # Creating dataframedf = pd.DataFrame(values) # New column to be addednew_col = [1, 2, 3, 4, 5] # Inserting the column at the# middle of the DataFramedf.insert(loc = 1, column = "col1", value = new_col)# show the dataframedf |
Выход:

Example 3: Inserting column at the end of the dataframe
Python3
# Importing pandas libraryimport pandas as pd # dictionaryvalues = {"col2": [6, 7, 8, 9, 10], "col3": [11, 12, 13, 14, 15]} # Creating dataframedf = pd.DataFrame(values) # New column to be addednew_col = [1, 2, 3, 4, 5] # Inserting the column at the# end of the DataFrame# df.columns gives index array # of column namesdf.insert(loc = len(df.columns), column = "col1", value = new_col)# show the dataframedf |
Выход:

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.