問題:
嘗試使用標量值的值時,會遇到以下錯誤:
ValueError: If using all scalar values, you must pass an index
當使用所有值都是標量的字典初始化DataFrame 時,會發生這種情況,如下例所示:
<code class="python">a = 2 b = 3 df2 = pd.DataFrame({'A': a, 'B': b})</code>
解:
要解決此問題,有兩個選項:
<code class="python">df = pd.DataFrame({'A': [a], 'B': [b]})</code>
<code class="python">df = pd.DataFrame({'A': a, 'B': b}, index=[0])</code>
如果必須使用標量值,請隨字典一起傳遞索引:
這為DataFrame 提供了理解資料結構所需的上下文。
示例:
<code class="python">a = 2 b = 3 df = pd.DataFrame({'A': [a], 'B': [b]}, index=[0]) print(df)</code>
以下代碼演示了使用標量值構造DataFrame 的正確方法:
A B 0 2 3輸出:
以上是以下是一些適合問答格式、英文且準確反映文章內容的標題選項: * **使用標量建立資料幀:為什麼 \"ValueError\&qu的詳細內容。更多資訊請關注PHP中文網其他相關文章!