pandas.DataFrame.insert

DataFrame. insert ( loc , column , value , allow_duplicates=False )

Insert column into DataFrame at specified location.

Raises a ValueError if column is already contained in the DataFrame,unless allow_duplicates is set to True.

Insert a column of data at the specified location. If a column already exists in the dataframe, set allow_duplicates to true to insert the specified column.

Parameters:

loc : int

Insertion index. Must verify 0 <= loc <= len(columns) which column to insert

column : string, number, or hashable object

label of the inserted column label of the inserted column

value : int, Series, or array-like

allow_duplicates : bool, optional Boolean type, optional


An example is as follows:

import numpy as np
import pandas as pd

# A = np.array([[1, 1], [1, 2], [1, 3]])
# print(np.shape(A))

df = pd.DataFrame(np.random.randint(1, 10, (6, 4)), index=None, columns=list('ABCD'))
df['E'] = pd.Series([1, 1, 1, 1, 1, 1])
s = pd.Series([1, 1, 1, 1, 1, 1])
df.insert(1, 'X', s)
print(df)

operation result:

   A  X  B  C  D  E
0  7  1  6  6  1  1
1  6  1  7  3  8  1
2  8  1  3  7  1  1
3  3  1  5  4  9  1
4  6  1  9  6  5  1
5  6  1  5  6  5  1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325589397&siteId=291194637