简体   繁体   English

列的长度必须与键相同。 为什么我会收到这样的错误? 谁能帮我吗?

[英]Columns must be same length as key. Why I'm getting such error? can anyone help me out?

cols = ["Gender", "Married", "Education", "Self_Employed", "Property_Area", "Loan_Status", "Dependents"]
for col in cols:
    df[col] = pd.get_dummies(df[col], drop_first=True)

get_dummies generates DataFrame which may have many columns (even if you use drop_first=True ) and you need join() to add all new columns. get_dummies生成DataFrame可能有很多列(即使您使用drop_first=True )并且您需要join()来添加所有新列。

And later you can use del df[col] to remove old column.稍后您可以使用del df[col]删除旧列。


Minimal example:最小的例子:

import pandas as pd

data = {
    'Gender':  ['Female','Male','Female'], 
    'Married': ['Yes','No','Yes'], 
}

df = pd.DataFrame(data)

print('\n--- before ---\n')
print(df)

for col in df.columns:
    result = pd.get_dummies(df[col])

    df = df.join(result)

    #del df[col]
    
print('\n--- after ---\n')
print(df)

Result:结果:

--- before ---

   Gender Married
0  Female     Yes
1    Male      No
2  Female     Yes

--- after ---

   Gender Married  Female  Male  No  Yes
0  Female     Yes       1     0   0    1
1    Male      No       0     1   1    0
2  Female     Yes       1     0   0    1

Columns may have the same values - ie.列可能具有相同的值 - 即。 Yes , No - so you may need to add prefixes to new columns. YesNo - 因此您可能需要为新列添加前缀。

    result = pd.get_dummies(df[col], prefix=col)

Eventually最终

    result = result.add_prefix(f"{col}_")

Minimal example:最小的例子:

import pandas as pd

data = {
    'Gender':  ['Female','Male','Female'], 
    'Married': ['Yes','No','Yes'],
    'Self_Employed': ['No','Yes','Yes'],
}

df = pd.DataFrame(data)

print('\n--- before ---\n')
print(df)

for col in df.columns:
    result = pd.get_dummies(df[col], prefix=col)
    #result = result.add_prefix(f"{col}_")

    df = df.join(result)

    #del df[col]

print('\n--- after ---\n')
print(df.to_string())

Result:结果:

--- before ---

   Gender Married Self_Employed
0  Female     Yes            No
1    Male      No           Yes
2  Female     Yes           Yes

--- after ---

   Gender Married Self_Employed  Gender_Female  Gender_Male  Married_No  Married_Yes  Self_Employed_No  Self_Employed_Yes
0  Female     Yes            No              1            0           0            1                 1                  0
1    Male      No           Yes              0            1           1            0                 0                  1
2  Female     Yes           Yes              1            0           0            1                 0                  1

EDIT:编辑:

You can do the same witthout for -loop usin columns= in get_dummies()您可以在get_dummies()for -loop 使用columns=执行相同的操作

all_results = pd.get_dummies(df, columns=df.columns) #, drop_first=True)
df = df.join(all_results)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 谁能告诉我为什么我在SOAPpy中遇到此错误? - Can anyone tell me why I'm getting this error in SOAPpy? 如何在 Pandas 中将文本拆分为列而不收到“列必须与键长度相同”错误消息? - How do I split text to columns in Pandas without getting "Columns must be same length as key" error message? 谁能帮我理解为什么我有错误“列表索引超出范围”? - Can anyone help me to understand why i have the error “list index out of range”? 谁能告诉我为什么我会收到此错误?,我已经安装了datareader软件包 - can anyone tell me why i'm getting this error ?, i already install datareader package 我正在用 python 尝试一些新的东西,但没有用,谁能帮我弄清楚为什么这个函数只打印 data[0]? - I'm trying something new with python but isn't working, can anyone help me figure out why the function only prints data[0]? 谁能告诉我为什么我的else语句出现无效的语法错误? - Can anyone please tell me why I'm getting an invalid syntax error with my else statement? 为什么我收到 OmegaExpansion header 的 Python 模块错误。 谁能帮我? - why am i getting Python Module error for OmegaExpansion header. Can anyone help me? 获取 ValueError:列的长度必须与键的长度相同 - Getting ValueError: Columns must be same length as key 我得到“数组必须都是相同的长度”。 有人可以帮我理解问题出在哪里以及如何解决吗? - I am getting "arrays must all be the same length". Can someone please help me understand where the problem lies and how to fix it? 我在pygame中创建移动平台时遇到了麻烦。 我遇到错误,有人可以帮我吗? - I am having trouble creating moving platforms in pygames. I am getting an error, can anyone help me out please?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM