Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas DataFrame with row list and column list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A B C D
a b c d

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading