Questions tagged [python]

241852 questions
1

votes
5

answer
563

Views

Python: Efficient way to call inbuilt function multiple times?

I have a code that looks something like this: def somefunction(somelist): for item in somelist: if len(item) > 10: do something elif len(item) > 6: do something elif len(item) > 3: do something else: do something Since I am calling len(item) multiple times, is it inefficient to do it this way? Would...
user2236076
2

votes
1

answer
55

Views

How to install Django based Project?

i have Django based Blog Application. File structure image : https://www.dropbox.com/s/8vnqwheucjeyy43/Selection_012.png Here no manage.py file. How can i run it locally ? Thanks.
akdev2
2

votes
2

answer
6.9k

Views

Python read from file and remove non-ascii characters

I have the following program that reads a file word by word and writes the word again to another file but without the non-ascii characters from the first file. import unicodedata import codecs infile = codecs.open('d.txt','r',encoding='utf-8',errors='ignore') outfile = codecs.open('d_parsed.txt','w'...
user1894963
2

votes
2

answer
808

Views

plot a daily profile with python

I want to make a daily profile plot: hour vs concentrations. I'm using matplotlib and datetime module. When I write: import datetime from pylab import * b = [datetime.time(12,0), datetime.time(13,0)] c = [4,5] plot(b,c) show() ... it doesn't work. I have to use datetime objects instead of time objec...
carla
6

votes
2

answer
5k

Views

Hooking into sqlalchemy models

I'm looking to hook into the model creation cycle for sqlalchemy models. For example on create or on save (like in the Ruby ORM ActiveRecord, in fact I'm moving a model from ActiveRecord to SqlAlchemy). Events looks like what I need: http://docs.sqlalchemy.org/en/rel_0_7/core/event.html, but I haven...
blueblank
1

votes
1

answer
33

Views

Scanning for file paths with glob

I am searching for all .csv's located in a subfolder with glob like so: def scan_for_files(path): file_list = [] for path, dirs, files in os.walk(path): for d in dirs: for f in glob.iglob(os.path.join(path, d, '*.csv')): file_list.append(f) return file_list If I call: path = r'/data/realtimedata/tra...
swifty
3

votes
1

answer
22

Views

Can we do file handling from executable created by py2exe in Python?

I wrote below code f = open("tt.txt","w") print >> f, 123 val = input("Enter the number_") print val*val raw_input() f.close() And then created executable through py2exe. On clicking on executable a window pops which asks for a number give square of it, but doesn't create a file like program does o...
Vimal Raj Sharma
2

votes
5

answer
599

Views

Does python import all the listed libraries?

I'm just wondering, I often have really long python files and imports tend to stack quite quickly. PEP8 says that the imports should always be written at the beginning of the file. Do all the imported libraries get imported when calling a function coded in the file? Or do only the necessary librarie...
RadiantHex
2

votes
1

answer
76

Views

Pandas: Conditionally generate descriptions from column content

I am trying to iron out some issues with a function that uses pandas regex via str.extract to get each row in column "name" to generate column "description". I am using regex and not split since the code must be able to manage a variety of formattings. The function must be modified to acknowledge va...
Winterflags
2

votes
2

answer
186

Views

External process to handle couchdb notification causes crash

I am having trouble handling changes to my couchdb database through a python script. data = 'test' f = open('/home/username/test','w') f.write(data + '\n') f.close() this is the script I try to run (for test purpose). It's called "list.py" and it's located in "/usr/local/src/couchdb". I modify my "l...
Lorenzo Norcini
1

votes
2

answer
114

Views

Dictionary changing many values to many keys

I was just wondering if in the wonderful world of Python there is any way to go from something like this: dict1 = {'a': [1,2,3], 'b': [4,5,6]} to dict2 = {'a':1, 'a':2, 'a':3,'b':4, 'b': 5, 'b': 6] or equivalent, the order is irrelevant but I need some way of decomposing dict1 into something in whic...
George Burrows
2

votes
5

answer
974

Views

algorithm to find the correct set of numbers

i will take either python of c# solution i have about 200 numbers: 19.16 98.48 20.65 122.08 26.16 125.83 473.33 125.92 3,981.21 16.81 100.00 43.58 54.19 19.83 3,850.97 20.83 20.83 86.81 37.71 36.33 6,619.42 264.53 ... ... i know that in this set of numbers, there is a combinat...
4

votes
5

answer
256

Views

Given a “jumbled” list L, get a list where each element is the index of the corresponding element of L, if L was sorted

Desired Output I want a function to return a list such that, given a "jumbled" list l, each element is the index of the corresponding element of l, if l was sorted. (I'm failing to think of a less convoluted way of saying this, sorry.) Examples f([3,1,2]) = [2,0,1] f([3,1,2,2,3]) = [3,0,1,2,4], sin...
Matthew Adams
2

votes
4

answer
58

Views

How to filter a Pandas series while writing to list

For a given column 'A' in a pandas dataframe 'tbl', I have been trying to write the column .tolist() and filter out the items that are '.'. This works, but doesn't seem very readable: list_of_A = tbl['A'][~tbl['A'].isin(['.'])].tolist() Also, checking a list of one seems needlessly slow, though str....
dragon951
4

votes
2

answer
4.3k

Views

Pythonic way to concatenate regex objects

I have python regex objects - say, re_first and re_second - I would like to concatenate. import re FLAGS_TO_USE = re.VERBOSE | re.IGNORECASE re_first = re.compile( r"""abc #Some comments here """, FLAGS_TO_USE ) re_second = re.compile( r"""def #More comments here """, FLAGS_TO_USE ) I want one regex...
vathymut
1

votes
3

answer
131

Views

Why is it bad to use data types to initialize instances in Python?

Sorry if the answer to this is obvious, but I want to be sure, if you have(in Python): class Name(object): def __init__(self): self.int_att1 = 0 self.int_att2 = 0 self.list_att = [] why can't(I know you can, but I've never seen a programmer do this) you initialize it in this way: class Name(object):...
BLUC
3

votes
1

answer
679

Views

Debugging unittests

I have some problems with debugging code from unittest in Django. While I run unittest, I have output FAIL: test_basket (api.api_1_0.tests.basket_tests.BasketTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/dasm/apps/filmas...
Dariusz Smigiel
1

votes
2

answer
53

Views

Remove redundant strings based on partial strings

I have a set of queries, where some are merely portions of the eventual search string. I need to clean the partial strings from a very long collection of queries. Is a fast way to do this across potentially millions of sets like this? t = {u'house prices', u'how ', u'how man', u'how many animals go...
zbinsd
1

votes
3

answer
213

Views

How to add a variable to the module I import from?

What I want to do is something like this: template.py def dummy_func(): print(VAR) # more functions like this to follow fabfile.py # this gets called by fabric (fabfile.org) # safe to think of it as ant build.xml import template template.VAR = 'some_val' from template import * Namely I have a templa...
yanchenko
7

votes
7

answer
594

Views

Find consecutive repeated nan in a numpy array

What is the best way to find the maximum number of consecutive repeated nan in a numpy array? Examples: from numpy import nan Input 1: [nan, nan, nan, 0.16, 1, 0.16, 0.9999, 0.0001, 0.16, 0.101, nan, 0.16] Output 1: 3 Input 2: [nan, nan, 2, 1, 1, nan, nan, nan, nan, 0.101, nan, 0.16] Output 2: 4
volt
1

votes
1

answer
74

Views

Can I combine error exception and a conditional in a single line?

If for example, my code does something like this: try: for n in graph[x]: #... #... if event == 0: #do something except IndexError: #do the same thing My if block and my error exception block have the same exact code; so instead of having redundant lines, I want to combine the two blocks. I want to...
Eyeofpie
3

votes
5

answer
61

Views

how can I move a list index value forward 'x' amount of times using python?

I'm trying to unscramble a code using pythonic methods. The way to crack the code is by selecting the letter two places ahead of itself. For example if the code was abc Then the solution would be cde So I am trying to figure out how I add 2 to the index value of a letter (given it is in a list like...
oneman
2

votes
2

answer
2.2k

Views

supress scientific notation when writing python floats to files

Writing floats to a CSV writes some of them like this: 2.0628800997782577e-05 c = csv.writer(open(file, "wb")) c.writerow([var1, var2]) What I've tried: I have already tried var1**8 following other answers on StackOverflow, but this simply raises them to the power of 8. I have also tried Decim...
Zach
2

votes
1

answer
48

Views

Decorator/Wrapper enhancing method internally called

NOTE: I'm not asking about common python decorators, but about the decorator design pattern. I want to write a decorator that is able to modify a function called by the concrete component, the following code sample illustrates my problem: In [2]: class Animal: ...: def sound(self): ...:...
lgvaz
6

votes
2

answer
13.4k

Views

datetime objects format

I am trying to use datetime objects, including datetime.month, datetime.day, and datetime.hour. The problem is that these objects (say datetime.month) give values as 1, 2, 3, and so on to 12. Instead, I need these in the format 01,02,03 and so on to 12. There's a similar issue with days and months....
ehertele
3

votes
1

answer
77

Views

How to structure modules to avoid things like “import module.module.module”

I have been writing quite a bit of Python code lately, and I am struggling to figure out how to properly structure my module to allow simple importing. I have a module structured as follows: /module /submod_1 submod_1_class.py /submod_2 submod_2_class.py but I find it incredibly annoying to have to...
Jeff
1

votes
2

answer
35

Views

Can't iterate through words in a file and append string to each line

I am reading in a list of words from a file. I want to append a string to each word, then print out the word with the appended string. However, my current code appends the string on a new line. with open("wordDict.txt") as wordFile: for line in wordFile: line = line + 'a' print(line) An example out...
joefthdfthfth
3

votes
2

answer
129

Views

Find all subsets from list of sets that appears in at least N different sets

I'm working on algorithm of grouping keywords from search engine by amount of same urls they have in SERP. Each group represents an url, and each value is an id of keyword for SERP where url appeared. I have list of groups: groups = [ [1], [1, 2 ,3], [1, 2, 3, 4, 5], [1, 2, 3 ,4], [2, 3], [4, 5, 6]...
Alex T
4

votes
2

answer
78

Views

breaking a string in python depending on character pattern

I have a string something like this: a = '5:::{"test":[{"a":1,"b":2},{"a":2,"b":3}]}4:::{"something":[{"d":1,"e":2},{"d":2,"e":3}]}' I would like to split this into a list with the values being: ['5:::{"test":[{"a":1,"b":2},{"a":2,"b":3}]}','4:::{"something":[{"d":1,"e":2},{"d":2,"e":3}]}'] I tried...
user2348075
3

votes
2

answer
76

Views

Reversing a Number using Class in python

I am writing a program to reverse a Number using class object.I have created constructor which reads kwargs.The code does not throw an error but returns 60 instead of 42. class Nups: def __init__(self,**kwargs): self._vars = kwargs def rev(self,f): h=0 r=self._vars.get(f) print r while r!=0: h=h+(r...
3

votes
1

answer
97

Views

pandas groupby timeseries data according to function result

I am analyzing power systems time series data, and I am trying to find the contiguous data points that go beyond a certain threshold value. I am currently using excel formula row by row manually to do this, but I as I am trying to search more efficient methods I realized that this could be done in p...
Emman D.
10

votes
4

answer
1.6k

Views

Call super().__init__() in classes derived from `object`?

The Python documentation says that the __init__ method of each class is responsible for initializing its super class. But for new-style classes, the ultimate base class is object. Doing dir(object) shows that object itself has an __init__ method and could potentially be initialized. Is there any...
1

votes
3

answer
59

Views

How to merge elements in list, how to compare 2 elements in list

I am new to programming, having a question: I have two lists: list = ["ich", "du", "etc", "."] abbr = ["etc.", "U.S"] I need to identify abbreviations in the first list using the list of given abbreviations in the second. I need to go through elements of first list and if element of the list and ne...
Nastja Kryvoscheya
2

votes
1

answer
42

Views

Check several conditions for all values in a column

I have just started using python & pandas. I have searched google and stack overflow for an answer to my question but haven't been able to find one. This is what I need to do: I have a df with several data rows per person (id) and a variable called response_go, which can be coded 1 or 0 (type int64)...
Vanessa S.
2

votes
1

answer
156

Views

python: numpy runs script twice

when I import numpy to my python script, the script is executed twice. Can someone tell me how I can stop this, since everything in my script takes twice as long? Here's an example: #!/usr/bin/python2 from numpy import * print 'test_start' lines = open('test.file', 'r').readlines() what=int(lines[0...
drunk user
1

votes
1

answer
64

Views

forming pairs of non-contiguous elements from an array

There are multiple examples of generator expressions yielding pairs of contiguous elements from a list on this website. However, I'd like to do something a little different: given np.arange(6), I would like to output [[0, 3], [1, 4], [2, 5]] (here, in the form of a list, but both list and np.ndarray...
Raoul
8

votes
3

answer
140

Views

Apply function n items at a time along axis

I am looking for a way to apply a function n items at the time along an axis. E.g. array([[ 1, 2], [ 3, 4], [ 5, 6], [ 7, 8]]) If I apply sum across the rows 2 items at a time I get: array([[ 4, 6], [ 12, 14]]) Which is the sum of 1st 2 rows and the last 2 rows. NB: I am dealing with much...
1

votes
1

answer
29

Views

“Optimizing Queries” video (Udacity web dev course), caching db queries

Here is the video that I am confused about: https://www.youtube.com/watch?v=9UHKsiDznwg At about 6:12 you can see the code he uses to cache database queries. What I don't understand is why he uses a dictionary to cache the queries. The way he has it set up won't the dictionary only ever store one va...
RB34
1

votes
3

answer
37

Views

String as a keyword argument and combine multiple dict from str.partition() output to one single dict

I have a string as below: src = "raidlevel=1,slot=0,DISK=1i:1:1_1i:1:2" and I followed the code example from here to convert it to a dictionary based on a separator (=). for i in src.split(','): key, sep, val = i.partition('=') dictRaid = {key.lower():val} if all(k in dictRaid for k in ('raidlevel'...
Ibrahim Quraish
3

votes
1

answer
2.1k

Views

Anyone get python26 install in Snow Leopard via Macports?

I got build error after run in Snow Leopard (MacPort v.1.8.0) sudo port install python26 any workaround please? Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_lang_python26/work/Python-2.6...
Jirapong