1

I must be missing something, but I cannot find any guides on how to construct a pandas dataframe using both list of rows and columns. The purpose is that the row_list and col_list are updated in a loop and can hold more or less strings, but will always equal each other in length.

Using transpose works on the rows, but I'm not sure how to pass the columns in.

row_list = ['a', 'b', 'c', 'd']
col_list = ['A', 'B', 'C', 'D']
df = pd.DataFrame(row_list, columns=col_list)
>>>
raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}")
ValueError: Shape of passed values is (4, 1), indices imply (4, 4)

df = pd.DataFrame(row_list).T
>>>
0 1 2 3
a b c d

Expected Output:

A B C D
a b c d

1 Answer 1

1

Wrap row_list in a list:

row_list = ['a', 'b', 'c', 'd']
col_list = ['A', 'B', 'C', 'D']
df = pd.DataFrame([row_list], columns=col_list)

# or
df = pd.DataFrame([dict(zip(col_list, row_list))])

Although not recommended, the solution with the transpose would have been:

df = pd.DataFrame(row_list, index=col_list).T

Output:

   A  B  C  D
0  a  b  c  d
Sign up to request clarification or add additional context in comments.

2 Comments

Why would you not recommend the transpose solution? Is it cumbersome with larger datasets?
It's less efficient and will mess up the dtypes if you have mixed dtypes (not in this case as your input is 1D).

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.