1

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!

6
  • 1
    pd.DataFrame([l]) Commented Jul 19, 2019 at 19:20
  • Alternatively, df.transpose() Commented Jul 19, 2019 at 19:20
  • 1
    Or an alias for transpose: df.T Commented Jul 19, 2019 at 19:22
  • The end result, I am looking to get a data frame on separate columns so that I can later export in .csv. I have a larger code that builds multiple lists, and for some reason, transpose doesn't work. Commented Jul 19, 2019 at 19:22
  • Can you describe "transpose does not work"? What Output do you see? Commented Jul 19, 2019 at 19:33

5 Answers 5

2

I usually using Series

df = pd.Series(l).to_frame('Header').T
Sign up to request clarification or add additional context in comments.

3 Comments

I think OP wants pd.Series(l).to_frame('Header').T.
Right, so this shows it in rows. I need it in columns, for example: Header 1 - 3.4 Header 2 - 3.2 Header 3 - 2.3 Header 4 - 4.3 Header 5 - 2.3
@WeNYoBen, always there to help :)
0

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

Comments

0

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

df = pdf.DataFrame([l])

Comments

0

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])

2 Comments

I may have been not 100% clear. I am looking for columns. So 5 headers and 1 row.
Don't you want this?
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.