Ryo_N
Ryo_N

Reputation: 25

using np.repeat multiple times to create a row in pandas dataframe

I have a dataframe with only column names ( 45 columns) and no actual data. I want to create a row within the dataframe so that 15 columns have data "A", 15 columns have data "B", and the last 15 columns have the data "C", like so in the example below.

1 2 3... 16 17 18...43 44 45
A A A... B  B  B... C  C  C

I didn't know how to do this using jupyter notebook so I'd created excel file and converted it to dataframe, but was there a way to do so using numpy or pandas in jupyter notebook? I suppose you could use np.repeat in some kind of way but I didn't know how.

Upvotes: 0

Views: 447

Answers (2)

Grayrigel
Grayrigel

Reputation: 3594

You can simply use lists to do this:

import pandas as pd

data = ['A']*15 + ['B']*15 + ['C']*15 
df = pd.DataFrame(data).T
print(df)

Output:

0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20  ... 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
0  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  B  B  B  B  B  B  ...  B  B  B  B  B  B  C  C  C  C  C  C  C  C  C  C  C  C  C  C  C

Upvotes: 1

Rajesh Bhat
Rajesh Bhat

Reputation: 1000

colnm = [str(i) for i in range(1, 46)]
data = np.repeat(['A', 'B', 'C'], 15).reshape(1, -1)
df = pd.DataFrame(data)
df.columns = colnm

Upvotes: 1

Related Questions