text
stringlengths
4
1.08k
The truth value of an array with more than one element is ambigous when trying to index an array,"c[np.logical_or(a, b)]"
list of ints into a list of tuples python,"my_new_list = zip(my_list[0::2], my_list[1::2])"
Using chromedriver with selenium/python/ubuntu,driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver')
how to get tuples from lists using list comprehension in python,"[(x, lst2[i]) for i, x in enumerate(lst)]"
python: how to plot one line in different colors,plt.show()
How to construct a dictionary from two dictionaries in python?,"{'y1': 1, 'x2': 2, 'x1': 1, 'y2': 2}"
Subtitles within Matplotlib legend,plt.show()
is it possible to plot timelines with matplotlib?,ax.yaxis.set_visible(False)
Parse FB Graph API date string into python datetime,"time.strptime('2011-03-06T03:36:45+0000', '%Y-%m-%dT%H:%M:%S+0000')"
How can I define multidimensional arrays in python?,data[i][j][k]
Sorting by nested dictionary in Python dictionary,"a['searchResult'].sort(key=lambda d: d['ranking'], reverse=True)"
Regex for getting all digits in a string after a character,"re.findall('\\d+(?=[^[]+$)', s)"
Check if a Python list item contains a string inside another string,matching = [s for s in some_list if 'abc' in s]
Run a .bat program in the background on Windows,os.startfile('startsim.bat')
How to send HTTP/1.0 request via urllib2?,print(urllib.request.urlopen('http://localhost/').read())
How to print floating point numbers as it is without any truncation in python?,print('{:.100f}'.format(2.345e-67))
convert csv file to list of dictionaries,"[{'col3': 3, 'col2': 2, 'col1': 1}, {'col3': 6, 'col2': 5, 'col1': 4}]"
How to reverse a string using recursion?,return reverse(str1[1:] + str1[0])
Comparing values in two lists in Python,"z = [(i == j) for i, j in zip(x, y)]"
How do I transform a multi-level list into a list of strings in Python?,"a = [('A', 'V', 'C'), ('A', 'D', 'D')]"
Sending a mail from Flask-Mail (SMTPSenderRefused 530),app.config['MAIL_SERVER'] = 'smtp.gmail.com'
Python: Make last item of array become the first,a[-1:] + a[:-1]
How to share secondary y-axis between subplots in matplotlib,plt.show()
How do I combine two lists into a dictionary in Python?,"dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))"
Styling with classes in Pyside + Python,self.show()
Converting year and day of year into datetime index in pandas,"pd.to_datetime(df['year'] * 1000 + df['doy'], format='%Y%j')"
convert a string of bytes into an int (python),"int.from_bytes('y\xcc\xa6\xbb', byteorder='little')"
How to prevent automatic escaping of special characters in Python,winpath = 'C:\\Users\\Administrator\\bin'
Extract row with maximum value in a group pandas dataframe,"df.sort('count', ascending=False).groupby('Mt', as_index=False).first()"
How can I format a float using matplotlib's LaTeX formatter?,"ax.set_title('${0} \\times 10^{{{1}}}$'.format('3.5', '+20'))"
Python regular expressions - how to capture multiple groups from a wildcard expression?,"re.findall('\\w', 'abcdefg')"
Python: Built-in Keyboard Signal/Interrupts,time.sleep(1)
How can I execute shell command with a | pipe in it,"subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)"
Numpy: find index of elements in one array that occur in another array,"np.where(np.in1d(A, B))[0]"
Finding recurring patterns in a string,"re.findall('^(.+?)((.+)\\3+)$', '42344343434')[0][:-1]"
Is it possible to have multiple statements in a python lambda expression?,"map(lambda x: heapq.nsmallest(x, 2)[1], list_of_lists)"
How to lowercase a python dataframe string column if it has missing values?,df['x'].str.lower()
How do I configure the ip address with CherryPy?,cherrypy.server.socket_host = '0.0.0.0'
How to overplot a line on a scatter plot in python?,"plt.plot(x, y, '.')"
Getting the first item item in a many-to-many relation in Django,Group.objects.get(id=1).members.all()[0]
Nonlinear colormap with Matplotlib,plt.show()
How do I get current URL in Selenium Webdriver 2 Python?,driver.current_url
Python list comprehension for loops,[(x + y) for x in '12345' for y in 'abc']
Comparing rows of two pandas dataframes?,"AtB.loc[:2, :2]"
Accented characters in Matplotlib,"ax.set_yticklabels(['\xe9', '\xe3', '\xe2'])"
"How to set ticks on Fixed Position , matplotlib",plt.show()
python: how to convert currency to decimal?,cents_int = int(round(float(dollars.strip('$')) * 100))
How to import or include data structures (e.g. a dict) into a Python file from a separate file,eval(open('myDict').read())
Pandas convert a column of list to dummies,pd.get_dummies(s.apply(pd.Series).stack()).sum(level=0)
Context dependent split of a string in python,"re.split('(?<!\\d),(?! )|(?<=\\d),(?![\\d ])', s)"
Creating a matrix of options using itertools,"itertools.product([False, True], repeat=5)"
string to list conversion in python,"[x.strip() for x in s.split(',')]"
How to get rid of double backslash in python windows file path string?,"""""""C:\\Users\\user\\Desktop\\Filed_055123.pdf"""""""
How to add a new encoding to python 2.6?,'\x83'.encode('cp870')
Removing one list from another,[x for x in a if x not in b]
How can I add a default path to look for python script files in?,sys.path.append('C:\\Users\\Jimmy\\Documents\\Python')
"In Django, how do I check if a user is in a certain group?",return user.groups.filter(name='Member').exists()
How to change the layout of a Gtk application on fullscreen?,gtk.main()
Counting the number of non-NaN elements in a numpy ndarray matrix in Python,np.count_nonzero(~np.isnan(data))
Python: Sum string lengths,length = sum(len(s) for s in strings)
How to split string into words that do not contain whitespaces in python?,"""""""This is a string"""""".split()"
Calcuate mean for selected rows for selected columns in pandas data frame,"df.iloc[:, ([2, 5, 6, 7, 8])]"
Django return redirect() with parameters,"url('^link/(?P<backend>\\w+?)/$', my_function)"
Merging multiple dataframes on column,merged.reset_index()
Creating a PNG file in Python,"f.write(makeGrayPNG([[0, 255, 0], [255, 255, 255], [0, 255, 0]]))"
How to get a function name as a string in Python?,my_function.__name__
Sort NumPy float array column by column,"A = np.array(sorted(A, key=tuple))"
pandas: how do I select first row in each GROUP BY group?,df.drop_duplicates(subset='A')
How to slice and extend a 2D numpy array?,"array([[1, 2], [7, 8], [3, 4], [9, 10], [5, 6], [11, 12]])"
breaking a string in python depending on character pattern,"re.findall('\\d:::.+?(?=\\d:::|$)', a)"
How do I watch a file for changes using Python?,os.stat(filename).st_mtime
Named colors in matplotlib,plt.show()
Get load at a moment in time or getloadavg() for a smaller time period in Python in Linux (CentOS),print(int(open('/proc/loadavg').next().split()[3].split('/')[0]))
How do I convert LF to CRLF?,"f = open('words.txt', 'rU')"
How to convert a tuple to a string in Python?,emaillist = '\n'.join(item[0] for item in queryresult)
Apply a function to the 0-dimension of an ndarray,"[func(a, b) for a, b in zip(arrA, arrB)]"
Unable to parse TAB in JSON files,"json.loads('{""MY_STRING"": ""Foo\tBar""}')"
getting the opposite diagonal of a numpy array,np.diag(np.rot90(array))
Get value of an input box using Selenium (Python),input.get_attribute('value')
python - can lambda have more than one return,"lambda a, b: (a, b)"
How can I compare two lists in python and return matches,set(a).intersection(b)
Python Right Click Menu Using PyGTK,button = gtk.Button('A Button')
Python: most efficient way to convert date to datetime,"datetime.datetime.combine(my_date, datetime.time.min)"
matplotlib: add circle to plot,plt.show()
Create a List that contain each Line of a File,"my_list = [line.split(',') for line in open('filename.txt')]"
How to extend pyWavelets to work with N-dimensional data?,"pywt.dwtn([[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 9, 10]], 'db1')"
PHP to python pack('H'),binascii.unhexlify('44756d6d7920537472696e67')
Saving a Numpy array as an image,"scipy.misc.imsave('outfile.jpg', image_array)"
How to filter a numpy.ndarray by date?,"A[:, (0)] > datetime.datetime(2002, 3, 17, 0, 0, 0)"
How to extract numbers from filename in Python?,regex = re.compile('\\d+')
Python: split elements of a list,[i.partition('\t')[-1] for i in l if '\t' in i]
How to get a variable name as a string in Python?,"dict((name, eval(name)) for name in ['some', 'list', 'of', 'vars'])"
How can I convert a Python dictionary to a list of tuples?,"[(v, k) for k, v in list(d.items())]"
What is the easiest way to convert list with str into list with int?,[int(i) for i in str_list]
Python - sort a list of nested lists,"sorted(l, key=asum)"
Concurrency control in Django model,"super(MyModel, self).save(*args, **kwargs)"
Precision in python,print('{0:.2f}'.format(your_number))
python: append values to a set,"a.update([3, 4])"
NumPy - Efficient conversion from tuple to array?,"np.array(x).reshape(2, 2, 4)[:, :, (0)]"
Sorting a list of tuples by the addition of second and third element of the tuple,"sorted(a, key=lambda x: (sum(x[1:3]), x[0]), reverse=True)"