text
stringlengths
4
1.08k
How to add an image in Tkinter (Python 2.7),root.mainloop()
pandas dataframe group year index by decade,df.groupby(df.index.year // 10 * 10).sum()
How to initialize a two-dimensional array in Python?,x = [[foo for i in range(10)] for j in range(10)]
Google App Engine json post request body,self.response.out.write(self.request.body)
Python/Matplotlib - Is there a way to make a discontinuous axis?,"plt.figure(figsize=(10, 8))"
Adding calculated column(s) to a dataframe in pandas,d['A'][1:] < d['C'][:-1]
Find phone numbers in python script,reg = re.compile('\\d{3}\\d{3}\\d{4}')
Concatenate elements of a tuple in a list in python,new_list = [' '.join(words) for words in words_list]
How do you create a legend for a contour plot in matplotlib?,plt.legend(loc='upper left')
Controlling alpha value on 3D scatter plot using Python and matplotlib,plt.show()
Python config parser to get all the values from a section?,dict(Config.items('Section'))
Convert bytes to a Python string,"""""""hello"""""".decode(encoding)"
Django: Query self referencing objects with no child elements,Category.objects.filter(category__isnull=True)
How to change the 3d axis settings in matplotlib,ax.w_yaxis.set_ticklabels([])
Importing from a relative path in Python,"sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))"
Writing a pandas DataFrame into a csv file with some empty rows,"df.to_csv('pandas_test.txt', header=False, index=False, na_rep=' ')"
Python find list lengths in a sublist,[len(x) for x in a[0]]
Does Python have a built in function for string natural sort?,"['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']"
Add colorbar to existing axis,plt.show()
How to set default value to all keys of a dict object in python?,d['foo']
Windows path in python,"os.path.join(mydir, myfile)"
Python: Find in list,"[1, 2, 3, 2].index(2)"
selecting from multi-index pandas,df.iloc[df.index.get_level_values('A') == 1]
Python regex: XOR operator,pattern = '(DT\\s+)+((RB\\s+)+|(JJ\\s+)+)(NN\\s*)*NN$'
Python: Display special characters when using print statement,"print(repr(a).replace(' ', '\\s'))"
"How to set ticks on Fixed Position , matplotlib",plt.show()
Batch Renaming of Files in a Directory,"rename('c:\\temp\\xx', '*.doc', 'new(%s)')"
Center origin in matplotlib,plt.show()
"How do I sort a list with ""Nones last""","[(False, 0), (False, 1), (False, 2), (False, 3), (False, 4), (True, None)]"
How to generate a module object from a code object in Python,sys.modules['m']
How to remove square brackets from list in Python?,"print(', '.join(map(str, LIST)))"
Is there a way to use PhantomJS in Python?,driver.quit()
How to implement Pandas GroupBy filter on mixed type data?,df = df[df['Found'] == 'No Match']
How to convert string to byte arrays?,"map(ord, 'Hello, \u9a6c\u514b')"
Access item in a list of lists,list1[0][2]
PLS-DA algorithm in python,"dummy = np.array([[1, 1, 0, 0], [0, 0, 1, 1]]).T"
pymongo: how to use $or operator to an column that is an array?,print(type(collection1.find_one()['albums'][0]))
Concise way to remove elements from list by index in Python,"[v for i, v in enumerate(myList) if i not in toRemove]"
count occurrences of number by column in pandas data frame,(df == 1).sum()
Python - how to run multiple coroutines concurrently using asyncio?,asyncio.get_event_loop().run_forever()
How to convert a list of multiple integers into a single integer?,"x = [1, 3, 5]"
Pyhon - Best way to find the 1d center of mass in a binary numpy array,np.flatnonzero(x[:-1] != x[1:]).mean() + 0.5
Python: most efficient way to convert date to datetime,"datetime(date.year, date.month, date.day)"
Plotting a polynomial in Python,plt.show()
"In Python, how to check if a string only contains certain characters?",bool(re.compile('^[a-z0-9\\.]+\\Z').match('1234\n'))
How to byte-swap a 32-bit integer in python?,"return struct.unpack('<I', struct.pack('>I', i))[0]"
Is there a Python function to determine which quarter of the year a date is in?,df['quarter'] = df['date'].dt.quarter
How to get a random (bootstrap) sample from pandas multiindex,"df.unstack().sample(3, replace=True).stack()"
Selecting a subset of functions from a list of functions in python,"return map(lambda f: f(*args), funcs)"
What is the difference between a string and a byte string?,"""""""τoρνoς"""""".decode('utf-8')"
Create 3D array using Python,"numpy.zeros((i, j, k))"
Python list of tuples to list of int,y = [i[0] for i in x]
Convert string to binary in python,"print(' '.join(format(ord(x), 'b') for x in a))"
Removing non-breaking spaces from strings using Python,"myString = myString.replace('\xc2\xa0', ' ')"
matplotlib: how to change data points color based on some variable,plt.show()
Add multiple columns to a Pandas dataframe quickly,"df.ix[:5, :10]"
how to safely remove elements from a list in Python,[x for x in a if x <= 1 or x >= 4]
"Python/Scipy: Find ""bounded"" min/max of a matrix","b = np.sort(a[..., :-1], axis=-1)"
How to get environment from a subprocess in Python,proc.communicate()
Titlecasing a string with exceptions,"""""""There is a way"""""".title()"
Can I restore a function whose closure contains cycles in Python?,"f(*args, **kwargs)"
How to fold/accumulate a numpy matrix product (dot)?,"from functools import reduce
reduce(np.dot, [S0, Sx, Sy, Sz])"
How to split string with limit by the end in Python,"""""""hello.world.foo.bar"""""".rsplit('.', 1)"
Remove empty string from list,mylist = [i for i in mylist if i != '']
Python: Intertwining two lists,"c = [item for pair in zip(a, b) for item in pair]"
How to remove lines in a Matplotlib plot,ax.lines.pop(0)
ipdb with python unittest module,"self.assertEqual('foo', 'bar')"
Best way to strip punctuation from a string in Python,"s = re.sub('[^\\w\\s]', '', s)"
Fill username and password using selenium in python,driver.find_element_by_name('submit').click()
remove special characters from string,"unicodedata.normalize('NFKD', source).encode('ascii', 'ignore')"
Getting inverse (1/x) elements of a numpy array,"array = np.array([1, 2, 3, 4])"
How to start a background process in Python?,os.system('some_command &')
Most efficient way to remove multiple substrings from string?,"re.sub('|'.join(map(re.escape, replace_list)), '', words)"
Displaying multiple masks in different colours in pylab,"plt.imshow(mmm * data, cmap='rainbow')"
Ordering Django queryset by an @property,"sorted(Thing.objects.all(), key=lambda t: t.name)"
How can I make a for-loop pyramid more concise in Python?,"product(list(range(3)), list(range(4)), ['a', 'b', 'c'], some_other_iterable)"
Fabric - sudo -u,"sudo('python manage.py collectstatic --noinput', user='www-data')"
paramiko combine stdout and stderr,ssh.close()
Multicast in Python,"sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)"
How to bind self events in Tkinter Text widget after it will binded by Text widget?,root.mainloop()
How to use regex with multiple data formats,"""""""\\bCVE-\\d+(?:-\\d+)?"""""""
How to know/change current directory in Python shell?,os.system('cd c:\\mydir')
Python - How can I do a string find on a Unicode character that is a variable?,"ast.literal_eval(""u'"" + zzz + ""'"")"
Intersection of two numpy arrays of different dimensions by column,"a[:, (0)][mask]"
Intersection of 2d and 1d Numpy array,"A[:, 3:].flat[np.in1d(A[:, 3:], B)] = 0"
How to plot a gradient color line in matplotlib?,"plt.plot(x[i:i + 2], y[i:i + 2])"
How to insert string to each token of a list of strings?,l = [i.split() for i in l]
Reading 3 bytes as an integer,"print(struct.unpack('>I', '\x00' + s)[0])"
How to add timeout to twisted defer,reactor.run()
How to remove the space between subplots in matplotlib.pyplot?,ax.set_yticklabels([])
how do I include a boolean AND within a regex?,"""""""(?=[MBDPI]{3})\\w*I\\w*"""""""
How can I filter a Haystack SearchQuerySet for None on an IntegerField,self.searchqueryset.filter(group__isnull=True)
How to delete an item in a list if it exists?,some_list.remove(thing)
How to print a numpy array without brackets,"print(re.sub('[\\[\\]]', '', np.array_str(a)))"
How does one convert a .NET tick to a python datetime?,"datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds=ticks / 10)"
Python: remove odd number from a list,return [x for x in l if x % 2 == 0]
python logging string formatting,logger.setLevel(logging.DEBUG)
Cross product of a vector in NumPy,"np.cross(a, b, axis=0)"
How to merge two Python dictionaries in a single expression?,c = dict(list(a.items()) | list(b.items()))