text
stringlengths 4
1.08k
|
|---|
Assigning string with boolean expression,openmode = 'w'
|
Python - use list as function parameters,some_func(*params)
|
Change one character in a string in Python?,""""""""""""".join(s)"
|
Using session in flask app,app.run()
|
How can i list only the folders in zip archive in Python?,[x for x in file.namelist() if x.endswith('/')]
|
Can I prevent fabric from prompting me for a sudo password?,"sudo('some_command', shell=False)"
|
How to check if a value exists in a dictionary (python),'one' in list(d.values())
|
"Writing a ""table"" from Python3","write('Temperature is {0} and pressure is {1})'.format(X, Y))"
|
Slicing a list into a list of sub-lists,"list(zip(*((iter([1, 2, 3, 4, 5, 6, 7, 8, 9]),) * 3)))"
|
Element-wise minimum of multiple vectors in numpy,"np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)"
|
How to count values in a certain range in a Numpy array?,((25 < a) & (a < 100)).sum()
|
Sum of outer product of corresponding lists in two arrays - NumPy,"[np.einsum('i,j->', x[n], e[n]) for n in range(len(x))]"
|
Django REST Framework - Serializing optional fields,"super(ProductSerializer, self).__init__(*args, **kwargs)"
|
Trying to strip b' ' from my Numpy array,"array(['one.com', 'two.url', 'three.four'], dtype='|S10')"
|
How can I sum the product of two list items using for loop in python?,"sum(x * y for x, y in zip(a, b))"
|
Can a list of all member-dict keys be created from a dict of dicts using a list comprehension?,[k for d in list(foo.values()) for k in d]
|
Combining two lists into a list of lists,"[('1', '11'), ('2', '22'), ('', '33'), ('', '44')]"
|
how to get request object in django unit testing?,"self.assertEqual(response.status_code, 200)"
|
How can I convert a string to an int in Python?,return float(a) / float(b)
|
How to add items into a numpy array,"array([[1, 3, 4, 10], [1, 2, 3, 20], [1, 2, 1, 30]])"
|
Python: Want to use a string as a slice specifier,slice(*[(int(i.strip()) if i else None) for i in string_slice.split(':')])
|
Is there a cleaner way to iterate through all binary 4-tuples?,"itertools.product(list(range(2)), repeat=4)"
|
"How do I randomly select a variable from a list, and then modify it in python?","['1', '2', '3', '4', '5', '6', '7', 'X', '9']"
|
How to decode unicode raw literals to readable string?,s.decode('unicode_escape')
|
How can I tail a log file in Python?,time.sleep(1)
|
How to format list and dictionary comprehensions,"{k: v for k, v in enumerate(range(10)) if v % 2 == 0}"
|
Python app engine: how to save a image?,self.response.out.write('Image not available')
|
Control a print format when printing a list in Python,"print('[%s]' % ', '.join('%.3f' % val for val in list))"
|
Python: updating a large dictionary using another large dictionary,b.update(d)
|
How to read only part of a list of strings in python,[s[:5] for s in buckets]
|
Align numpy array according to another array,"a[np.in1d(a, b)]"
|
How to install subprocess module for python?,subprocess.call(['py.test'])
|
Python: Check if a string contains chinese character?,"re.findall('[\u4e00-\u9fff]+', ipath)"
|
Return list of items in list greater than some value,[x for x in j if x >= 5]
|
Find the nth occurrence of substring in a string,"""""""foo bar bar bar"""""".replace('bar', 'XXX', 1).find('bar')"
|
finding index of an item closest to the value in a list that's not entirely sorted,"min(enumerate(a), key=lambda x: abs(x[1] - 11.5))"
|
Parameters to numpy's fromfunction,"array([[0.0, 0.0], [1.0, 1.0]]), array([[0.0, 1.0], [0.0, 1.0]])"
|
Creating a zero-filled pandas data frame,"d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)"
|
Convert tab-delimited txt file into a csv file using Python,"list(csv.reader(open('demo.txt', 'r'), delimiter='\t'))"
|
Sorting dictionary keys in python,"sorted(d, key=d.get)"
|
How to use re match objects in a list comprehension,[m.group(1) for l in lines for m in [regex.search(l)] if m]
|
Python Pandas: How to get the row names from index of a dataframe?,df.index['Row 2':'Row 5']
|
Convert list of tuples to list?,"[1, 2, 3]"
|
sorting values of python dict using sorted builtin function,"sorted(iter(mydict.items()), key=itemgetter(1), reverse=True)"
|
How to add a new row to an empty numpy array,"arr = np.empty((0, 3), int)"
|
How to make curvilinear plots in matplotlib,"plt.plot(line[0], line[1], linewidth=0.5, color='k')"
|
How to remove all integer values from a list in python,"no_integers = [x for x in mylist if not isinstance(x, int)]"
|
numpy with python: convert 3d array to 2d,"img.transpose(2, 0, 1).reshape(3, -1)"
|
Is there a way to make Seaborn or Vincent interactive?,"plt.plot(x, y)"
|
How to convert this particular json string into a python dictionary?,"json.loads('[{""name"":""sam""}]')"
|
Omit (or format) the value of a variable when documenting with Sphinx,"self.add_line(' :annotation: = ' + objrepr, '<autodoc>')"
|
python split string based on regular expression,"re.split(' +', str1)"
|
Manually setting xticks with xaxis_date() in Python/matplotlib,plt.show()
|
Turning string with embedded brackets into a dictionary,"{'key3': 'value with spaces', 'key2': 'value2', 'key1': 'value1'}"
|
Python BeautifulSoup Extract specific URLs,"soup.find_all('a', href=re.compile('http://www\\.iwashere\\.com/'))"
|
Python & Matplotlib: creating two subplots with different sizes,plt.show()
|
Histogram equalization for python,"plt.imshow(im2, cmap=plt.get_cmap('gray'))"
|
Regular expression to return all characters between two special characters,"re.findall('\\[(.*?)\\]', mystring)"
|
Calcuate mean for selected rows for selected columns in pandas data frame,"df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=1)"
|
multiple plot in one figure in Python,plt.show()
|
How do I reuse plots in matplotlib?,plt.draw()
|
"Is there a way to perform ""if"" in python's lambda",lambda x: True if x % 2 == 0 else False
|
Taking a screenshot with Pyglet [Fix'd],pyglet.app.run()
|
Using a Python Dictionary as a Key (Non-nested),tuple(sorted(a.items()))
|
How can I convert Unicode to uppercase to print it?,print('ex\xe1mple'.upper())
|
How to sort tire sizes in python,"['235', '40', '17']"
|
"In Python, why won't something print without a newline?",sys.stdout.flush()
|
How to remove gray border from matplotlib,plt.show()
|
How can I control a fan with GPIO on a Raspberry Pi 3 using Python?,time.sleep(5)
|
Transform unicode string in python,"data['City'].encode('ascii', 'ignore')"
|
Pandas: join with outer product,demand.ix['Com'].apply(lambda x: x * series)
|
Two values from one input in python?,"var1, var2 = input('Enter two numbers here: ').split()"
|
Circular pairs from array?,"[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1)]"
|
Pandas DataFrame to List of Dictionaries,df.to_dict('index')
|
Numpy: Get random set of rows from 2D array,"A[(np.random.choice(A.shape[0], 2, replace=False)), :]"
|
Print list in table format in python,print(' '.join(row))
|
How to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly?,{{my_variable | forceescape | linebreaks}}
|
How can I tell if a file is a descendant of a given directory?,"os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == '/the/dir/'"
|
sorting a graph by its edge weight. python,"lst.sort(key=lambda x: x[2], reverse=True)"
|
How do I url encode in Python?,urllib.parse.quote('http://spam.com/go/')
|
how to combine two columns with an if/else in python pandas?,"df['year'] = df['year'].where(source_years != 0, df['year'])"
|
Max Value within a List of Lists of Tuple,"output.append(max(flatlist, key=lambda x: x[1]))"
|
"Flatten, remove duplicates, and sort a list of lists in python","y = sorted(set(x), key=lambda s: s.lower())"
|
Regular expression to find any number in a string,nums.search('0001.20000').group(0)
|
"Concatenating Unicode with string: print '£' + '1' works, but print '£' + u'1' throws UnicodeDecodeError",print('\xa31'.encode('latin-1'))
|
All combinations of a list of lists,list(itertools.product(*a))
|
How to check for palindrome using Python logic,str(n) == str(n)[::-1]
|
Python: BeautifulSoup - get an attribute value based on the name attribute,"soup.find('meta', {'name': 'City'})['content']"
|
How to convert strings numbers to integers in a list?,changed_list = [(int(f) if f.isdigit() else f) for f in original_list]
|
Flask sqlalchemy many-to-many insert data,db.session.commit()
|
how to plot arbitrary markers on a pandas data series?,ts.plot(marker='.')
|
Python MySQL escape special characters,sql = 'UPGRADE inventory_server set server_mac = %s where server_name = %s'
|
Efficient distance calculation between N points and a reference in numpy/scipy,"np.sqrt(np.sum((a - b) ** 2, axis=1))"
|
Sum of Every Two Columns in Pandas dataframe,np.arange(len(df.columns)) // 2
|
"Why can you loop through an implicit tuple in a for loop, but not a comprehension in Python?","[i for i in ('a', 'b', 'c')]"
|
How can I set the aspect ratio in matplotlib?,fig.savefig('axAspect.png')
|
In Tkinter is there any way to make a widget not visible? ,root.mainloop()
|
Insert item into case-insensitive sorted list in Python,"['aa', 'bb', 'CC', 'Dd', 'ee']"
|
How do you check the presence of many keys in a Python dictinary?,"set(['stackoverflow', 'google']).issubset(sites)"
|
Sorting JSON in python by a specific value,"entries = sorted(list(json_data.items()), key=lambda items: items[1]['data_two'])"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.