我试图从 3 个城市提取数据。如何读取所有 3 个城市的数据,而不是在下面一一读取?我是否有重复的代码来读取下面的数据?如何从字典中读取数据以避免错误?非常感谢。
import csv
with open('C:\\Users\\jasch\\chicago.csv') as chicago_data:
csvReader = csv.reader(chicago_data)
import csv
with open('C:\\Users\\jasch\\new_york_city.csv') as new_york_data:
csvReader = csv.reader(new_york_data)
import csv
with open('C:\\Users\\jasch\\washington.csv') as washington_data:
csvReader = csv.reader(washington_data)
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
df = pd.read_csv(CITY_DATA[city])
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
print (df['month'])
NameError Traceback (most recent call last)
<ipython-input-16-b1588646f194> in <module>()
7 'washington': 'washington.csv' }
8
----> 9 df = pd.read_csv(CITY_DATA[city])
10
11 df['Start Time'] = pd.to_datetime(df['Start Time'])
NameError: name 'city' is not defined
3.城市数据的csv文件下面的列名几乎相同。
Start Time End Time Trip Duration \
0 2017-05-29 18:36:27 2017-05-29 18:49:27 780
1 2017-06-12 19:00:33 2017-06-12 19:24:22 1429
2 2017-02-13 17:02:02 2017-02-13 17:20:10 1088
3 2017-04-24 18:39:45 2017-04-24 18:54:59 914
4 2017-01-26 15:36:07 2017-01-26 15:43:21 434
Start Station End Station \
0 Columbus Dr & Randolph St Federal St & Polk St
1 Kingsbury St & Erie St Orleans St & Merchandise Mart Plaza
2 Canal St & Madison St Paulina Ave & North Ave
3 Spaulding Ave & Armitage Ave California Ave & Milwaukee Ave
4 Clark St & Randolph St Financial Pl & Congress Pkwy
User Type Gender Birth Year
0 Subscriber Male 1991.0
1 Customer NaN NaN
2 Subscriber Female 1982.0
3 Subscriber Male 1966.0
4 Subscriber Female 1983.0