text
stringlengths 4
1.08k
|
|---|
Is it possible to kill a process on Windows from within Python?,os.system('taskkill /im make.exe')
|
How to remove parentheses only around single words in a string,"re.sub('\\((\\w+)\\)', '\\1', s)"
|
Check if a list has one or more strings that match a regex,"[re.search('\\d{4}', s) for s in lst]"
|
Finding the index of elements based on a condition using python list comprehension,[i for i in range(len(a)) if a[i] > 2]
|
How does python know to add a space between a string literal and a variable?,print(str(a) + ' plus ' + str(b) + ' equals ' + str(a + b))
|
How to count all elements in a nested dictionary?,sum(len(x) for x in list(food_colors.values()))
|
How do I model a many-to-many relationship over 3 tables in SQLAlchemy (ORM)?,session.query(Shots).filter_by(event_id=event_id)
|
How to remove specific elements in a numpy array,"numpy.delete(a, index)"
|
How can I remove the fragment identifier from a URL?,urlparse.urldefrag('http://www.address.com/something#something')
|
Is there a way of drawing a caption box in matplotlib,plt.show()
|
Is there a way to plot a Line2D in points coordinates in Matplotlib in Python?,plt.show()
|
deleting rows in numpy array,"x = numpy.delete(x, 2, axis=1)"
|
How to convert string to byte arrays?,""""""""""""".join([('/x%02x' % ord(c)) for c in 'hello'])"
|
How do you extract a column from a multi-dimensional array?,[row[1] for row in A]
|
Sorting a list of tuples by the addition of second and third element of the tuple,"sorted(lst, key=lambda x: (-sum(x[1:]), x[0]))"
|
How to get the url address from upper function in Scrapy?,"yield Request(url=url, callback=self.parse, meta={'page': 1})"
|
Python split string on regex,"p = re.compile('((?:Friday|Saturday)\\s*\\d{1,2})')"
|
Python: Split NumPy array based on values in the array,"np.where(np.diff(arr[:, (1)]))[0] + 1"
|
"Reading Freebase data dump in python, read to few lines?","open('file', 'rb')"
|
Print multiple arguments in python,"print('Total score for {} is {}'.format(name, score))"
|
Background color for Tk in Python,root.configure(background='black')
|
is it possible to plot timelines with matplotlib?,ax.spines['right'].set_visible(False)
|
Filtering out certain bytes in python,"re.sub('[^ -\ud7ff\t\n\r\ue000-\ufffd\u10000-\u10ffFF]+', '', text)"
|
How to get transparent background in window with PyGTK and PyCairo?,win.show()
|
Split a list into nested lists on a value,"[[1, 4], [6], [3], [4]]"
|
Create a list of tuples with adjacent list elements if a condition is true,"[(x, y) for x, y in zip(myList, myList[1:]) if y == 9]"
|
Easier way to add multiple list items?,sum(sum(x) for x in lists)
|
How to use a dot in Python format strings?,"""""""Hello {user[name]}"""""".format(**{'user': {'name': 'Markus'}})"
|
Regex to remove repeated character pattern in a string,"re.sub('^(.+?)\\1+$', '\\1', input_string)"
|
"List of Tuples (string, float)with NaN How to get the min value?","min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1])"
|
Sorting a list of dicts by dict values,"sorted(a, key=dict.values, reverse=True)"
|
Extract row with maximum value in a group pandas dataframe,df.groupby('Mt').first()
|
Extract data from HTML table using Python,"print(r.sub('\\1_STATUS = ""\\2""\\n\\1_TIME = \\3', content))"
|
How do I do a not equal in Django queryset filtering?,Entry.objects.filter(~Q(id=3))
|
Use groupby in Pandas to count things in one column in comparison to another,df.groupby('Event').Status.value_counts().unstack().fillna(0)
|
Using Django ORM get_or_create with multiple databases,MyModel.objects.using('my_non_default_database').get_or_create(name='Bob')
|
Displaying multiple masks in different colours in pylab,plt.show()
|
Adding calculated column(s) to a dataframe in pandas,df['t-1'] = df['t'].shift(1)
|
How to remove leading and trailing zeros in a string? Python,your_string.strip('0')
|
python: how to convert a string to utf-8,"stringnamehere.decode('utf-8', 'ignore')"
|
Select dataframe rows between two dates,df['date'] = pd.to_datetime(df['date'])
|
A list as a key for PySpark's reduceByKey,"rdd.map(lambda k_v: (set(k_v[0]), k_v[1])).groupByKey().collect()"
|
Easy way to convert a unicode list to a list containing python strings?,[x.encode('UTF8') for x in EmployeeList]
|
How to loop backwards in python?,"list(range(10, 0, -1))"
|
python: check if an numpy array contains any element of another array,"np.any(np.in1d(a1, a2))"
|
how do I insert a column at a specific column index in pandas?,df.reindex(columns=['n'] + df.columns[:-1].tolist())
|
apply a function to a pandas Dataframe whose returned value is based on other rows,"df.groupby(['item', 'price']).region.apply(f)"
|
How to apply a function to a series with mixed numbers and integers,"pd.to_numeric(a, errors='coerce').fillna(-1)"
|
How can I use python itertools.groupby() to group a list of strings by their first character?,"groupby(tags, key=operator.itemgetter(0))"
|
How to sort with lambda in Python,"a = sorted(a, key=lambda x: x.modified, reverse=True)"
|
How can I create a standard colorbar for a series of plots in python,plt.show()
|
Removing items from unnamed lists in Python,[item for item in my_sequence if item != 'item']
|
Pandas: how to change all the values of a column?,df['Date'].str.extract('(?P<year>\\d{4})').astype(int)
|
Get IP address in Google App Engine + Python,os.environ['REMOTE_ADDR']
|
How to replace string values in pandas dataframe to integers?,stores['region'] = stores['region'].astype('category')
|
Delete every non utf-8 symbols froms string,"line = line.decode('utf-8', 'ignore').encode('utf-8')"
|
How to get two random records with Django,MyModel.objects.order_by('?')[:2]
|
How to make a FigureCanvas fit a Panel?,"self.axes = self.figure.add_axes([0, 0, 1, 1])"
|
Horizontal stacked bar chart in Matplotlib,"df2.plot(kind='bar', stacked=True)"
|
subprocess.Popen with a unicode path,"subprocess.Popen('Pok\xc3\xa9mon.mp3', shell=True)"
|
Get unique values from a list in python,"set(['a', 'b', 'c', 'd'])"
|
How do I calculate the md5 checksum of a file in Python?,"hashlib.md5(open('filename.exe', 'rb').read()).hexdigest()"
|
Pipe subprocess standard output to a variable,"subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)"
|
How to convert a list of multiple integers into a single integer?,"sum(d * 10 ** i for i, d in enumerate(x[::-1]))"
|
Python: How to read csv file with different separators?,"data = [line[i:i + 12] for i in range(0, len(line), 12)]"
|
Saving a numpy array with mixed data,"numpy.savetxt('output.dat', my_array.reshape((4, 2)), fmt='%f %i')"
|
Problem with inserting into MySQL database from Python,conn.commit()
|
pandas: how to run a pivot with a multi-index?,"df.pivot_table(values='value', index=['year', 'month'], columns='item')"
|
Setting matplotlib colorbar range,"quadmesh.set_clim(vmin=0, vmax=15)"
|
Extracting date from a string in Python,"dparser.parse('monkey 10/01/1980 love banana', fuzzy=True)"
|
Post JSON using Python Requests,"requests.post('http://httpbin.org/post', json={'test': 'cheers'})"
|
python backreference regex,"""""""package ([^\\s]+)\\s+is([\\s\\S]*)end\\s+(package|\\1)\\s*;"""""""
|
Implicit conversions in Python,A(1) + A(2)
|
pandas: how to run a pivot with a multi-index?,"df.groupby(['year', 'month', 'item'])['value'].sum().unstack('item')"
|
Python sorting - A list of objects,somelist.sort(key=lambda x: x.resultType)
|
Comparing two lists in Python,"['a', 'c']"
|
How to assign a string value to an array in numpy?,"CoverageACol = numpy.array([['a', 'b'], ['c', 'd']], dtype=numpy.dtype('a16'))"
|
Plotting categorical data with pandas and matplotlib,df.colour.value_counts().plot(kind='bar')
|
How do I sort a list of strings in Python?,mylist.sort()
|
How can I create an array/list of dictionaries in python?,dictlist = [dict() for x in range(n)]
|
UnicodeEncodeError when writing to a file,write(s.encode('latin-1'))
|
Concatenating two one-dimensional NumPy arrays,"numpy.concatenate([a, b])"
|
How to disable the minor ticks of log-plot in Matplotlib?,"plt.xscale('log', subsx=[2, 3, 4, 5, 6, 7, 8, 9])"
|
"How can I ""divide"" words with regular expressions?","print(re.match('[^/]+', text).group(0))"
|
How can I splice a string?,t = s[:1] + 'whatever' + s[6:]
|
what would be the python code to add time to a specific timestamp?,datetime.datetime.now() + datetime.timedelta(seconds=10)
|
"Pythonic way to fetch all elements in a dictionary, falling between two keys?","dict((k, v) for k, v in parent_dict.items() if k > 2 and k < 4)"
|
Python Requests Multipart HTTP POST,"requests.post(url, headers=headers, data=data, files=files)"
|
selecting across multiple columns with python pandas?,df[(df['A'] > 1) | (df['B'] < -1)]
|
How do I extract the names from a simple function?,"['foo.bar', 'foo.baz']"
|
Creating 2D dictionary in Python,dict_names['d1']['name']
|
python string splitting,"re.split('(\\d+)', 'a1b2c30d40')"
|
Numpy: Sorting a multidimensional array by a multidimensional array,"a[[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]]"
|
2d array of lists in python,"matrix = [[['s1', 's2'], ['s3']], [['s4'], ['s5']]]"
|
BeautifulSoup - easy way to to obtain HTML-free contents,return ''.join(soup.findAll(text=True))
|
Complex Sorting of a List,"sorted(['1:14', '8:01', '12:46', '6:25'], key=daytime)"
|
openCV video saving in python,cv2.destroyAllWindows()
|
Formatting text to be justified in Python 3.3 with .format() method,"""""""${:.2f}"""""".format(amount)"
|
Zip and apply a list of functions over a list of values in Python,"[x(y) for x, y in zip(functions, values)]"
|
Python: Uniqueness for list of lists,unique_data = [list(x) for x in set(tuple(x) for x in testdata)]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.