You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas DataFrame值循环转换报错求助:将n/y/?转为0/1/0

Solution for Converting Categorical Values (n/y/?) to Numeric in Pandas DataFrame

Got it, let's fix this issue step by step. First, the error you're seeing happens because when you use df.names in your loop, Python is trying to access an attribute named names on the DataFrame (which doesn't exist) instead of the column whose name is stored in your names variable. You need to use bracket notation df[names] to dynamically access columns by their name.

Fixed Loop Approach

Here's your original code adjusted to work correctly:

for col_name in df.columns.values:
    # Replace 'n'→0 and 'y'→1 first
    df[col_name].replace(('n', 'y'), (0, 1), inplace=True)
    # Replace '?'→0 next
    df[col_name].replace('?', 0, inplace=True)
    # Convert the column to integer type explicitly
    df[col_name] = df[col_name].astype(int)

More Efficient One-Liner Approach

Instead of looping through each column manually, you can handle all columns in one go with a single replace call—this is cleaner and faster for large DataFrames:

# Define a mapping dictionary for all values
value_mapping = {'n': 0, 'y': 1, '?': 0}
# Apply the mapping to the entire DataFrame and convert to integers
df = df.replace(value_mapping).astype(int)

Alternative: Using applymap

If you prefer a functional approach, applymap lets you apply a custom function to every element in the DataFrame:

def convert_to_numeric(val):
    return 1 if val == 'y' else 0
    # This handles both 'n' and '?' cases by returning 0

df = df.applymap(convert_to_numeric).astype(int)

Verify the Result

After running any of these methods, you can check the output with df.head() to confirm all values are now integers:

party infants water budget physician salvador religious satellite aid missile immigration synfuels education superfund crime duty_free_exports eaa_rsa
0       0       1     0       1         1        1          0         0   0       0            1         0         1         1     1                  0       1
1       0       1     0       1         1        1          0         0   0       0            0         0         1         1     1                  0       0
2       0       1     1       0         1        1          0         0   0       0            0         1         0         1     1                  0       0
3       0       1     1       0         0        1          0         0   0       0            0         1         0         1     0                  0       1
4       1       1     1       0         1        1          0         0   0       0            0         1         0         1     1                  1       1

内容的提问来源于stack exchange,提问作者JL1829

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:05:06