text
stringlengths
4
1.08k
how to change the color of a single bar if condition is True matplotlib,plt.show()
Array initialization in Python,"[(x + i * y) for i in range(1, 10)]"
Python pandas dataframe: retrieve number of columns,len(df.columns)
How to use `numpy.savez` in a loop for save more than one array?,"np.savez(tmp, *getarray[:10])"
Python continuously parse console input,sys.stdin.read(1)
Splitting a string into words and punctuation,"re.findall(""[\\w']+|[.,!?;]"", ""Hello, I'm a string!"")"
Construct single numpy array from smaller arrays of different sizes,"np.hstack([np.arange(i, j) for i, j in zip(start, stop)])"
Flask broken pipe with requests,app.run(threaded=True)
how to get field type string from db model in django,model._meta.get_field('g').get_internal_type()
Reading in integer from stdin in Python,n = int(input())
Python3 bytes to hex string,a.decode('ascii')
Finding in elements in a tuple and filtering them,[x for x in l if x[0].startswith('img')]
simple/efficient way to expand a pandas dataframe,"y = pd.DataFrame(y, columns=list('y'))"
Edit XML file text based on path,tree.write('filename.xml')
changing the values of the diagonal of a matrix in numpy,A.ravel()[:A.shape[1] ** 2:A.shape[1] + 1]
How can I split and parse a string in Python?,print(mycollapsedstring.split(' '))
Similarity of lists in Python - comparing customers according to their features,"[[3, 1, 2], [1, 3, 1], [2, 1, 3]]"
Python Nested List Comprehension with two Lists,[(x + y) for x in l2 for y in l1]
Contour graph in python,plt.show()
How would I go about using concurrent.futures and queues for a real-time scenario?,time.sleep(spacing)
Color values in imshow for matplotlib?,plt.show()
How to remove \n from a list element?,[i.strip() for i in l]
fastest way to populate a 1D numpy array,"np.fromiter(a, dtype=np.float)"
How to convert the following string in python?,print('/'.join(new))
removing pairs of elements from numpy arrays that are NaN (or another value) in Python,~np.isnan(a).any(1)
Select rows from a DataFrame based on values in a column in pandas,df.query('foo == 222 | bar == 444')
Scrapy - Follow RSS links,xxs.select('//link/text()').extract()
Open document with default application in Python,os.system('start ' + filename)
Python remove anything that is not a letter or number,"re.sub('[\\W_]+', '', 'a_b A_Z \x80\xff \u0404', flags=re.UNICODE)"
Converting string to dict?,"ast.literal_eval(""{'x':1, 'y':2}"")"
Creating 2D dictionary in Python,d['set1']['name']
Get size of a file before downloading in Python,"open(filename, 'rb')"
Python Image Library produces a crappy quality jpeg when I resize a picture,"im.save(thumbnail_file, 'JPEG', quality=90)"
Connecting two points in a 3D scatter plot in Python and matplotlib,matplotlib.pyplot.show()
Most efficient way to build list of highest prices from queryset?,most_expensive = Car.objects.values('company_unique').annotate(Max('price'))
python: find only common key-value pairs of several dicts: dict intersection,dict(set.intersection(*(set(d.items()) for d in dicts)))
How to override default create method in django-rest-framework,"return super(MyModel, self).save(*args, **kwargs)"
Python: sorting items in a dictionary by a part of a key?,"lambda item: (item[0].rsplit(None, 1)[0], item[1])"
Multiplying a string by zero,s * (a + b) == s * a + s * b
Transposing part of a pandas dataframe,df = df[~((df['group_A'] == 0) | (df['group_B'] == 0))]
How to get nested-groups with regexp,"re.findall('\\[ (?:[^][]* \\[ [^][]* \\])* [^][]* \\]', s, re.X)"
How to pass members of a dict to a function,some_func(**mydict)
Sorting dictionary keys in python,"my_list = sorted(list(dict.items()), key=lambda x: x[1])"
From ND to 1D arrays,c = a.flatten()
How to get absolute url in Pylons?,"print(url('blog', id=123, qualified=True))"
Accessing model field attributes in Django,MyModel._meta.get_field('foo').verbose_name
Test if lists share any items in python,any(i in a for i in b)
Confused about running Scrapy from within a Python script,log.start()
Python how to reduce on a list of tuple?,"sum(x * y for x, y in zip(a, b))"
Ignore an element while building list in python,[r for r in (f(char) for char in string) if r is not None]
How to set environment variables in Python,os.environ['DEBUSSY'] = str(myintvariable)
Reference to Part of List - Python,"[0, 1, 0, 1, 2, 5, 6, 7, 8, 9]"
How to generate random number of given decimal point between 2 number in Python?,"round(random.uniform(min_time, max_time), 1)"
How to escape single quote in xpath 1.0 in selenium for python,"driver.find_element_by_xpath('//span[text()=""' + cat2 + '""]').click()"
How to access a dictionary key value present inside a list?,print(L[1]['d'])
Python: Pandas Dataframe how to multiply entire column with a scalar,"df.loc[:, ('quantity')] *= -1"
changing the values of the diagonal of a matrix in numpy,"A.ravel()[i:max(0, A.shape[1] - i) * A.shape[1]:A.shape[1] + 1]"
Implementing breadcrumbs in Python using Flask?,app.run()
"How to do an inverse `range`, i.e. create a compact range based on a set of numbers?","['1-5', '7', '9-10']"
How do you get a decimal in python?,print('the number is {:.2}'.format(1.0 / 3.0))
How to join list of strings?,""""""" """""".join(L)"
Possible to generate Data with While in List Comprehension,print([i for i in range(5)])
RFC 1123 Date Representation in Python?,"datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')"
Python/matplotlib mplot3d- how do I set a maximum value for the z-axis?,plt.show()
Python: How do I randomly select a value from a dictionary key?,"['Protein', 'Green', 'Squishy']"
Selecting a column on a multi-index pandas DataFrame,df
How do I plot a step function with Matplotlib in Python?,plt.show()
"Python ""in"" Comparison of Strings of Different Word Length",all(x in 'John Michael Marvulli'.split() for x in 'John Marvulli'.split())
Where does Python root logger store a log?,logging.basicConfig(level=logging.WARNING)
Django: variable parameters in URLconf,"url('^(?P<category>\\w)/(?P<filters>.*)/$', 'myview'),"
How to insert the contents of one list into another,"array = ['the', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']"
python: plotting a histogram with a function line on top,plt.show()
Builder pattern equivalent in Python,return ''.join('Hello({})'.format(i) for i in range(100))
"Remove all articles, connector words, etc., from a string in Python","re.sub('\\s+(a|an|and|the)(\\s+)', '\x02', text)"
Impossible lookbehind with a backreference,"print(re.sub('(.+)(?<=\\1)', '(\\g<0>)', test))"
Impossible lookbehind with a backreference,"print(re.sub('(.)(?<=\\1)', '(\\g<0>)', test))"
Equivalent of objects.latest() in App Engine,MyObject.all().order('-time').fetch(limit=1)[0]
How to check if a value is in the list in selection from pandas data frame?,"df_new[df_new['l_ext'].isin([31, 22, 30, 25, 64])]"
Plotting stochastic processes in Python,plt.show()
Create List of Single Item Repeated n Times in Python,"itertools.repeat(0, 10)"
How To Plot Multiple Histograms On Same Plot With Seaborn,"ax.set_xlim([0, 100])"
Divide the values of two dictionaries in python,{k: (float(d2[k]) / d1[k]) for k in d1.keys() & d2}
Python: list() as default value for dictionary,dct[key].append(some_value)
Correctly reading text from Windows-1252(cp1252) file in python,print('J\xe2nis'.encode('utf-8'))
How do I return a JSON array with Bottle?,"{'data': [{'id': 1, 'name': 'Test Item 1'}, {'id': 2, 'name': 'Test Item 2'}]}"
Check to see if a collection of properties exist inside a dict object in Python,all(dict_obj.get(key) is not None for key in properties_to_check_for)
Pandas dropna - store dropped rows,"df.dropna(subset=['col2', 'col3'])"
Convert Average of Python List Values to Another List,"[([k] + [(sum(x) / float(len(x))) for x in zip(*v)]) for k, v in list(d.items())]"
How can I do a line break (line continuation) in Python?,a = '1' + '2' + '3' + '4' + '5'
Convert string to ASCII value python,[ord(c) for c in s]
Python: Is there a way to split a string of numbers into every 3rd number?,"[int(a[i:i + 3]) for i in range(0, len(a), 3)]"
How to create new folder?,os.makedirs(newpath)
Sort Python list of objects by date,results.sort(key=lambda r: r.person.birthdate)
How do I send a POST request as a JSON?,"response = urllib.request.urlopen(req, json.dumps(data))"
How to get the screen size in Tkinter?,screen_height = root.winfo_screenheight()
Django: Lookup by length of text field,"ModelWithTextField.objects.filter(text_field__iregex='^.{7,}$')"
Why is it a syntax error to invoke a method on a numeric literal in Python?,(5).bit_length()
Is there a fast Way to return Sin and Cos of the same value in Python?,"a, b = np.sin(x), np.cos(x)"
Checking number of elements in Python's `Counter`,sum(counter.values())
Fast way to convert strings into lists of ints in a Pandas column?,"[3, 2, 1, 0, 3, 2, 3]"