Home > Mobile >  How can I use the pandas.insert() without knowing the size of the column I want to insert?
How can I use the pandas.insert() without knowing the size of the column I want to insert?

Time:10-04

I want to insert another column in a data frame that is simply full of ones, so [1,1,1,1...] by using the insert function, however, I am not sure how to do it. I do not know the number of ones, is there any alternative ways to do it?

CodePudding user response:

You can just pass a scalar to insert:

Example:

df = pd.DataFrame([[1,2,3], [4,5,6]], columns=['A', 'B', 'D'])

df.insert(2, 'C', 1)

output:

   A  B  C  D
0  1  2  1  3
1  4  5  1  6

CodePudding user response:

Can you elaborate and share an example?.Are you looking for something like this?

import numpy as np
import pandas as pd

df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
series= pd.Series([1 for i in range(1,10)])

df.insert(2,"newcol",series)
print(df)
  • Related