前言
用一个小例子,看看Python和Java读取CSV文件并进行数据分析时的代码量和难度。
假设我们有一个CSV文件,其中包含某个城市每个月的平均温度和降雨量数据。我们需要读取这个CSV文件,并计算该城市每年的平均温度和降雨量。以下是使用Python和Java分别实现这个任务的代码。
(文末有惊喜)
Python代码:
import pandas as pd
# 读取CSV文件
df = pd.read_csv("city_weather.csv")
# 计算每年的平均温度和降雨量
df["year"] = pd.to_datetime(df["date"]).dt.year
yearly_data = df.groupby("year").mean()
print(yearly_data)
(文末有惊喜)
Java代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CityWeatherAnalysis {
public static void main(String[] args) throws IOException {
// 读取CSV文件
BufferedReader reader = new BufferedReader(new FileReader("city_weather.csv"));
String line = reader.readLine();
Map<Integer, Double> tempSumByYear = new HashMap<>();
Map<Integer, Double> rainSumByYear = new HashMap<>();
Map<Integer, Integer> countByYear = new HashMap<>();
while ((line = reader.readLine()) != null) {
String[] fields = line.split(",");
int year = Integer.parseInt(fields[0].substring(0, 4));