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

Python新手:DataFrame格式化打印结果异常问题求助

Fixing Your Pandas Output Formatting Issue

Let's break down what's going wrong and fix it step by step:

1. The Root Cause of the Weird Output

Looking at your code, the most likely culprit is that you accidentally created duplicate columns (you included EMPLCNT twice in your columns list when initializing the DataFrame). While this doesn't directly break accessing CITY or CONTRCNT, it can lead to unexpected behavior in some pandas versions, and more importantly, it's unnecessary.

Additionally, if you had multiple rows with the same maximum CONTRCNT value (luckily you don't here), using idxmax() would only return the first occurrence—but if you accidentally used boolean indexing (like df[df['CONTRCNT'] == df['CONTRCNT'].max()]), you'd get a DataFrame instead of a Series, which would cause the weird output you're seeing when accessing columns (since you'd be printing a Series instead of a scalar value).

2. Corrected Code

Let's fix the duplicate columns and use clean string formatting to get your desired output:

import pandas as pd

customers = {
    'NAME': ['Breadpot', 'Hoviz', 'Hovis', 'Grenns', 'Magnolia', 'Dozen', 'Sun'],
    'CITY': ['Sydney', 'Manchester', 'London', 'London', 'Chicago', 'San Francisco', 'San Francisco'],
    'COUNTRY': ['Australia', 'UK', 'UK', 'UK', 'USA', 'USA', 'USA'],
    'CPERSON': ['Sam.Keng@info.com', 'harry.ham@hoviz.com', 'hamlet.host@hoviz.com', 'grenns@grenns.com', 'man@info.com', 'dozen@dozen.com', 'sunny@sun.com'],
    'EMPLCNT': [250, 150, 1500, 200, 1024, 1000, 2000],
    'CONTRCNT': [48, 7, 12800, 12800, 25600, 5, 2],
    'CONTRCOST': [1024.00, 900.00, 10510.50, 128.30, 512000.00, 1000.20, 10000.01]
}

# Remove duplicate 'EMPLCNT' from columns list
df = pd.DataFrame(customers, columns=['CITY', 'COUNTRY', 'CPERSON', 'EMPLCNT', 'CONTRCNT', 'CONTRCOST'])

# Get the row with the maximum number of contracts
max_contract_row = df.loc[df['CONTRCNT'].idxmax()]

# Format the output exactly as you want using f-strings
city = max_contract_row['CITY']
contract_count = max_contract_row['CONTRCNT']
print(f'City with largest number of contracts: "{city}" ({contract_count} contracts)')

3. Output

This will produce exactly the format you requested:

City with largest number of contracts: "Chicago" (25600 contracts)

4. Handling Multiple Rows with Maximum Contracts

If there were multiple cities with the same highest number of contracts, you could modify the code to print all of them:

max_contract_value = df['CONTRCNT'].max()
max_contract_rows = df[df['CONTRCNT'] == max_contract_value]

print('Cities with largest number of contracts:')
for _, row in max_contract_rows.iterrows():
    print(f'"{row["CITY"]}" ({row["CONTRCNT"]} contracts)')

This way, you'll cover both single and multiple maximum cases cleanly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 06:43:11