Question

How to make a table from a csv file without using prettytable or pandas. I have...

How to make a table from a csv file without using prettytable or pandas. I have to use format I'm trying to...

I'm trying to get a column for "Type", "Total", and "Percent" from TipJoke.csv file.

import csv
with open('TipJoke.csv', newline='') as csv_file:
filereader = csv.reader(csv_file, delimiter=' ')
for row in filereader:
print( '{:2} {:3} {:4}'.format('Type', 'Total', 'Percent'))
print(', '.join(row))

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

CODE:

import pandas as pd

df=pd.read_csv('data/My_Data/Chegg/TipJoke.csv')#Loading the csv file into dataframe

print(df.head())#Viewing the basic format of dataframe or the file

total_items=len(df) #To get the total items for calculating percentage

df['Card'].value_counts()#It gives us the count of each item in card

items=[]for type in df['Card'].unique():

total=df['Card'].value_counts().loc[type]#Getting the count of each items

percent=total/total_items#Calculating the percentage and below we are formating as given

type='{:2}'.format(type)

total='{:3}'.format(total)

percent='{:4}'.format(percent)

items.append([type,total,percent])

table=pd.DataFrame(items,columns=['Type','Total','Percent'])#Creating DataFrame to form table with given data and columns

print(table)#Priniting the table

OUTPUT:

Add a comment
Know the answer?
Add Answer to:
How to make a table from a csv file without using prettytable or pandas. I have...
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
  • --------__--------__Python--------__--------__ You will be reading in the data from the file SalesJan2009.csv. When you do, you...

    --------__--------__Python--------__--------__ You will be reading in the data from the file SalesJan2009.csv. When you do, you need to save all the items from the PRICE field into a list called amtCollected. After you get them all in that list, you will need to create a variable called total that holds the sum of all the numbers in the list. Then create a variable called avg that holds the average of the numbers in the list. Now, print the following strings:...

  • Python with Pandas dataframe I have a csv file that contains a large number of columns...

    Python with Pandas dataframe I have a csv file that contains a large number of columns and rows. I need to write a script that concatenates some elements of the first row with some elements of the 2 row. Something like # if data[1][0] starts with ch then concatenate the element right below it. I have attached a picture of just a sample of my data. The booleans have to stay on there as is. But I must drop the...

  • Pandas DataFrame in Python : I have csv file which has date column with object data...

    Pandas DataFrame in Python : I have csv file which has date column with object data type which ranges from 1908 to 2018: (Original) Date                 (My result) Date                  (I Need) Date                       17-Sep-08                                  2008-09-17                 1908-09-17 7-Sep-09                                    2009-09-07                  1909-09-07 .    (more years)                         .   (more years)               .     .                                                 .                                      . 8-Nov-07                                       2007-11-07                 2007-11-07 23-Sep-08                                     2008-09-23                 2008-09-23 29-Dec-18                                     2018-12-29                 2018-12-29 When I am converting it to datetime64[ns] or/and adding column as year after extracting just year values from date...

  • ## python pandas # i want to print ALL of the columns import quandl import math...

    ## python pandas # i want to print ALL of the columns import quandl import math import pandas as pd df = quandl.get('WIKI/GOOGL') df['HL_PCT'] = df['Adj. High'] - df['Adj. Low']/ df['Adj. Close'] df['PCT_CH'] = df['Adj. Close'] - df['Adj. Open']/ df['Adj. Open'] print(df.head()) thon 3.7.0 Shell workthrough 1.p. X Edit Shell Debug Options Window Help РСт CH File Edit Format Run Options Adi, Volume Open High Low HL_PCT .. Heln dow 2004-08-19 100.01 104.06 95.96 44659000.0 51.234713 49.322842 quandl import math...

  • I'm working with Java and I have a error message  1 error Error: Could not find or...

    I'm working with Java and I have a error message  1 error Error: Could not find or load main class Flowers. This is the problem: Instructions Make sure the source code file named Flowers.java is open. Declare the variables you will need. Write the Java statements that will open the input file, flowers.dat, for reading. Write a while loop to read the input until EOF is reached. In the body of the loop, print the name of each flower and where...

  • I have my assignment printing, but I can find why the flowers is printing null and...

    I have my assignment printing, but I can find why the flowers is printing null and not the type of flower. Instructions Make sure the source code file named Flowers.java is open. Declare the variables you will need. Write the Java statements that will open the input file, flowers.dat, for reading. Write a while loop to read the input until EOF is reached. In the body of the loop, print the name of each flower and where it can be...

  • Python function: This is my code and I don't know how to add the column to...

    Python function: This is my code and I don't know how to add the column to the csv file: def write_with_averages(read,write): with open (read,'r') as f_in: header = f_in.readline() reader=csv.reader(f_in) with open (write,'w') as f_out: writer=csv.writer(f_out) New_data=[] for Name, Test1, Test2, Test3 in reader: Total=(float(Test1)+float(Test2)+float(Test3)) average=Total/3 New_data.append(average) Hint: Skip the first line of the file as it is a header line Hint: All values come in as strings, so convert to floats before mathematical comparisons and calculations. File Format Name,Test1,Test2,Test3...

  • Hello can somebody please help me with Project 15-3 File Cleaner assignment? This project is to...

    Hello can somebody please help me with Project 15-3 File Cleaner assignment? This project is to be done while using Java programming. Here are what the assignment says… Create an application that reads a file that contains an email list, reformats the data, and writes the cleaned list to another file. Below are the grading criteria… Fix formatting. The application should fix the formatting problems. Write the File. Your application should write a file named prospects_clean.csv. Use title case. All...

  • 1. Create a table that will hold the data in avgprice kwh state.csv. This .csv file...

    1. Create a table that will hold the data in avgprice kwh state.csv. This .csv file contains the annual data from 1990-2012 on the average energy price per kilowatt hour (KwH) by state and provider type. Implement the following queries: • Print each row that has Tennessee as state, order the result by year in descending order. • Print the average residential, commercial, industrial, and transportation price for the state of Texas from the year 1990-2012. 2. Create the tables...

  • HELP! HOW WOULD I WRITE THIS IN PSEUDOCODE? from itertools import accumulate from collections import Counter...

    HELP! HOW WOULD I WRITE THIS IN PSEUDOCODE? from itertools import accumulate from collections import Counter def addvalues(a, b): if type(a) is str: a = a.strip("\n") if type(b) is str: b = b.strip("\n") return int(a) + int(b) def maxValues(a, b): if type(a) is str: a = a.strip("\n") if type(b) is str: b = b.strip("\n") a = int(a) b = int(b) return max(a, b) def main(): counter = 0 total = 0 maximum_cars = 0 file = open("MainAndState.dat", "r") maximum =...

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