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

如何使用Pandas提取2014年灌溉用水量Top10的县?

解决提取2014年灌溉用水量Top10县的问题

Hey there! Let's work through this step by step to get you the top 10 counties with the most irrigation water use in 2014. First, let's fix the small bug in your existing code, then walk through the full workflow.

第一步:修正日期转换的错误

Looking at your code, the line where you convert the Year column to datetime has a tiny mistake—you're passing the string ['Year'] instead of the actual column from your DataFrame. Here's the corrected version:

%matplotlib inline
import csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 读取CSV文件
data = pd.read_csv('info.csv')

# 修正:将Year列转换为日期时间格式(传入data['Year']而非['Year'])
data['Year'] = pd.to_datetime(data['Year'], format='%Y')

第二步:筛选2014年的数据

Now that we have properly formatted dates, we can filter down to only 2014 records. You can either extract the year as a separate column for clarity, or filter directly:

# 方法1:提取年份为单独列(方便后续操作)
data['Year_Num'] = data['Year'].dt.year
data_2014 = data[data['Year_Num'] == 2014]

# 方法2:直接筛选(更简洁)
data_2014 = data[data['Year'].dt.year == 2014]

第三步:排序并提取Top10县

Next, we'll sort the 2014 data by irrigation water use (descending order) and grab the top 10 entries. Important: Replace 'Irrigation_Water_Use' and 'County' with the actual column names from your CSV file (check your data to confirm these!):

# 按灌溉用水量降序排序,取前10个县
top_10_counties = data_2014.sort_values(by='Irrigation_Water_Use', ascending=False).head(10)

# 打印结果(只显示县名和用水量列)
print(top_10_counties[['County', 'Irrigation_Water_Use']])

额外提示(避免踩坑)

  • 处理缺失值: If your data has missing values in the irrigation use column, add this line before sorting to drop those rows:
    data_2014 = data_2014.dropna(subset=['Irrigation_Water_Use'])
    
  • 如果Year列是整数: If your Year column is already stored as an integer (e.g., 2014 instead of the string '2014'), you don't need to convert it to datetime at all—just filter directly:
    data = pd.read_csv('info.csv')
    data_2014 = data[data['Year'] == 2014]
    top_10_counties = data_2014.sort_values(by='Irrigation_Water_Use', ascending=False).head(10)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:42:44