Pandas创建变量报错:Wrong number of items passed问题解析与解决
ValueError: Wrong number of items passed X, placement implies 1 in Pandas Hey there! Let's break down this error and get your binary column working correctly.
What the Error Means
That ValueError is telling you a simple mismatch: you're trying to assign multiple values per row to a single new column (which only expects one value per row). In your case, np.where is receiving a multi-column DataFrame (3 or 12 columns, depending on your filter) instead of a single "yes/no" signal for each row, so it can't fit that into one column.
Why This Happens in Your Code
Look at your np.where line:
np.where(df[(df['var_1'].isin(list)) & (df['var2'] >= '2000-01-01') & ...],'yes','No')
You've wrapped your entire condition inside df[], which returns a subset of your original DataFrame (all columns for rows that match the condition) instead of a simple boolean Series (a single True/False value for every row indicating if it meets the criteria). That multi-column DataFrame is what's causing the "wrong number of items" error.
How to Fix It
You need to pass a boolean Series directly to np.where, not a filtered DataFrame. Here's the corrected code:
import pandas as pd import numpy as np # First, define your condition as a boolean Series (no extra df[] wrapper!) # Note: Fixed var2 -> var_2 to match the next condition, and renamed 'list' to avoid conflict with Python's built-in type condition = (df['var_1'].isin(some_list)) & \ (df['var_2'] >= '2000-01-01') & \ (df['var_2'] <= '2000-12-31') & \ (df['var_3'] > 0) & \ (df['var_4'] == 'OK') # Now assign the new column using np.where with the boolean condition df['yes/no'] = np.where(condition, 'Yes', 'No')
Key Fixes:
- Removed the outer
df[]around your condition: nowconditionis a 1-dimensional boolean Series where each entry isTrueif the row meets all your criteria,Falseotherwise. - Renamed
listtosome_list:listis a built-in Python type, so using it as a variable name can cause unexpected issues. - Fixed a possible typo: you had
var2in one condition andvar_2in the next—make sure these are the correct column names from your CSV!
Verify It Works
If you run condition on its own, it should output a Series with the same number of rows as your original DataFrame, filled with True/False values. This is exactly what np.where needs to assign the correct 'Yes'/'No' value to each row in your new column.
内容的提问来源于stack exchange,提问作者BENAMARA ILAN

