Skip to content
Advertisement

Split Single Column(1,000 rows) into two smaller columns(500 each)

How to split a single column containing 1000 rows into chunk of two columns containing 500 rows per column in pandas.

I have a csv file that contains a single column and I need to split this into multiple columns. Below is the format in csv.

Steps I took:
I had multiple csv files containing one column with 364 rows. I concatenated them after converting them into a dataframe, but it copies the file in a linear fashion.

Code I tried

JavaScript

How the data is:

column1
1
2
3
.
.
364
1
2
3
.
.
364

I need to split the above column in the format shown below.
What the data should be:

column1 column2
1 1
2 2
3 3
4 4
5 5
. .
. .
. .
364 364

Advertisement

Answer

Answer updated to work for arbitrary number of columns

You could start with number of columns or row length. For a given initial column length you could calculate one given the other. In this answer I use desired target column length – tgt_row_len.

JavaScript

Create groups in the index for the following grouping operation

JavaScript

Previous answer that handles creating two columns

This answer just shows 10 target rows as an example. That can easily be changed to 364 or 500.

A dataframe where column1 contains 2 sets of 10 rows

JavaScript

Move the bottom set of rows to column2

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement