【问题标题】:Filter column value from multiple csv files using python(pandas)使用 python(pandas) 从多个 csv 文件中过滤列值
【发布时间】:2018-11-05 20:19:06
【问题描述】:

CITY_DATA = { 'chicago': 'chicago.csv','纽约城': 'new_york_city.csv','washington': 'washington.csv' }

要求用户指定要分析的城市、月份和日期。

Returns:
    (str) city - name of the city to analyze
    (str) month - name of the month to filter by, or "all" to apply no month filter
    (str) day - name of the day of week to filter by, or "all" to apply no day filter

待办事项:获取城市(芝加哥、纽约市、华盛顿)的用户输入。提示:使用 while 循环处理无效输入

这是芝加哥的前 5 行,下面是 3 个 csv 文件之一。我的问题是每个城市总共有 3 个 csv 文件。如何从不同的文件中过滤列值(城市/月/日)?如果使用循环,我对所有城市或 12 个月或 7 天使用 if、elif、elif.... 似乎是错误的。抱歉,我是 Python 新手,对此我感到头晕目眩。请帮忙解答或提示。谢谢。

            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  

下面的代码有什么问题?应该在 if 语句之后放置 city=input('Enter a city') 吗?困惑。

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' }
def get_city():
    print("Hello! Let's explore some US bikeshare data! \n Which city would you like? \n Chicago, New York City or Washington? ")
cities = ['chicago', 'new york city', 'washington']
city = input('Enter a city: ')
Enter a city: san jose

if city == 'chicago':
    return chicago
elif city == 'new york city':
    return new_york_city
elif city == 'washington':
    return washington
else:
    print ('Ops, your enter is out of range.')

File "<ipython-input-14-335bd5bdf8dc>", line 2
    return chicago
    ^
SyntaxError: 'return' outside function

【问题讨论】:

  • 你的数据在哪里?
  • 请把它放在不会出现严重格式错误的问题中。
  • 如何把数据放在这里?有 3 个大的 csv 文件。这是列名和第一行。开始时间 结束时间 旅行持续时间 开始站 结束站 用户类型 性别 出生年份 6/23/2017 15:09 6/23/2017 15:14 321 Wood St & Hubbard St Damen Ave & Chicago Ave 订户 男性 1992
  • 编辑您的问题并添加前 5-10 行。
  • HINT: Use a while loop to handle invalid input。这是你的暗示吗?还是老师提供的作业规则?

标签: python pandas filter


【解决方案1】:

这是 Udacity 的数据分析项目。我就是这样做的。

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' }

def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.

    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """
    print('Hello! Let\'s explore some US bikeshare data!')

    cities = ['chicago', 'new york city', 'washington']
    cond = 0
    while cond != 1:
        city = input("Which city would you like? ")
        city = city.lower()
        if city in cities:
            cond = 1
        else:
            cond = 0



        # TO DO: get user input for month (all, january, february, ... , june)
    months = ['all' , 'january', 'february', 'march','april','may','june','july','august','september''october','november','december']
    cond = 0
    while cond != 1:
        month = input("Which month would you like? ")
        month = month.lower()
        if month in months:
            cond = 1
        else:
            cond = 0



        # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
    days = ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday','sunday']
    cond = 0
    while cond != 1:
        day = input("Which day would you like? ")
        day = day.lower()
        if day in days:
            cond = 1
        else:
            cond = 0



    print('-'*40)
    return city, month, day

【讨论】:

  • 谢谢。我不太明白 cond =0 和 cond=1 是什么意思。
  • 是while循环的条件语句。您可以改用布尔值。 while 循环一直运行,直到接受的输入是给定日期、月份或城市的用户输入之一。
  • 您需要使用 while 循环,因为此人可以在城市中进行多次无效尝试。我将城市输入设置为 city.lower() 因为芝加哥就是芝加哥。
猜你喜欢
  • 1970-01-01
  • 2018-03-29
  • 1970-01-01
  • 2016-05-11
  • 1970-01-01
  • 2017-07-31
  • 1970-01-01
  • 2017-03-07
  • 2021-09-23
相关资源
最近更新 更多