英文:
Pandas DataFrame with row list and column list
问题
Expected Output:
A B C D
a b c d
英文:
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
得分: 1
将row_list
包装在一个列表中:
row_list = ['a', 'b', 'c', 'd']
col_list = ['A', 'B', 'C', 'D']
df = pd.DataFrame([row_list], columns=col_list)
# 或者
df = pd.DataFrame([dict(zip(col_list, row_list))])
尽管不建议这种方法,使用转置的解决方案是:
df = pd.DataFrame(row_list, index=col_list).T
输出:
A B C D
0 a b c d
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论