text
stringlengths
4
1.08k
Divide the values of two dictionaries in python,{k: (float(d2[k]) / d1[k]) for k in d2}
Divide the values of two dictionaries in python,{k: (d2[k] / d1[k]) for k in list(d1.keys()) & d2}
Divide the values of two dictionaries in python,"dict((k, float(d2[k]) / d1[k]) for k in d2)"
How to specify date format when using pandas.to_csv?,"df.to_csv(filename, date_format='%Y%m%d')"
How to remove a key from a python dictionary?,"my_dict.pop('key', None)"
replace values in an array,"b = np.where(np.isnan(a), 0, a)"
"Python, running command line tools in parallel","subprocess.call('start command -flags arguments', shell=True)"
"Python, running command line tools in parallel","subprocess.call('command -flags arguments &', shell=True)"
Passing the '+' character in a POST request in Python,"f = urllib.request.urlopen(url, urllib.parse.unquote(urllib.parse.urlencode(params)))"
How do I remove whitespace from the end of a string in Python?,""""""" xyz """""".rstrip()"
URL encoding in python,urllib.parse.quote(s.encode('utf-8'))
URL encoding in python,urllib.parse.quote_plus('a b')
Convert string to numpy array,"np.array(map(int, '100110'))"
Convert string to numpy array,"print(np.array(list(mystr), dtype=int))"
How can I convert an RGB image into grayscale in Python?,"img = cv2.imread('messi5.jpg', 0)"
sorting a graph by its edge weight. python,"lst.sort(key=lambda x: x[2], reverse=True)"
How to find all occurrences of an element in a list?,"indices = [i for i, x in enumerate(my_list) if x == 'whatever']"
How can I execute shell command with a | pipe in it,"subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)"
How to count the number of a specific character at the end of a string ignoring duplicates?,len(my_text) - len(my_text.rstrip('?'))
converting currency with $ to numbers in Python pandas,"df[df.columns[1:]].replace('[\\$,]', '', regex=True).astype(float)"
Conditionally fill a column of a pandas df with values of a different df,"df1.merge(df2, how='left', on='word')"
Switch every pair of characters in a string,"print(''.join(''.join(i) for i in zip(a2, a1)) + a[-1] if len(a) % 2 else '')"
How to make a window jump to the front?,"root.attributes('-topmost', True)"
How to make a window jump to the front?,root.lift()
Elegant way to convert list to hex string,"hex(int(''.join([str(int(b)) for b in walls]), 2))"
Elegant way to convert list to hex string,"hex(sum(b << i for i, b in enumerate(reversed(walls))))"
Print multiple arguments in python,"print(('Total score for', name, 'is', score))"
Print multiple arguments in python,"print('Total score for {} is {}'.format(name, score))"
Print multiple arguments in python,"print('Total score for %s is %s ' % (name, score))"
Print multiple arguments in python,"print(('Total score for', name, 'is', score))"
Is it possible to serve a static html page at the root of a django project?,"url('^$', TemplateView.as_view(template_name='your_template.html'))"
use a list of values to select rows from a pandas dataframe,"df[df['A'].isin([3, 6])]"
How to get the concrete class name as a string?,instance.__class__.__name__
How can I execute Python code in a virtualenv from Matlab,system('/path/to/my/venv/bin/python myscript.py')
django models selecting single field,"Employees.objects.values_list('eng_name', flat=True)"
Python regex findall alternation behavior,"re.findall('\\d|\\d,\\d\\)', '6,7)')"
How do I make python to wait for a pressed key,input('Press Enter to continue...')
Print string as hex literal python,"""""""ABC"""""".encode('hex')"
python + pymongo: how to insert a new field on an existing document in mongo from a for loop,"db.Doc.update({'_id': b['_id']}, {'$set': {'geolocCountry': myGeolocCountry}})"
"Regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc","re.sub('l+', 'l', 'lollll')"
Getting the nth element using BeautifulSoup,rows = soup.findAll('tr')[4::5]
Reverse Y-Axis in PyPlot,plt.gca().invert_xaxis()
Reverse Y-Axis in PyPlot,plt.gca().invert_yaxis()
How do I stack two DataFrames next to each other in Pandas?,"pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)"
Creating a JSON response using Django and Python,"return HttpResponse(json.dumps(response_data), content_type='application/json')"
Process escape sequences in a string,myString.decode('string_escape')
How do I calculate the md5 checksum of a file in Python?,"hashlib.md5(open('filename.exe', 'rb').read()).hexdigest()"
Finding key from value in Python dictionary:,"[k for k, v in d.items() if v == desired_value]"
Extract all keys from a list of dictionaries,{k for d in LoD for k in list(d.keys())}
Extract all keys from a list of dictionaries,set([i for s in [list(d.keys()) for d in LoD] for i in s])
Extract all keys from a list of dictionaries,[i for s in [list(d.keys()) for d in LoD] for i in s]
"Is there a more elegant way for unpacking keys and values of a dictionary into two lists, without losing consistence?","keys, values = zip(*list(d.items()))"
Convert a string to integer with decimal in Python,int(Decimal(s))
Convert a string to integer with decimal in Python,int(s.split('.')[0])
Numpy: How to check if array contains certain numbers?,"numpy.in1d(b, a).all()"
Numpy: How to check if array contains certain numbers?,numpy.array([(x in a) for x in b])
Node labels using networkx,"networkx.draw_networkx_labels(G, pos, labels)"
How to make a copy of a 2D array in Python?,y = [row[:] for row in x]
Pythonic way to populate numpy array,"X = numpy.loadtxt('somefile.csv', delimiter=',')"
Check if a Python list item contains a string inside another string,matching = [s for s in some_list if 'abc' in s]
How to write/read a Pandas DataFrame with MultiIndex from/to an ASCII file?,"df.to_csv('mydf.tsv', sep='\t')"
How do I create a LIST of unique random numbers?,"random.sample(list(range(100)), 10)"
Splitting on last delimiter in Python string?,"s.rsplit(',', 1)"
Python check if all elements of a list are the same type,"all(isinstance(x, int) for x in lst)"
Python check if all elements of a list are the same type,"all(isinstance(x, int) for x in lst)"
Python . How to get rid of '\r' in string?,line.strip()
How can I scroll a web page using selenium webdriver in python?,"driver.execute_script('window.scrollTo(0, Y)')"
How can I scroll a web page using selenium webdriver in python?,"driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')"
How do I convert a datetime.date object into datetime.datetime in python?,"datetime.datetime.combine(dateobject, datetime.time())"
How to check if one of the following items is in a list?,print(any(x in a for x in b))
Saving a Numpy array as an image,"scipy.misc.imsave('outfile.jpg', image_array)"
Regex for removing data in parenthesis,"item = re.sub(' ?\\([^)]+\\)', '', item)"
Regex for removing data in parenthesis,"item = re.sub(' ?\\(\\w+\\)', '', item)"
Regex for removing data in parenthesis,"item = re.sub(' \\(\\w+\\)', '', item)"
Checking if any elements in one list are in another,len(set(list1).intersection(list2)) > 0
convert hex to decimal,"i = int(s, 16)"
convert hex to decimal,"int('0xff', 16)"
convert hex to decimal,"int('FFFF', 16)"
convert hex to decimal,ast.literal_eval('0xdeadbeef')
convert hex to decimal,"int('deadbeef', 16)"
Take screenshot in Python on Mac OS X,os.system('screencapture screen.png')
How to set window size using phantomjs and selenium webdriver in python,"driver.set_window_size(1400, 1000)"
Replace non-ascii chars from a unicode string in Python,"unicodedata.normalize('NFKD', 'm\xfasica').encode('ascii', 'ignore')"
Pandas/Python: How to concatenate two dataframes without duplicates?,"pandas.concat([df1, df2]).drop_duplicates().reset_index(drop=True)"
numpy: efficiently reading a large array,"a = numpy.fromfile('filename', dtype=numpy.float32)"
How to use the mv command in Python with subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)"
How to use the mv command in Python with subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)"
How to use Unicode characters in a python string,print('\u25b2'.encode('utf-8'))
Comparing two .txt files using difflib in Python,"difflib.SequenceMatcher(None, file1.read(), file2.read())"
Creating a dictionary from a string,"dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))"
How to check if all elements in a tuple or list are in another?,"all(i in (1, 2, 3, 4, 5) for i in (1, 6))"
python pandas extract unique dates from time series,df['Date'].map(lambda t: t.date()).unique()
Formatting text to be justified in Python 3.3 with .format() method,"""""""{:>7s}"""""".format(mystring)"
How do I read an Excel file into Python using xlrd? Can it read newer Office formats?,"open('ComponentReport-DJI.xls', 'rb').read(200)"
How to sort a dataFrame in python pandas by two or more columns?,"df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)"
How to sort a dataFrame in python pandas by two or more columns?,"df.sort_values(['a', 'b'], ascending=[True, False])"
How to sort a dataFrame in python pandas by two or more columns?,"df1.sort(['a', 'b'], ascending=[True, False], inplace=True)"
How to sort a dataFrame in python pandas by two or more columns?,"df.sort(['a', 'b'], ascending=[True, False])"
Django redirect to root from a view,redirect('Home.views.index')
Remove all values within one list from another list in python,"[x for x in a if x not in [2, 3, 7]]"