Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a dataframe by repeating series multiple times?

Tags:

python

pandas

Is there any function like the following to create a dataframe with ten columns of Series s?

df = pd.DataFrame(s, 10)

Thank you!

like image 886
bbc Avatar asked Jul 15 '14 14:07

bbc


People also ask

How do you create a DataFrame using multiple series?

You can create a DataFrame from multiple Series objects by adding each series as a columns. By using concat() method you can merge multiple series together into DataFrame. This takes several params, for our scenario we use list that takes series to combine and axis=1 to specify merge series as columns instead of rows.

How do you create a repeated DataFrame?

To create a data frame with a column having repeated values, we simply need to use rep function and we can repeat the values in a sequence of the values passed or repeating each value a particular number of times.

How do you repeat a series on pandas?

Pandas Series: repeat() function The repeat() function is used to repeat elements of a Series. Returns a new Series where each element of the current Series is repeated consecutively a given number of times. The number of repetitions for each element. This should be a non-negative integer.

How do you repeat data in a DataFrame in Python?

Pandas str. repeat() method is used to repeat string values in the same position of passed series itself. An array can also be passed in case to define the number of times each element should be repeated in series.


2 Answers

Use concat:

In [57]:

s = pd.Series(arange(10))
s
Out[57]:
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
dtype: int32
In [59]:

pd.concat([s] * 10, axis=1)

Out[59]:
   0  1  2  3  4  5  6  7  8  9
0  0  0  0  0  0  0  0  0  0  0
1  1  1  1  1  1  1  1  1  1  1
2  2  2  2  2  2  2  2  2  2  2
3  3  3  3  3  3  3  3  3  3  3
4  4  4  4  4  4  4  4  4  4  4
5  5  5  5  5  5  5  5  5  5  5
6  6  6  6  6  6  6  6  6  6  6
7  7  7  7  7  7  7  7  7  7  7
8  8  8  8  8  8  8  8  8  8  8
9  9  9  9  9  9  9  9  9  9  9

If you want to append as rows then remove the axis=1 param.

like image 124
EdChum Avatar answered Oct 07 '22 22:10

EdChum


I don't know of any pure numpy solution for what you want but you can use list comprehension and zip to transpose.

df = pd.DataFrame(zip(*[s for i in range(10)]))

Without the comprehension...

df = pd.DataFrame(zip(*[s]*10))
like image 26
ZJS Avatar answered Oct 08 '22 00:10

ZJS