【问题标题】:Getting ValueError: Columns must be same length as key获取 ValueError:列的长度必须与键的长度相同
【发布时间】:2021-07-18 17:38:03
【问题描述】:

我收到此错误

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 格式的列。所以我想将所有这些列转换为正确的字符串数据类型。 请告诉我为什么会出现此错误,我在两侧使用相同的列列表,对吗?

> 回答:重复数据框中的列导致这种类型的 错误。有两列同名。

【问题讨论】:

    标签: python python-3.x list dataframe


    【解决方案1】:

    试试这个更简单的迭代,因为您的列表理解似乎出了点问题。鉴于您在 cmets 中描述的问题,请执行一些操作,例如在迭代时打印列的名称,以查看哪个列崩溃:

    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)
    
    

    【讨论】:

    • 我现在得到这个错误:ValueError:一个系列的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
    • 你能发一份你的df样本吗?我无法重现该错误。我将编辑我的答案以显示一个玩具示例。
    • 它有 147 列。如果我使用 4 或 5 列,则不会发生同样的错误
    • 可能一次检查一些列,例如,如果它转换为 astype(str) 而不会崩溃,则打印 col 名称
    • 列数较少时效果很好。
    【解决方案2】:

    @Hummarabi 我开始一步一步地一次取 10 列并打印对象类型的列名

    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) 打印了这些列,令我惊讶的是,我看到有两列同名。 ('错误','错误') 因此,我删除了其中一列并运行,现在一切正常,我现在没有任何错误。 但是这种类型的手动检查对于非常大的数据来说有点麻烦。 但有一个观察结果是 ValueError:Series 的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。


    当数据中有重复时发生


    【讨论】:

    • 很好的调试工作,感谢您指出重复的问题
    猜你喜欢
    • 2019-02-24
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2022-01-23
    • 2018-11-04
    相关资源
    最近更新 更多