g3lo
g3lo

Reputation: 163

How to convert a list into multiple columns using Python?

Example:

l = ['3.4', '3.2', '2.3', '4.3', '2.3']

Is there a way to convert the list above into separate columns?

For example, I am can do this:

Header
3.4
3.2
2.3
4.3
2.3

with the following code:

df = pdf.DataFrame(l)

However, I would like to achieve the following:

3.4 | 3.2 | 2.3 | 4.3 | 2.3 -> separate columns, rather than rows.

Thank you!

Upvotes: 1

Views: 1366

Answers (5)

johnDanger
johnDanger

Reputation: 2333

You can either transpose the dataframe after initialization

df.transpose()

OR

you can change the list to begin with to change its shape from (4, 1) to (1, 4)

l2 = [l]
pd.DataFrame(l2)

OR

Create a new dictionary to feed into pandas (dictionaries are the typical way to create a dataframe)

colNames = ['a','b','c','d'] 
pd.DataFrame(dict(list(zip(l, colNames))))

Cheers!

Upvotes: 0

flashy
flashy

Reputation: 564

You can use this code:

l = ['3.4', '3.2', '2.3', '4.3', '2.3']

for i in range(len(l)):
    if i == list(range(len(l)))[-1]:
        print("└───", end="")
    else:
        print("├───", end="")
    print(l[i])

Upvotes: 0

Krishna Rao
Krishna Rao

Reputation: 99

You can use in similar code, but use list of lists:

df = pdf.DataFrame([l])

Upvotes: 0

Abhishek Kumar
Abhishek Kumar

Reputation: 788

You can use below snippet

l = ['3.4', '3.2', '2.3', '4.3', '2.3']
l = np.array(l)
df = pd.DataFrame(l.reshape(-1,len(l)))
df =
    0   1   2   3   4
0   3.4 3.2 2.3 4.3 2.3

Hope this helps

Upvotes: 0

BENY
BENY

Reputation: 323376

I usually using Series

df = pd.Series(l).to_frame('Header').T

Upvotes: 2

Related Questions