Question

Write a function in python that will take in a df (dataframe) and n (integer that...

Write a function in python that will take in a df (dataframe) and n (integer that determines the number of rows that the returned df will display):

create a new dataframe df1 by copying the input df, with only two columns "fruit" and "price" from the original df. Then add two new columns to df1 labeled "brand" and "time of purchase" and assign values appropriately.

Return df1

NOTE: If n= -1, return all the rows. If n ≥ 0 return df1 with n rows

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code:

def function1(df,n):    #this function in used for returning number of rows in argument 2
    if n==-1:            #if n is -1 then returned df as it is
        return df
    else:
        return df[:n]    #otherwise return dataframe with n rows using slicing like that

def function2(df):        #this function is used for copying one data frame to another with only 2 columns 
    df1=df[['fruit','price']]     #that copy fruit and price column with data from df to df1
    df1['brand']=['Fruits']*len(df)       #that insert new column brand in df1 with value of all rows if Fruits
    df1['time of purchase']=['4:00']*len(df)     #that insert new column time of purchase with value 4:00 in all rows
    return df1 

import pandas as pd 

# intialise data with fruit,price and quantity column 
data = {'fruit':['Apple', 'Banana', 'Orange', 'Grapes'], 'price':[20, 21, 19, 18],'Quantiry':[2, 10, 6, 9]} 
  
# Create DataFrame 
df = pd.DataFrame(data) 
function1(df,2)    #that will return dataframe with 2 rows
function2(df)       #that will return dataframe with 4 columns fruit,price and 2 new column brand time of purchase

#this function in used for returning number of rows in argument 2 #if n is -1 then returned df as it is def function1(df,n):

OUTPUT

for function1:

fruit price Quantiry 0 Apple 20 2 1 Banana 21 10

for function2:

fruit price brand time of purchase 0 Apple 20 Fruits 4:00 1 Banana 21 Fruits 4:00 2 Orange 19 Fruits 4:00 3 Grapes 18 Fruits

Add a comment
Know the answer?
Add Answer to:
Write a function in python that will take in a df (dataframe) and n (integer that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • (a) Load the data file data/tips.csv into a pandas DataFrame called tips_df using the pandas read_table()...

    (a) Load the data file data/tips.csv into a pandas DataFrame called tips_df using the pandas read_table() function. Check the first five rows. (b) Create a new dataframe called tips by randomly sampling 6 records from the dataframe tips_df. Refer to the sample() function documentation. (c) Add a new column to tips called idx as a list ['one', 'two', 'three', 'four', 'five', 'six'] and then later assign it as the index of tips dataframe. Display the dataframe. (d) Create a new...

  • Hi team, can you create a python programs for 1. Create DataFrame shape of 300x5 from...

    Hi team, can you create a python programs for 1. Create DataFrame shape of 300x5 from scratch a. Column_1: Generate random 300 floating numbers between 1 and 0 b. Column_2: Generate random 300 integers between 10 and 1000 c. Column_3: multiply column_2 with column_1 d. Column_4: Generate random 300 Ordinal categorical variable with three unique values e. Column_5: Generate random 300 Nominal categorical variable with two unique values 2. Get head, tail of the created data 3. Show mean, max,...

  • For Python debugExercise12.py is a recursive function that accepts an integer argument, n, and prints the...

    For Python debugExercise12.py is a recursive function that accepts an integer argument, n, and prints the numbers 1 up through n. By debugging these programs, you can gain expertise in program logic in general and the Python programming language in particular. def main(): # Local variable number = 0 # Get number as input from the user. number = int(input('How many numbers to display? ')) # Display the numbers. print_num(number) # The print_num function is a a recursive function #...

  • language is python Write a function named subsetStrings that has two inputs, a list of strings...

    language is python Write a function named subsetStrings that has two inputs, a list of strings and an integer n. Your function should use a single list comprehension to create a new list containing the first n characters of each string in the input list if the length of the individual string is at least n (strings that are too short should be skipped). Your function should return the new list ex: inputList 'Frederic, 'powerade', 'spring break, 'pen'] and n-4...

  • USING PYTHON! The second function you will write should be called ‘varOrd’. Your function should take...

    USING PYTHON! The second function you will write should be called ‘varOrd’. Your function should take two (2) arguments, an integer and a string. The function should return one (1) integer calculated as follows. If the input integer is 1, the function should return the sum of the return value of the ord() function on each character of the string (e.g., varOrd(1, ‘cat’) should return the result of ord(‘c’) + ord(‘a’) + ord(‘t’)). If the input integer is 2, the...

  • python Write a function that takes as input a single integer parametern and computes the nth...

    python Write a function that takes as input a single integer parametern and computes the nth Fibonacci Sequence number The Fibonacci sequence first two terms are 1 and 1(so, if n - 2 your function should return 1). From there, the previous two values are summed to come up with the next result in the sequence 1.1,2,3,5,8,13, 21, 34, 55, etc.) For example, if the input is 7 then your function should return 13 26561.1615880 1 def Fibonacci(n): # your...

  • IN PYTHON: Write a function that takes, as an argument, a positive integer n, and returns...

    IN PYTHON: Write a function that takes, as an argument, a positive integer n, and returns a LIST consisting of all of the digits of n (as integers) in the same order. Name this function intToList(n). For example, intToList(123) should return the list [1,2,3].

  • Write a program in Python that accepts as input an integer N and a real number...

    Write a program in Python that accepts as input an integer N and a real number c, and outputs the coefficient of the Nth degree term of the Taylor series for the function f(x) = ex centered at c. This process should recur until the user enters a quit code. Erroneous input should be excepted as necessary, and should result in a new prompt.

  • Q1 SUMMER2020- nts python language Example Write a program to read an integer r then print...

    Q1 SUMMER2020- nts python language Example Write a program to read an integer r then print a triangle with r number of rows using .asterisks Result Input 5 Hint: Use end= parameter of the print function to not add a newline to the end of the string * * * * * * * * * * * * 9 - عام python language Course Information o Course Material Assignments o example input Lab Exercises Quizzes Result 7.0 ACUTE 7.0...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT