473,287 Members | 1,419 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

CSV to Array

i have a csv file that has a number in one column and a corresponding number in the second column. i am trying to store both of these numbers in an array. i have done this before with an excel file but how would i go about doing this with a csv file since the command xlsht wont work in csv. here is my code so far to print everything but how do i store them in an array and what would be the correct way to define the array.

Expand|Select|Wrap|Line Numbers
  1. import csv
  2. reader = csv.reader(open("C:\Fahad\New\Dtap.csv", "rb"))
  3. for row in reader:
  4.     print row
  5.  
Nov 2 '07 #1
5 8828
ok i did figure out how to store it in an array but how do i store it as a number. it looks like python is just treating it like a character instead of a number.
also i want the array size to be equal to the number of columns in the csv file what would be the correct way to define that?
Nov 2 '07 #2
bartonc
6,596 Expert 4TB
ok i did figure out how to store it in an array but how do i store it as a number. it looks like python is just treating it like a character instead of a number.
also i want the array size to be equal to the number of columns in the csv file what would be the correct way to define that?
Here's a trick that I use. I hope you find it useful:
Expand|Select|Wrap|Line Numbers
  1. >>> data = ['12.2', 'hello', '7']
  2. >>> converters = (float, str, int)
  3. >>> for i, item in enumerate(data):
  4. ...     print converters[i](item)
  5. ...     
  6. 12.2
  7. hello
  8. 7
  9. >>> 
Nov 2 '07 #3
bvdet
2,851 Expert Mod 2GB
This function is useful when you do not know the types of the data items:
Expand|Select|Wrap|Line Numbers
  1. def convertType(s):
  2.         for func in (int, float, eval):
  3.             try:
  4.                 n = func(s)
  5.                 return n
  6.             except:
  7.                 pass
  8.         return s
Expand|Select|Wrap|Line Numbers
  1. >>> data = ['12.2', 'hello', '7', '[12,24,36,"goodbye"]', '12*12']
  2. >>> for item in data:
  3. ...     print convertType(item)
  4. ...     
  5. 12.2
  6. hello
  7. 7
  8. [12, 24, 36, 'goodbye']
  9. 144
  10. >>> 
Nov 2 '07 #4
bartonc
6,596 Expert 4TB
This function is useful when you do not know the types of the data items:
Expand|Select|Wrap|Line Numbers
  1. def convertType(s):
  2.         for func in (int, float, eval):
  3.             try:
  4.                 n = func(s)
  5.                 return n
  6.             except:
  7.                 pass
  8.         return s
Expand|Select|Wrap|Line Numbers
  1. >>> data = ['12.2', 'hello', '7', '[12,24,36,"goodbye"]', '12*12']
  2. >>> for item in data:
  3. ...     print convertType(item)
  4. ...     
  5. 12.2
  6. hello
  7. 7
  8. [12, 24, 36, 'goodbye']
  9. 144
  10. >>> 
Nice touch, throwing in the eval! I really like it!
Nov 2 '07 #5
bvdet
2,851 Expert Mod 2GB
Nice touch, throwing in the eval! I really like it!
I actually use this in almost every script run in SDS/2. We import data from a text file formatted like this:

#Python Script Default File
access_hole_height=1.25
access_hole_length=1.25
access_hole_radius=0.5
flange_setback_bott=6.5
flange_setback_top=6.5
flush_lower_left=0.0
flush_lower_right=0.0
flush_upper_left=0.5
flush_upper_right=0.5
prep_angle=45.0
prep_list=['Top Left', 'Bottom Left']
print_doc=No
Here's the actual code used:
Expand|Select|Wrap|Line Numbers
  1. def fdim(s):
  2.     ss = s.split('/')
  3.     return float(ss[0])/float(ss[1])
  4.  
  5. def convertType(s):
  6.         for func in (int, float, fdim, eval):
  7.             try:
  8.                 n = func(s)
  9.                 return n
  10.             except:
  11.                 pass
  12.         return s
  13.  
  14. def import_data(file_name):
  15.     patt = r'.+=.+'
  16.     try:
  17.         data = [item.strip().split('=') for item in re.findall(patt, open(file_name).read()) if not item.startswith('#')]
  18.         return dict(zip([j[0].strip() for j in data], [convertType(i[1].strip()) for i in data]))
  19.     except:
  20.         Warning("User default file import error. Reverting to auto or initial defaults...")
  21.         return None
It returns a dictionary with the values of the correct types. The 'eval()' was necessary to convert saved lists, and the 'fdim()' to convert fractions that were saved to disk as strings.
Nov 2 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Brian | last post by:
I'm diddlying with a script, and found some behavior I don't understand. Take this snippet: for ($i = 0; $i <= count($m); $i++) { array_shift($m); reset($m); }
2
by: Stormkid | last post by:
Hi Group I'm trying to figure out a way that I can take two (two dimensional) arrays and avShed and shed, and subtract the matching elements in shed from avShed I've pasted the arrays blow from a...
15
by: lawrence | last post by:
I wanted to test xml_parse_into_struct() so I took the example off of www.php.net and put this code up on a site: <?php $simple = <<<END <item>
8
by: vcardillo | last post by:
Hello all, Okay, I am having some troubles. What I am doing here is dealing with an employee hierarchy that is stored in an array. It looks like this: $employees = array( "user_id" => array(...
12
by: Sam Collett | last post by:
How do I remove an item with a specified value from an array? i.e. array values 1,2,2,5,7,12,15,21 remove 2 from array would return 1,5,7,12,15,21 (12 and 21 are NOT removed, duplicates are...
8
by: Mike S. Nowostawsky | last post by:
I tried using the "toUpperCase()" property to change the value of an array entity to uppercase BUT it tells me that the property is invalid. It seems that an array is not considered an object when...
58
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of...
104
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from...
7
by: Jim Carlock | last post by:
Looking for suggestions on how to handle bad words that might get passed in through $_GET variables. My first thoughts included using str_replace() to strip out such content, but then one ends...
17
by: =?Utf-8?B?U2hhcm9u?= | last post by:
Hi Gurus, I need to transfer a jagged array of byte by reference to unmanaged function, The unmanaged code should changed the values of the array, and when the unmanaged function returns I need...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.