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

如何修复Pandas中访问'preco_ordem'列时的KeyError错误

Fixing KeyError: 'preco_ordem' in Pandas CSV Import

Looks like you ran into a classic encoding-related column name mismatch! Let's break down what's happening and fix it step by step.

The Root Cause

Looking at your sample data output, the actual column name for the price field is preÂ�o_ordem, not preco_ordem as you tried to reference. This is an encoding glitch from reading the CSV file—special characters like õ got mangled when parsed with unicode_escape, leading to a mismatched column name that Pandas can't locate.

Step 1: Verify Your Column Names

First, confirm exactly what column names Pandas is interpreting by running this right after importing the CSV:

print(all_trades.columns.tolist())

This will print the full list of column names, including the mangled one for the price field.

Step 2: Fix the Column Name Reference

You have two clean ways to resolve this:

Option A: Rename Columns During Import (Recommended)

Define the correct column names upfront when reading the CSV to avoid dealing with mangled names entirely:

all_trades = pandas.read_csv(
    './ccmx18hf .csv',
    parse_dates={'Date': [0,1]},
    index_col=0,
    encoding='unicode_escape',
    # Manually set the correct column names to replace the mangled ones
    names=['order_side', 'preco_ordem', 'quant_total', 'quant_neg', 'status'],
    header=0  # Skip the original mangled header row
)

Now you can safely reference all_trades['preco_ordem'] without any KeyError.

Option B: Rename Columns After Import

If you prefer to keep the original import code, rename the mangled column after loading the data:

all_trades = all_trades.rename(columns={'pre�o_ordem': 'preco_ordem'})

(Make sure to use the exact mangled name you saw from print(all_trades.columns) here.)

Step 3: Fix the Price Column Data Processing

While you're at it, notice your price values use commas as decimal separators (like 39,36). Your current cleanup function won't handle this correctly—you'll need to replace commas with periods before converting to float:

def cleanup(x):
    if isinstance(x, str):
        # Replace commas with decimal points first
        x = x.replace(',', '.')
        if 'e-' in x:
            return 0.0
    # Add a try/except to handle any unexpected values gracefully
    try:
        return float(x)
    except (ValueError, TypeError):
        return 0.0

Full Corrected Code

Putting it all together, here's your updated code that should work without errors:

from itertools import zip_longest
import itertools
import pandas
import numpy as np
import matplotlib.pyplot as plt

# Import CSV with corrected column names
all_trades = pandas.read_csv(
    './ccmx18hf .csv',
    parse_dates={'Date': [0,1]},
    index_col=0,
    encoding='unicode_escape',
    names=['order_side', 'preco_ordem', 'quant_total', 'quant_neg', 'status'],
    header=0
)

print(all_trades.head())

volume = all_trades['quant_total']
print(volume.head())

# Now we can access the price column without KeyError
trades = all_trades['preco_ordem']

def cleanup(x):
    if isinstance(x, str):
        x = x.replace(',', '.')
        if 'e-' in x:
            return 0.0
    try:
        return float(x)
    except (ValueError, TypeError):
        return 0.0

# Process volume column
volume = volume.apply(lambda x: cleanup(x))
volume = volume.astype(np.float32)

# Process trades column too
trades = trades.apply(lambda x: cleanup(x))
trades = trades.astype(np.float32)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:10:21