Skip to main content
 首页 » 编程设计

python之按特定顺序向 Pandas DataFrame 添加值和列

2025年05月04日16daizhj

在 Pandas 中,如何将值添加到具有按特定顺序设置的列的 DataFrame?

我尝试过各种不同的错误结果。

例如:

df = pd.DataFrame([a, b, c], columns=["A", "B", "C"]) 

ValueError: ('Shape of passed values is (..., ...), indices imply (..., ...)', u'occurred at index 0')

df = pd.DataFrame([a], [b], [c], columns=["A", "B", "C"]) 

TypeError: ('init() takes at most 6 arguments (... given)', u'occurred at index 0')

a, b, c 只是字符串:

a = "string a" 
b = "string b" 
c = "string c" 

请您参考如下方法:

您应该传递一个列表列表,其中每个列表包含三个元素,即三列的值,因此每个内部列表类似于一行。示例 -

df = pd.DataFrame([[a, b, c]], columns=["A", "B", "C"])