tags
tags

Reputation: 4060

Convert a string with whitespaces to a dataframe with desired dimensions in Python

What's a smart way to convert a string with white spaces into some dataframe (some 'table') with desired dimensions (X columns and Y rows) in Python?

Say my string is string = 'A B C D E F G H I J K L' and I want to convert it into a 3 cols x 4 rows dataframe.

I guess there are useful pandas/numpy tool for that.

Upvotes: 1

Views: 75

Answers (1)

Liam Foley
Liam Foley

Reputation: 7822

Use Numpy.reshape()

import numpy as np
import pandas as pd

string = 'A B C D E F G H I J K L'

list1 = [char for char in string.split(' ') if char != '']
df = pd.DataFrame(np.reshape(list1,[3,4]))

Outputs:

   0  1  2  3
0  A  B  C  D
1  E  F  G  H
2  I  J  K  L

Whoops... here it is with 3 col x 4 rows:

pd.DataFrame(np.reshape(list1,[4,3]))

   0  1  2
0  A  B  C
1  D  E  F
2  G  H  I
3  J  K  L

Edit: put the imports on top.

Upvotes: 3

Related Questions