Pandas DataFrame 使用行列表和列列表。

huangapple go评论58阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年4月7日 00:20:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定