text
stringlengths
4
1.08k
How to obtain all unique combinations of values of particular columns,"df.drop_duplicates(subset=['Col2', 'Col3'])"
Python: sort an array of dictionaries with custom comparator?,key = lambda d: d['rank'] if d['rank'] != 0 else float('inf')
How to make good reproducible pandas examples,"df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])"
Trying to count words in a string,print({word: word_list.count(word) for word in word_list})
Crop image with corrected distortion in OpenCV (Python),"cv2.imshow('Crop', desired_result)"
Python saving multiple figures into one PDF file,pdf.close()
Best way to delete a django model instance after a certain date,print(Event.objects.filter(date__lt=datetime.datetime.now()).delete())
Selecting unique observations in a pandas data frame,"df.drop_duplicates(cols='uniqueid', inplace=True)"
Deleting key/value from list of dictionaries using lambda and map,"map(lambda d: d.pop('k1'), list_of_d)"
Navigation with BeautifulSoup,soup.select('div.container a[href]')
How do I find information about a function in python?,help(function)
Interleave list with fixed element,"[elem for x in list for elem in (x, 0)][:-1]"
Loop for each item in a list,list(itertools.product(*list(mydict.values())))
How do I convert an integer to a list of bits in Python,[int(n) for n in bin(21)[2:].zfill(8)]
Is there a matplotlib flowable for ReportLab?,matplotlib.use('PDF')
Redirect to a URL which contains a 'variable part' in Flask (Python),"return redirect(url_for('dashboard', username='foo'))"
Passing a function with two arguments to filter() in python,"list(filter(functools.partial(get_long, treshold=13), DNA_list))"
Python: Find difference between two dictionaries containing lists,"{key: list(set(a[key]).difference(b.get(key, []))) for key in a}"
Pythonic way to print a multidimensional complex numpy array to a string,""""""" """""".join([str(x) for x in np.hstack((a.T.real, a.T.imag)).flat])"
how to calculate percentage in python,print('The total is ' + str(total) + ' and the average is ' + str(average))
Fastest way of deleting certain keys from dict in Python,"dict((k, v) for k, v in somedict.items() if not k.startswith('someprefix'))"
How to download to a specific directory with Python?,"urllib.request.urlretrieve('http://python.org/images/python-logo.gif', '/tmp/foo.gif')"
Python Count the number of substring in list from other string list without duplicates,"['Smith', 'Smith', 'Roger', 'Roger-Smith']"
Python - How can I do a string find on a Unicode character that is a variable?,s.decode('utf-8').find('\u0101')
How can I dynamically get the set of classes from the current python module?,"getattr(sys.modules[__name__], 'A')"
store return value of a Python script in a bash script,sys.exit(1)
In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame?,pd.to_datetime(pd.Series(date_stngs))
Find all list permutations of a string in Python,"['m', 'o', 'n', 'k', 'e', 'y']"
Filling array with zeros in numpy,"np.zeros((4, 3, 2))"
"UTF-8 In Python logging, how?",logging._defaultFormatter = logging.Formatter('%(message)s')
printing list in python properly,"print('[%s]' % ', '.join(map(str, mylist)))"
How to get the n next values of a generator in a list (python),list(next(it) for _ in range(n))
Python: plot data from a txt file,plt.show()
Best way to print list output in python,"print('{0}\n{1}'.format(item[0], '---'.join(item[1])))"
Generate a n-dimensional array of coordinates in numpy,"ndim_grid([2, -2, 4], [5, 3, 6])"
Plotting animated quivers in Python,plt.show()
Python list comprehension for loops,"[(x + y) for x, y in zip('ab', '12345')]"
Splitting a list into uneven groups?,"[[1, 2], [3, 4, 5, 6]]"
append tuples to a list,result.extend(item)
How to select a Radio Button?,"br.form.set_value(['1'], name='prodclass')"
Coordinates of item on numpy array,ii = np.where(a == 4)
How to determine a numpy-array reshape strategy,"np.einsum('ijk,kj->i', A, B)"
How to convert a Numpy 2D array with object dtype to a regular 2D array of floats,"np.array(arr[:, (1)], dtype=[('', np.float)] * 3).view(np.float).reshape(-1, 3)"
Converting datetime.date to UTC timestamp in Python,"timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)"
How to search help using python console,help('modules')
Convert a Pandas DataFrame to a dictionary,"{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}"
Plot smooth line with PyPlot,plt.show()
Append 2 dimensional arrays to one single array,"array([[[1, 5], [2, 6]], [[3, 7], [4, 8]]])"
Element-wise minimum of multiple vectors in numpy,"np.minimum.reduce([np.arange(3), np.arange(2, -1, -1), np.ones((3,))])"
Sorting by nested dictionary in Python dictionary,"srt_dict['searchResult'].sort(key=lambda d: d['ranking'], reverse=True)"
Initializing 2D array in Python,arr = [[None for x in range(6)] for y in range(6)]
'module' object has no attribute 'now' will trying to create a CSV,datetime.datetime.now()
Is there a Numpy function to return the first index of something in an array?,array[itemindex[0][1]][itemindex[1][1]]
making errorbars not clipped in matplotlib with Python,plt.show()
"In Django, how does one filter a QuerySet with dynamic field lookups?",Person.objects.filter(**kwargs)
What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python,"ascii_garbage = text.encode('ascii', 'replace')"
Reading data blocks from a file in Python,line = f.readline()
Wildcard matching a string in Python regex search,pattern = '6 of\\s+(.+?)\\s+fans'
Wildcard matching a string in Python regex search,pattern = '6 of\\s+(\\S+)\\s+fans'
Wildcard matching a string in Python regex search,pattern = '6 of\\D*?(\\d+)\\D*?fans'
Complex Sorting of a List,"['8:00', '12:30', '1:45', '6:15']"
How to Check if String Has the same characters in Python,len(set('aaaa')) == 1
Writing a binary buffer to a file in python,myfile.write(c_uncompData_p[:c_uncompSize])
How to filter rows of Pandas dataframe by checking whether sub-level index value within a list?,df[df.index.map(lambda x: x[0] in stk_list)]
UTF-8 compatible compression in python,json.dumps({'compressedData': base64.b64encode(zString)})
Setting Transparency Based on Pixel Values in Matplotlib,plt.show()
get array values in python,"[(1, 3), (3, 4), (4, None)]"
Python(pandas): removing duplicates based on two columns keeping row with max value in another column,"df.groupby(['A', 'B']).max()['C'].reset_index()"
permutations with unique values,"[(2, 1, 1), (1, 2, 1), (1, 1, 2)]"
How do I create a CSV file from database in Python?,"writer.writerow(['mary', '3 main st', '704', 'yada'])"
Replace value in any column in pandas dataframe,"pd.to_numeric(df.stack(), 'coerce').unstack()"
"TypeError: list indices must be integers, not str,while parsing json",l['type'][0]['references']
How to return a static HTML file as a response in Django?,"url('^path/to/url', TemplateView.as_view(template_name='index.html')),"
"In python, how does one test if a string-like object is mutable?","isinstance(s, str)"
How to query an HDF store using Pandas/Python,"pd.read_hdf('test.h5', 'df', where=[pd.Term('A', '=', ['foo', 'bar']), 'B=1'])"
Checking a List for a Sequence,set(L[:4])
Is there a way to leave an argument out of the help using python argparse,"parser.add_argument('--secret', help=argparse.SUPPRESS)"
How to plot a rectangle on a datetime axis using matplotlib?,plt.show()
Impregnate string with list entries - alternating,""""""""""""".join(chain.from_iterable(zip_longest(a, b, fillvalue='')))"
How do I generate permutations of length LEN given a list of N Items?,"itertools.permutations(my_list, 3)"
Python sum of ASCII values of all characters in a string,sum(bytearray('abcdefgh'))
How to write a memory efficient Python program?,f.close()
How to get indices of N maximum values in a numpy array?,ind[np.argsort(a[ind])]
Is there a direct approach to format numbers in jinja2?,{{'%d' | format(42)}}
How to compare value of 2 fields in Django QuerySet?,players = Player.objects.filter(batting__gt=F('bowling'))
Replace a substring selectively inside a string,"re.sub('\\bdelhi\\b(?=(?:""[^""]*""|[^""])*$)', '', a).strip()"
How to mute all sounds in chrome webdriver with selenium,driver.get('https://www.youtube.com/watch?v=hdw1uKiTI5c')
How do I convert a file's format from Unicode to ASCII using Python?,"unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')"
Convert hex to binary,"bin(int('abc123efff', 16))[2:]"
Convert alphabet letters to number in Python,chr(ord('x')) == 'x'
Concatenate rows of pandas DataFrame with same id,df1.reset_index()
Can I find the path of the executable running a python script from within the python script?,os.path.dirname(sys.executable)
How can I convert from scatter size to data coordinates in matplotlib?,plt.draw()
Network Pinging with Python,os.system('ping -c 5 www.examplesite.com')
Efficient array operations in python,transmission_array.extend(zero_array)
How to redirect 'print' output to a file using python?,f.write('whatever')
How do I check if all elements in a list are the same?,all(x == mylist[0] for x in mylist)
Python: Removing spaces from list objects,hello = [x.strip(' ') for x in hello]
ggplot multiple plots in one object,plt.show()
Finding the index of elements based on a condition using python list comprehension,a[:] = [x for x in a if x <= 2]