text stringlengths 4 1.08k |
|---|
python sort list of lists with casting,"[['bla', '-0.2', 'blub'], ['bla', '0.1', 'blub'], ['blaa', '0.3', 'bli']]" |
Python sort parallel arrays in place?,"perm = sorted(range(len(foo)), key=lambda x: foo[x])" |
Pandas changing order of columns after data retrieval,"df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})" |
How to reliably open a file in the same directory as a Python script,print(os.path.dirname(os.path.abspath(sys.argv[0]))) |
How can I set the aspect ratio in matplotlib?,fig.savefig('force.png') |
Pandas intersect multiple series based on index,"pd.concat(series_list, axis=1)" |
summing only the numbers contained in a list,"sum([x for x in list if isinstance(x, (int, float))])" |
numpy replace negative values in array,"numpy.where(a <= 2, a, 2)" |
How can I change password for domain user(windows Active Directory) using Python?,"host = 'LDAP://10.172.0.79/dc=directory,dc=example,dc=com'" |
Specify list of possible values for Pandas get_dummies,"['A', 'B', 'C', 'B', 'B', 'D', 'E']" |
"How to write a pandas Series to CSV as a row, not as a column?",pd.DataFrame(s).T |
How can I convert this string to list of lists?,"ast.literal_eval('[[0,0,0], [0,0,1], [1,1,0]]')" |
How can I color Python logging output?,logging.warn('a warning') |
How to use ax.get_ylim() in matplotlib,"ax.axhline(1, color='black', lw=2)" |
Add Text on Image using PIL,"font = ImageFont.truetype('sans-serif.ttf', 16)" |
Add missing date index in dataframe,df.to_csv('test.csv') |
Removing starting spaces in Python?,"re.sub('^[^a]*', '')" |
How to get one number specific times in an array python,"[[4], [5, 5], [6, 6, 6]]" |
Regex to get list of all words with specific letters (unicode graphemes),"print(' '.join(get_words(['\u0baa', '\u0bae\u0bcd', '\u0b9f'])))" |
Row-wise indexing in Numpy,i = np.indices(B.shape)[0] |
Python: Make last item of array become the first,a[-2:] + a[:-2] |
Replace duplicate values across columns in Pandas,"pd.Series(['M', '0', 'M', '0']).duplicated()" |
Regular expression to return all characters between two special characters,"re.findall(pat, s)" |
"Is it possible to take an ordered ""slice"" of a dictionary in Python based on a list of keys?","res = [(x, my_dictionary[x]) for x in my_list if x in my_dictionary]" |
How to extract variable name and value from string in python,ast.literal_eval(ata.split('=')[1].strip()) |
How to remove duplicates from a dataframe?,"df = pd.DataFrame({'a': [1, 2, 3, 3, 3], 'b': [1, 2, None, 1, None]})" |
How to convert hex string to integer in Python?,"int('0x000000001', 16)" |
pythonic way to associate list elements with their indices,"d = dict([(y, x) for x, y in enumerate(t)])" |
tuple digits to number conversion,float(str(a[0]) + '.' + str(a[1])) |
Best way to randomize a list of strings in Python,""""""""""""".join([str(w) for w in random.sample(item, len(item))])" |
"SqlAlchemy and Flask, how to query many-to-many relationship",x = Dish.query.filter(Dish.restaurants.any(name=name)).all() |
pymssql windows authentication,"conn = pymssql.connect(server='EDDESKTOP', database='baseballData')" |
webdriver wait for ajax request in python,driver.implicitly_wait(10) |
Change the name of a key in dictionary,"dict((d1[key], value) for key, value in list(d.items()))" |
How to calculate a column in a Row using two columns of the previous Row in Spark Data Frame?,"df.select('*', current_population).show()" |
How to switch between python 2.7 to python 3 from command line?,print('hello') |
How can I simulate input to stdin for pyunit?,return int(input('prompt> ')) |
Expanding NumPy array over extra dimension,"np.tile(b, (2, 2, 2))" |
How to continue a task when Fabric receives an error,sudo('rm tmp') |
More efficient way to look up dictionary values whose keys start with same prefix,result = [d[key] for key in d if key.startswith(query)] |
Remove a prefix from a string,"print(remove_prefix('template.extensions', 'template.'))" |
Convert List to a list of tuples python,zip(*it) |
Unable to access files from public s3 bucket with boto,conn = boto.connect_s3(anon=True) |
Constructing a python set from a numpy matrix,y = numpy.unique(x) |
Repeating elements in list Python,"set(x[0] for x in zip(a, a[1:]) if x[0] == x[1])" |
How to determine whether a Pandas Column contains a particular value,"df.isin({'A': [1, 3], 'B': [4, 7, 12]})" |
Best way to return a value from a python script,sys.exit(0) |
"How can I parse HTML with html5lib, and query the parsed HTML with XPath?",[td.text for td in tree.xpath('//td')] |
delete a row from dataframe when the index (DateTime) is Sunday,df.asfreq('B') |
How to bind spacebar key to a certain method in tkinter (python),root.mainloop() |
how to combine two data frames in python pandas,"bigdata = pd.concat([data1, data2], ignore_index=True)" |
How to generate all permutations of a list in Python,"[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]" |
Auto delete data which is older than 10 days in django,posting_date = models.DateTimeField(auto_now_add=True) |
Save a subplot in matplotlib,fig.savefig('full_figure.png') |
One-line expression to map dictionary to another,"d = dict((m.get(k, k), v) for k, v in list(d.items()))" |
How can I get the path to the %APPDATA% directory in Python?,print(os.getenv('APPDATA')) |
How to make a window jump to the front?,"window.attributes('-topmost', 0)" |
How to serve file in webpy?,app.run() |
Quick way to upsample numpy array by nearest neighbor tiling,"np.kron(a, np.ones((B, B), a.dtype))" |
How to unzip an iterator?,"a = zip(list(range(10)), list(range(10)))" |
Pylab: map labels to colors,plt.show() |
How to re.sub() a optional matching group using regex in Python?,"re.sub('url((?:#[0-9]+)?)', 'new_url\\1', test2)" |
Writing hex data into a file,"f.write(bytes((i,)))" |
convert a flat list to list of list in python,"[['a', 'b', 'c'], ['d', 'e', 'f']]" |
Python Pandas: How to move one row to the first row of a Dataframe?,df.set_index('a') |
Multithreaded web server in python,server.serve_forever() |
Intraday candlestick charts using Matplotlib,plt.show() |
How to scrape a website that requires login first with Python,print(br.open('https://github.com/settings/emails').read()) |
How do I select a random element from an array in Python?,random.choice(mylist) |
Sort a part of a list in place,a[i:j].sort() |
Python get most recent file in a directory with certain extension,"newest = max(glob.iglob('upload/*.log'), key=os.path.getctime)" |
How to pass arguments to callback functions in PyQt,"some_action.triggered.connect(functools.partial(some_callback, param1, param2))" |
Appending data to a json file in Python,"json.dump([], f)" |
Test if a class is inherited from another,"self.assertTrue(issubclass(QuizForm, forms.Form))" |
How do I model a many-to-many relationship over 3 tables in SQLAlchemy (ORM)?,session.query(Shots).filter_by(event_id=event_id).order_by(asc(Shots.user_id)) |
pandas: get the value of the index for a row?,"df.set_index('prod_code', inplace=True)" |
Take multiple lists into dataframe,"pd.DataFrame(list(map(list, zip(lst1, lst2, lst3))))" |
Writing hex data into a file,f.write(hex(i)) |
Python: Find the sum of all the multiples of 3 or 5 below 1000,"sum(set(list(range(0, 1000, 3)) + list(range(0, 1000, 5))))" |
random Decimal in python,decimal.Decimal(str(random.random())) |
how to pick just one item from a generator (in python)?,next(g) |
How do I read a random line from one file in python?,print(random.choice(list(open('file.txt')))) |
python dictionary values sorting,"OrderedDict(sorted(list(d.items()), key=d.get))" |
Create multiple columns in Pandas Dataframe from one function,"return pandas.Series({'IV': iv, 'Vega': vega})" |
matplotlib: Group boxplots,"ax.set_xticklabels(['A', 'B', 'C'])" |
How to do CamelCase split in python,"['Camel', 'Case', 'XYZ']" |
Matching and Combining Multiple 2D lists in Python,"[['00f7e0b88577106a', '2', 'hdisk37']]" |
Python Matplotlib: plot with 2-dimensional arguments : how to specify options?,plt.show() |
Merge two python pandas data frames of different length but keep all rows in output data frame,"df1.merge(df2, how='left', left_on='Column1', right_on='ColumnA')" |
Calling a function of a module from a string with the function's name in Python,locals()['myfunction']() |
"in Python, how to convert list of float numbers to string with certain format?",p = [tuple('{0:.2f}'.format(c) for c in b) for b in a] |
Sorting a list of lists of dictionaries in python,"[{'play': 3.0, 'uid': 'mno', 'id': 5}, {'play': 1.0, 'uid': 'pqr', 'id': 6}]" |
Sorting list of lists by a third list of specified non-sorted order,"sorted(a, key=lambda x: b.index(x[0]))" |
Unpack a list in Python?,function_that_needs_strings(*my_list) |
Adding colors to a 3d quiver plot in matplotlib,plt.show() |
How do I run Python code from Sublime Text 2?,"{'keys': ['ctrl+shift+c'], 'command': 'exec', 'args': {'kill': true}}" |
Python Plot: How to remove grid lines not within the circle?,plt.show() |
Using multiple cursors in a nested loop in sqlite3 from python-2.7,db.commit() |
"How to use ""raise"" keyword in Python",raise Exception('My error!') |
Regex matching between two strings?,"m = re.findall('<!--(.*?)-->', string, re.DOTALL)" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.