text stringlengths 4 1.08k |
|---|
Get models ordered by an attribute that belongs to its OneToOne model,User.objects.order_by('-pet__age')[:10] |
make a time delay,time.sleep(5) |
make a time delay,time.sleep(60) |
make a time delay,sleep(0.1) |
make a time delay,time.sleep(60) |
make a time delay,time.sleep(0.1) |
Remove strings from a list that contains numbers in python,[x for x in my_list if not any(c.isdigit() for c in x)] |
"how to do a left,right and mid of a string in a pandas dataframe",df['state'].apply(lambda x: x[len(x) / 2 - 1:len(x) / 2 + 1]) |
How do I draw a grid onto a plot in Python?,plt.grid(True) |
python How do you sort list by occurrence with out removing elements from the list?,"sorted(lst, key=lambda x: (-1 * c[x], lst.index(x)))" |
Find max length of each column in a list of lists,[max(len(str(x)) for x in line) for line in zip(*foo)] |
Count the number of Occurrence of Values based on another column,df.Country.value_counts().reset_index(name='Sum of Accidents') |
Calculating difference between two rows in Python / Pandas,data.set_index('Date').diff() |
python: append values to a set,"a.update([3, 4])" |
How can I get an array of alternating values in python?,a[1::2] = -1 |
Faster way to rank rows in subgroups in pandas dataframe,df.groupby('group')['value'].rank(ascending=False) |
Js Date object to python datetime,"datetime.strptime('Tue, 22 Nov 2011 06:00:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')" |
Python: Converting from binary to String,"struct.pack('<I', 1633837924)" |
Inserting a string into a list without getting split into characters,list.append('foo') |
Inserting a string into a list without getting split into characters,"list.insert(0, 'foo')" |
Case insensitive dictionary search with Python,theset = set(k.lower() for k in thedict) |
How to pad with n characters in Python,"""""""{s:{c}^{n}}"""""".format(s='dog', n=5, c='x')" |
How to check if type of a variable is string?,"isinstance(s, str)" |
How to check if type of a variable is string?,"isinstance(s, str)" |
How do I merge a list of dicts into a single dict?,dict(pair for d in L for pair in list(d.items())) |
How do I merge a list of dicts into a single dict?,"{k: v for d in L for k, v in list(d.items())}" |
How to sort a Pandas DataFrame according to multiple criteria?,"df.sort_values(['Peak', 'Weeks'], ascending=[True, False], inplace=True)" |
How to sort a Pandas DataFrame according to multiple criteria?,"df.sort(['Peak', 'Weeks'], ascending=[True, False], inplace=True)" |
Running Python code contained in a string,"eval(""print('Hello')"")" |
Creating a list of dictionaries in python,"[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]" |
Creating a list of dictionaries in python,"[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]" |
how to get all possible combination of items from 2-dimensional list in python?,list(itertools.product(*a)) |
"Pandas sum by groupby, but exclude certain columns","df.groupby(['Country', 'Item_Code'])[['Y1961', 'Y1962', 'Y1963']].sum()" |
Python turning a list into a list of tuples,"done = [(el, x) for el in [a, b, c, d]]" |
Removing nan values from an array,x = x[numpy.logical_not(numpy.isnan(x))] |
Removing the first folder in a path,os.path.join(*x.split(os.path.sep)[2:]) |
Replacing instances of a character in a string,"line = line.replace(';', ':')" |
Python - How to call bash commands with pipe?,"subprocess.call('tar c my_dir | md5sum', shell=True)" |
hex string to character in python,"""""""437c2123"""""".decode('hex')" |
Get required fields from Document in mongoengine?,"[k for k, v in User._fields.items() if v.required]" |
Pandas remove column by index,"df = df.ix[:, 0:2]" |
Change a string of integers separated by spaces to a list of int,"x = map(int, x.split())" |
Change a string of integers separated by spaces to a list of int,x = [int(i) for i in x.split()] |
Find and click an item from 'onclick' partial value,"driver.find_element_by_css_selector(""input[onclick*='1 Bedroom Deluxe']"")" |
Python / Remove special character from string,"re.sub('[^a-zA-Z0-9-_*.]', '', my_string)" |
How to display a pdf that has been downloaded in python,webbrowser.open('file:///my_pdf.pdf') |
Removing backslashes from a string in Python,"result = result.replace('\\', '')" |
Removing backslashes from a string in Python,"result.replace('\\', '')" |
Replace value in any column in pandas dataframe,"df.replace('-', 'NaN')" |
How do I convert datetime to date (in Python)?,datetime.datetime.now().date() |
How do I convert datetime to date (in Python)?,datetime.datetime.now().date() |
How to get all sub-elements of an element tree with Python ElementTree?,[elem.tag for elem in a.iter()] |
How to get all sub-elements of an element tree with Python ElementTree?,[elem.tag for elem in a.iter() if elem is not a] |
How can I split and parse a string in Python?,"""""""2.7.0_bf4fda703454"""""".split('_')" |
Python - Move elements in a list of dictionaries to the end of the list,"sorted(lst, key=lambda x: x['language'] != 'en')" |
"How to check if all values of a dictionary are 0, in Python?",all(value == 0 for value in list(your_dict.values())) |
Python Pandas Pivot Table,"df.pivot_table('Y', rows='X', cols='X2')" |
do a try-except without handling the exception,"try: |
doSomething() |
except: |
pass" |
do a try-except without handling the exception,"try: |
doSomething() |
except Exception: |
pass" |
Python - Sum 4D Array,M.sum(axis=0).sum(axis=0) |
Python datetime to microtime,time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0 |
How to check if any value of a column is in a range in Pandas?,df[(x <= df['columnX']) & (df['columnX'] <= y)] |
sort a list of lists by a specific index of the inner list,"sorted(L, key=itemgetter(2))" |
sort a list of lists by a specific index of the inner list,l.sort(key=(lambda x: x[2])) |
sort a list of lists by a specific index,"sorted(l, key=(lambda x: x[2]))" |
sort a list of lists by a specific index,"sorted_list = sorted(list_to_sort, key=itemgetter(2, 0, 1))" |
How to find row of 2d array in 3d numpy array,"np.argwhere(np.all(arr == [[0, 3], [3, 0]], axis=(1, 2)))" |
How to select only specific columns from a DataFrame with MultiIndex columns?,"data.loc[:, (list(itertools.product(['one', 'two'], ['a', 'c'])))]" |
How to select only specific columns from a DataFrame with MultiIndex columns?,"data.loc[:, ([('one', 'a'), ('one', 'c'), ('two', 'a'), ('two', 'c')])]" |
How to account for accent characters for regex in Python?,"hashtags = re.findall('#(\\w+)', str1, re.UNICODE)" |
Rename Files,"os.rename(src, dst)" |
How to get text for a root element using lxml?,print(etree.tostring(some_tag.find('strong'))) |
"Saving dictionary whose keys are tuples with json, python","json.dumps({str(k): v for k, v in data.items()})" |
How to correctly parse UTF-8 encoded HTML to Unicode strings with BeautifulSoup?,soup = BeautifulSoup(response.read().decode('utf-8')) |
How to delete a file without an extension?,os.remove(filename) |
Get the immediate minimum among a list of numbers in python,min([x for x in num_list if x > 2]) |
pandas: replace string with another string,df['prod_type'] = 'responsive' |
How do I sort a list with positives coming before negatives with values sorted respectively?,"sorted(lst, key=lambda x: (x < 0, x))" |
How do I calculate the date six months from the current date,six_months = (date.today() + relativedelta(months=(+ 6))) |
How do I calculate the date six months from the current date,"(date(2010, 12, 31) + relativedelta(months=(+ 1)))" |
How do I calculate the date six months from the current date,"(date(2010, 12, 31) + relativedelta(months=(+ 2)))" |
calculate the date six months from the current date,print((datetime.date.today() + datetime.timedelta(((6 * 365) / 12))).isoformat()) |
Finding The Biggest Key In A Python Dictionary,"sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)" |
how to get all the values from a numpy array excluding a certain index?,a[np.arange(len(a)) != 3] |
what is a quick way to delete all elements from a list that do not satisfy a constraint?,[x for x in lst if fn(x) != 0] |
Python Pandas - Date Column to Column index,df.set_index('month') |
How to read lines from a file into a multidimensional array (or an array of lists) in python,"arr = [line.split(',') for line in open('./urls-eu.csv')]" |
python list comprehension with multiple 'if's,[i for i in range(100) if i > 10 if i < 20] |
Removing letters from a list of both numbers and letters,""""""""""""".join([c for c in strs if c.isdigit()])" |
splitting a string based on tab in the file,"re.split('\\t+', yas.rstrip('\t'))" |
numpy matrix multiplication,(a.T * b).T |
remove (chomp) a newline,'test string\n'.rstrip() |
remove (chomp) a newline,'test string \n\n'.rstrip('\n') |
remove (chomp) a newline,s.strip() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.