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. -
import csv
-
reader = csv.reader(open("C:\Fahad\New\Dtap.csv", "rb"))
-
for row in reader:
-
print row
-
5 8848
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?
bartonc 6,596
Recognized Expert Expert
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: -
>>> data = ['12.2', 'hello', '7']
-
>>> converters = (float, str, int)
-
>>> for i, item in enumerate(data):
-
... print converters[i](item)
-
...
-
12.2
-
hello
-
7
-
>>>
bvdet 2,851
Recognized Expert Moderator Specialist
This function is useful when you do not know the types of the data items: - def convertType(s):
-
for func in (int, float, eval):
-
try:
-
n = func(s)
-
return n
-
except:
-
pass
-
return s
- >>> data = ['12.2', 'hello', '7', '[12,24,36,"goodbye"]', '12*12']
-
>>> for item in data:
-
... print convertType(item)
-
...
-
12.2
-
hello
-
7
-
[12, 24, 36, 'goodbye']
-
144
-
>>>
bartonc 6,596
Recognized Expert Expert
This function is useful when you do not know the types of the data items: - def convertType(s):
-
for func in (int, float, eval):
-
try:
-
n = func(s)
-
return n
-
except:
-
pass
-
return s
- >>> data = ['12.2', 'hello', '7', '[12,24,36,"goodbye"]', '12*12']
-
>>> for item in data:
-
... print convertType(item)
-
...
-
12.2
-
hello
-
7
-
[12, 24, 36, 'goodbye']
-
144
-
>>>
Nice touch, throwing in the eval! I really like it!
bvdet 2,851
Recognized Expert Moderator Specialist
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_hei ght=1.25
access_hole_len gth=1.25
access_hole_rad ius=0.5
flange_setback_ bott=6.5
flange_setback_ top=6.5
flush_lower_lef t=0.0
flush_lower_rig ht=0.0
flush_upper_lef t=0.5
flush_upper_rig ht=0.5
prep_angle=45.0
prep_list=['Top Left', 'Bottom Left']
print_doc=No
Here's the actual code used: - def fdim(s):
-
ss = s.split('/')
-
return float(ss[0])/float(ss[1])
-
-
def convertType(s):
-
for func in (int, float, fdim, eval):
-
try:
-
n = func(s)
-
return n
-
except:
-
pass
-
return s
-
-
def import_data(file_name):
-
patt = r'.+=.+'
-
try:
-
data = [item.strip().split('=') for item in re.findall(patt, open(file_name).read()) if not item.startswith('#')]
-
return dict(zip([j[0].strip() for j in data], [convertType(i[1].strip()) for i in data]))
-
except:
-
Warning("User default file import error. Reverting to auto or initial defaults...")
-
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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);
}
|
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 print_r cmd any
suggestions would be great. Thanks much Todd
//avShed array
Array ( => Array ( => 1 => 08:00 ) => Array
( => 1 => 08:05 ) => Array ( => 1
=> 08:10 ) => Array ( => 1 => 08:15 )
=> Array ( => 1 => 08:20 ) => Array...
|
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>
|
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( "name", "title",
"reports to user id", "start date in the format: mm/dd/yyyy" )
);
How can I display this hierarchy in simple nested <li> tags in the most
|
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 also removed)
So far I have (val is value, ar is array, returns new array):
| |
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 it is assigned a text
literal?? HOW can I change the array value to upper case then? What other
method exists for arrays?
Ex:
var GridArrayName1 = new Array();
GridArrayName1 = new Array ('test-value');
GridArrayName1 = GridArrayName1...
|
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 code...
TCHAR myArray;
DoStuff(myArray);
|
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 that array
Could you show me a little example how to do this?
Thanks.
|
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 up looking for characters that wrap
around the stripped characters and it ends up as a recursive
ordeal that fails to identify a poorly constructed $_GET
variable (when someone hand-types the item into the line and
makes a simple typing error).
|
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 to show the array data to the end user.
Can I do that?
How?
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |