Huy Pham
Huy Pham

Reputation: 71

Adding a column to panda dataframe

I have been trying for hours to find a method to replicate columns n number of times and add them a Dataframe but has had little luck. Please help!

Current Dataframe:

    0
0   2
1   4
2   5
3   6
4   9

Output:

    0  1 2 ... 99
0   2  2 2     2
1   4  4 4     4 
2   5  5 5     5
3   6  6 6     6
4   9  9 9     9

Upvotes: 0

Views: 66

Answers (3)

Karl Thornton
Karl Thornton

Reputation: 21

>>> df
   0
0  2
1  4
2  5
3  6
4  9

.iloc is another option

>>> df.iloc[:, [0] * 10]
   0  0  0  0  0  0  0  0  0  0
0  2  2  2  2  2  2  2  2  2  2
1  4  4  4  4  4  4  4  4  4  4
2  5  5  5  5  5  5  5  5  5  5
3  6  6  6  6  6  6  6  6  6  6
4  9  9  9  9  9  9  9  9  9  9

Upvotes: 1

Anurag Dabas
Anurag Dabas

Reputation: 24322

As mention in comment by @sammywemmy you can use:-

df=pd.concat([df]*100, axis = 'columns')

After that rename columns:-

df.columns=range(0,len(df.columns))

Upvotes: 1

ThePyGuy
ThePyGuy

Reputation: 18456

There could be several ways, one way is something like this:

df= pd.DataFrame()
    for i in range(5):
        for j in range(0,10):
            df.loc[i,j] = i+j
        
df
     0    1    2    3    4    5     6     7     8     9
0  0.0  1.0  2.0  3.0  4.0  5.0   6.0   7.0   8.0   9.0
1  1.0  2.0  3.0  4.0  5.0  6.0   7.0   8.0   9.0  10.0
2  2.0  3.0  4.0  5.0  6.0  7.0   8.0   9.0  10.0  11.0
3  3.0  4.0  5.0  6.0  7.0  8.0   9.0  10.0  11.0  12.0
4  4.0  5.0  6.0  7.0  8.0  9.0  10.0  11.0  12.0  13.0

Upvotes: 0

Related Questions