'How can I display five rows of data based on user in Python?

df = pd.read_csv(CITY_DATA[city])

def user_stats(df,city):
    """Displays statistics of users."""

    print('\nCalculating User Stats...\n')

    start_time = time.time()

    print('User Type Stats:')
    print(df['User Type'].value_counts())

    if city != 'washington':
        print('Gender Stats:')
        print(df['Gender'].value_counts())

        print('Birth Year Stats:')

        most_common_year = df['Birth Year'].mode()[0]
        print('Most Common Year:',most_common_year)

        most_recent_year = df['Birth Year'].max()
        print('Most Recent Year:',most_recent_year)

        earliest_year = df['Birth Year'].min()
        print('Earliest Year:',earliest_year)

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

I want to ask the user in the first step: "Do you want to see the first 5 rows of data?". if He typed yes it will show the first 5 rows, then it asks user again " Do you want to see the next 5 rows of data?" then he says yes and it shows the next 5 data. I need to keep asking until he says no.

Hints:
-We will show the data based on the location. namely, we will show the first 5 data in the first attempt, then the second 5 data for the second "yes" So we need to keep track of this. How? (I used start_loc variable)
-Please check the iloc function. It returns dataframe based on the position. For example, df.iloc[0:5] will return the first 5 rows of data.

Can I do it using the following code:

view_data = input('\nWould you like to view 5 rows of individual trip data? Enter yes or no\n')
start_loc = 0
while (?????):
    print(df.iloc[????:????])
    start_loc += 5
    view_display = input("Do you wish to continue?: “).lower()


Solution 1:[1]

Something like this?

  1. use your variable start_loc inside the iloc
  2. just assign a boolean to your for loop, which you set to false if user types "no"
view_data = input('\nWould you like to view 5 rows of individual trip data? Enter yes or no\n')
start_loc = 0
keep_asking = True
while (keep_asking):
    print(df.iloc[start_loc:start_loc + 5])
    start_loc += 5
    view_display = input("Do you wish to continue?: ").lower()
    if view_display == "no": 
        keep_asking = False

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sandsten