解決 ValueError: If using all scalar values, you must pass an index
解決 ValueError: If using all scalar values, you must pass an index¶
這個錯誤通常出現在沒有設定索引時,想要建立一個 DataFrame。¶
In [2]:
import pandas as pd
dict1 = {1:"a", 2:"b", 3:"c", 4:"d"}
df = pd.DataFrame(dict1)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-2-68948f391692> in <module> 1 import pandas as pd 2 dict1 = {1:"a", 2:"b", 3:"c", 4:"d"} ----> 3 df = pd.DataFrame(dict1) ~\anaconda3\envs\Work37\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy) 527 528 elif isinstance(data, dict): --> 529 mgr = init_dict(data, index, columns, dtype=dtype) 530 elif isinstance(data, ma.MaskedArray): 531 import numpy.ma.mrecords as mrecords ~\anaconda3\envs\Work37\lib\site-packages\pandas\core\internals\construction.py in init_dict(data, index, columns, dtype) 285 arr if not is_datetime64tz_dtype(arr) else arr.copy() for arr in arrays 286 ] --> 287 return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype) 288 289 ~\anaconda3\envs\Work37\lib\site-packages\pandas\core\internals\construction.py in arrays_to_mgr(arrays, arr_names, index, columns, dtype, verify_integrity) 78 # figure out the index, if necessary 79 if index is None: ---> 80 index = extract_index(arrays) 81 else: 82 index = ensure_index(index) ~\anaconda3\envs\Work37\lib\site-packages\pandas\core\internals\construction.py in extract_index(data) 389 390 if not indexes and not raw_lengths: --> 391 raise ValueError("If using all scalar values, you must pass an index") 392 393 if have_series: ValueError: If using all scalar values, you must pass an index
要解決這個問題,就是將索引設定好,這裡有幾個解決方法,供各位參考。¶
In [3]:
import pandas as pd
# 直接在建立 DataFrame 時,設定 Index 就好。
dict1 = {1:"a", 2:"b", 3:"c", 4:"d"}
df = pd.DataFrame(dict1,index=[0])
print(df)
1 2 3 4 0 a b c d
In [5]:
import pandas as pd
# 輸入字典的時候,不要讓 value 視為內容,把 value 轉換為 list 再傳入。
dict1 = {1:["a"], 2:["b"], 3:["c"], 4:["d"]}
df = pd.DataFrame(dict1)
print(df)
1 2 3 4 0 a b c d
In [9]:
import pandas as pd
# 直接將 Key 和 value 轉換為 list 即可。
dict1 = {1:"a", 2:"b", 3:"c", 4:"d"}
df = pd.DataFrame([dict1])
print(df)
1 2 3 4 0 a b c d
In [12]:
import pandas as pd
# 使用 from_dict 將 dict 轉換為 DataFrame,在這裡將 orient = index 設定為使用字典鍵
# 可以用 .T 取得轉置資料,此與numpy的語法相同
dict1 = {1:"a", 2:"b", 3:"c", 4:"d"}
df = pd.DataFrame.from_dict(dict1, orient='index').T
print(df)
1 2 3 4 0 a b c d
Lai Tai-Yu (賴岱佑)
Comments
Post a Comment