簡體   English   中英

獲取 ValueError:列的長度必須與鍵的長度相同

[英]Getting ValueError: Columns must be same length as key

我收到這個錯誤

ValueError: Columns must be same length as key

我的代碼是

all_columns=[ col  for col, dt in y.dtypes.items() if dt == 'object']
df[all_columns] = df[all_columns].astype(str)

我有一些 dict 格式的列。 所以我想將所有這些列轉換為正確的字符串數據類型。 請告訴我為什么會出現此錯誤,我在兩側使用相同的列列表,對嗎?

> 答案:重復數據框中的列會導致此類錯誤。 有兩列具有相同的名稱。

試試這個更簡單的迭代,因為看起來你的列表理解出了問題。 鑒於您在評論中描述的問題,請執行一些操作,例如在迭代時打印列的名稱,以查看哪一列崩潰:

df = pd.DataFrame({'TEXT': ['hello there', 'python fun', np.nan, '']})

print(df.dtypes)
# TEXT    object
# dtype: object

for col in df.columns:
    print(col)
    if df[col].dtype == 'object':
        df[col] = df[col].astype(str)
        print('converted', col)

print(df.dtypes)
# TEXT    object
# dtype: object

或者,嘗試使用此列表理解一次獲取所有對象列,也許您的列表理解是問題所在:

df = pd.DataFrame({'TEXT1': ['hello there', 'python fun', np.nan, ''],
                   'TEXT2': ['hi', 'bye', np.nan, ''],
                   'not text': [1, 2, 3, 4]})

obj_cols = [col for col in df.columns if df[col].dtype == 'object']

df[obj_cols] = df[obj_cols].astype(str)

@Hummarabi 我開始一步一步地一次取 10 列並打印類型為 object 的列名

for col in y.columns[1:10]:
    if y[col].dtypes == 'object':
#          y[col] = y[col].astype(str)
        print(col)

所以我得到了這個錯誤

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

在 y.columns[50:60] 列期間,我按y[y.columns[60:70]].head(80)打印列,令我驚訝的是,我看到有兩列同名。 ('error','error') 所以我刪除了其中一列並運行,現在一切正常,我現在沒有錯誤。 但是這種類型的手動檢查對於超大數據來說有點麻煩。 但是一個觀察結果是ValueError:一個系列的真值是不明確的。 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。


當數據中有重復項時發生


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM