1

I started working with CSV files in Python and I want to learn how to manipulate them correctly. I want to learn how to manage large amounts of data such this CSV file found here Sacramento Crime January 2006 with 7,548 crime records.

Basically I want to turn it into a table containing the first row as header (name, ID, latitude etc.) and all other values under it. I used the code from this question which is similar to mine but does not work entirely.

According to that question I should have the name of the header followed by its contents but I get:

{'address': [], 'etc': []} []

When I should be getting {{'adress':[]]} ['addresses in CSV file( 7k etc)']

Also it is all in one line when I want it to look like

Name ID Latitude etc
John 55 -4.56777 etc

whilst all my CSV file is like this:

cdatetime,address,district,beat,grid,crimedescr,ucr_ncic_code,latitude,longitude
1/1/06 0:00,3108 OCCIDENTAL DR,3,3C     

Currently I only have worked on what is found in the answer of the linked question but I have been struggling for a while to find a way. By the way I am really new to Python, as in I just learned how to open, read, write files etc. Also should I be using import pandas or import csv. Which is better?

Community
  • 1
  • 1
Maiels
  • 47
  • 1
  • 11
  • 1
    I'd recommend you learn some pandas. Go to something like datacamp or some other education site to learn the basics if you struggling to find somewhere. But you can import csv files with pandas using the read_csv method. – Aklys Apr 17 '17 at 10:51
  • `{['address': []]} []` is not a valid python expression, you can't get that. – Tamas Hegedus Apr 17 '17 at 10:55
  • @TamasHegedus edited the post, my mistake, sorry. – Maiels Apr 17 '17 at 12:20
  • @Aklys, thank you, I will look into it. – Maiels Apr 17 '17 at 12:21
  • If you found the solution yourself, feel free to add it as an answer to your own question! This way it will be more useful to others in the future. – mkrieger1 Apr 17 '17 at 15:58

1 Answers1

1

I found a solution to my question. Much more simple than I thought, using pandas that is. I had no idea it is so useful for manipulating CSV files.

import pandas as pd

path=("path to csv file")
table= pd.read_csv(path, header='infer', sep=',')
print(table)

You might need to change your separator and depending on your file you might need to change the value of you header(0 and infer are default). This was the following result

cdatetime           adress        district beat   etc.
1/1/06 0:00    3108 OCCIDENTAL DR      3      3C  etc.
Maiels
  • 47
  • 1
  • 11