intent
stringlengths
4
183
snippet
stringlengths
2
1k
Python: How to remove empty lists from a list?
list2 = [x for x in list1 if x != []]
Python: How to remove empty lists from a list?
list2 = [x for x in list1 if x]
Django view returning json without using template
return HttpResponse(data, mimetype='application/json')
regex to get all text outside of brackets
re.findall('(.*?)\\[.*?\\]', example_str)
regex to get all text outside of brackets
re.findall('(.*?)(?:\\[.*?\\]|$)', example_str)
Matching multiple regex patterns with the alternation operator?
re.findall('\\(.+?\\)|\\w', '(zyx)bc')
Matching multiple regex patterns with the alternation operator?
re.findall('\\((.*?)\\)|(\\w)', '(zyx)bc')
Matching multiple regex patterns with the alternation operator?
re.findall('\\(.*?\\)|\\w', '(zyx)bc')
Perform a string operation for every element in a Python list
elements = ['%{0}%'.format(element) for element in elements]
start python script as background process from within a python script
subprocess.Popen(['background-process', 'arguments'])
Python dictionary: Get list of values for list of keys
[mydict[x] for x in mykeys]
Create dictionary from lists of keys and multiple values
dict([('Name', 'Joe'), ('Age', 22)])
Numpy - Averaging multiple columns of a 2D array
data.reshape(-1, j).mean(axis=1).reshape(data.shape[0], -1)
Replace all quotes in a string with escaped quotes?
print(s.encode('unicode-escape').replace('"', '\\"'))
Partitioning a string in Python by a regular expression
re.split('(\\W+)', s)
plotting stacked barplots on a panda data frame
df.plot(kind='barh', stacked=True)
How to reverse a dictionary in Python?
{i[1]: i[0] for i in list(myDictionary.items())}
finding index of multiple items in a list
[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()]
find out if a Python object is a string
isinstance(obj, str)
find out if a Python object is a string
isinstance(o, str)
find out if a Python object is a string
(type(o) is str)
find out if a Python object is a string
isinstance(o, str)
find out if a Python object is a string
isinstance(obj_to_test, str)
take the content of a list and append it to another list
list2.extend(list1)
take the content of a list and append it to another list
list1.extend(mylog)
take the content of a list and append it to another list
c.extend(a)
take the content of a list and append it to another list
for line in mylog: list1.append(line)
Appending tuples to lists
b.append((a[0][0], a[0][2]))
Where do I get a SECRET_KEY for Flask?
app.config['SECRET_KEY'] = 'Your_secret_string'
How to unpack a Series of tuples in Pandas?
pd.DataFrame(out.tolist(), columns=['out-1', 'out-2'], index=out.index)
How to find the position of an element in a list , in Python?
[x for x in range(len(stocks_list)) if stocks_list[x] == 'MSFT']
Is it possible to wrap the text of xticks in matplotlib in python?
ax.set_xticklabels(labels, rotation=45)
How to remove symbols from a string with Python?
re.sub('[^\\w]', ' ', s)
get current directory - Python
os.path.basename(os.path.dirname(os.path.realpath(__file__)))
Regex and Octal Characters
print(re.findall("'\\\\[0-7]{1,3}'", str))
Python split string based on regex
re.split('[ ](?=[A-Z]+\\b)', input)
Python split string based on regex
re.split('[ ](?=[A-Z])', input)
Using Python Requests to send file and JSON in single request
r = requests.post(url, files=files, headers=headers, data=data)
How to write bytes to a file in Python 3 without knowing the encoding?
open('filename', 'wb').write(bytes_)
Mapping dictionary value to list
[dct[k] for k in lst]
How to find duplicate names using pandas?
x.set_index('name').index.get_duplicates()
Truncating floats in Python
round(1.923328437452, 3)
Order list by date (String and datetime)
sorted(li, key=lambda x: datetime.strptime(x[1], '%d/%m/%Y'), reverse=True)
Move radial tick labels on a polar plot in matplotlib
ax.set_rlabel_position(135)
How to check if a path is absolute path or relative path in cross platform way with Python?
os.path.isabs(my_path)
Counting the Number of keywords in a dictionary in python
len(list(yourdict.keys()))
Counting the Number of keywords in a dictionary in python
len(set(open(yourdictfile).read().split()))
Pandas dataframe get first row of each group
df.groupby('id').first()
Splitting a list in a Pandas cell into multiple columns
pd.concat([df[0].apply(pd.Series), df[1]], axis=1)
Extracting specific src attributes from script tags
re.findall('src="js/([^"]*\\bjquery\\b[^"]*)"', data)
Most efficient way to convert items of a list to int and sum them up
sum(int(float(item)) for item in [_f for _f in ['', '3.4', '', '', '1.0'] if _f])
How to use subprocess when multiple arguments contain spaces?
subprocess.Popen(['c:\\Program Files\\VMware\\VMware Server\\vmware-cmd.bat'])
how to reverse a priority queue in Python without using classes?
q.put((-n, n))
pandas plot dataframe barplot with colors by category
df['group'].plot(kind='bar', color=['r', 'g', 'b', 'r', 'g', 'b', 'r'])
Python regex for MD5 hash
re.findall('([a-fA-F\\d]{32})', data)
Getting the length of an array
len(my_list)
Getting the length of an array
len(l)
Getting the length of an array
len(s)
Getting the length of an array
len(my_tuple)
Getting the length of an array
len(my_string)
remove escape character from string
"""\\a""".decode('string_escape')
Python string replace two things at once?
"""obama""".replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')
How do I remove/delete a folder that is not empty with Python?
shutil.rmtree('/folder_name')
in pandas how can I groupby weekday() for a datetime column?
data['weekday'] = data['my_dt'].apply(lambda x: x.weekday())
How to sort Counter by value? - python
sorted(x, key=x.get, reverse=True)
How to sort Counter by value? - python
sorted(list(x.items()), key=lambda pair: pair[1], reverse=True)
Append a NumPy array to a NumPy array
np.vstack((a, b))
numpy concatenate two arrays vertically
print(concatenate((a, b), axis=0))
numpy concatenate two arrays vertically
print(concatenate((a, b), axis=1))
numpy concatenate two arrays vertically
c = np.r_[(a[None, :], b[None, :])]
numpy concatenate two arrays vertically
np.array((a, b))
How can I do DNS lookups in Python, including referring to /etc/hosts?
print(socket.getaddrinfo('google.com', 80))
How to update a subset of a MultiIndexed pandas DataFrame
df.xs('sat', level='day', drop_level=False)
How do I return a 401 Unauthorized in Django?
return HttpResponse('Unauthorized', status=401)
How to dynamically select template directory to be used in flask?
Flask(__name__, template_folder='wherever')
How do I INSERT INTO t1 (SELECT * FROM t2) in SQLAlchemy?
session.execute('INSERT INTO t1 (SELECT * FROM t2)')
Sorting a list of lists in Python
c2.sort(key=lambda row: row[2])
Sorting a list of lists in Python
c2.sort(key=lambda row: (row[2], row[1], row[0]))
Sorting a list of lists in Python
c2.sort(key=lambda row: (row[2], row[1]))
Non-ASCII characters in Matplotlib
matplotlib.rc('font', **{'sans-serif': 'Arial', 'family': 'sans-serif'})
Pandas datetime column to ordinal
df['date'].apply(lambda x: x.toordinal())
Get HTML Source of WebElement in Selenium WebDriver using Python
element.get_attribute('innerHTML')
Most efficient way to get the integer index of a key in pandas
df.index.get_loc('bob')
open a terminal from python
os.system('gnome-terminal -e \'bash -c "sudo apt-get update; exec bash"\'')
Python - How to declare and add items to an array?
my_dict.update({'third_key': 1})
Python - How to declare and add items to an array?
my_list = []
Python - How to declare and add items to an array?
my_list.append(12)
Add entry to list and remove first one in Python
myList.insert(0, 'wuggah')
Converting a hex-string representation to actual bytes in Python
"""\\xF3\\xBE\\x80\\x80""".replace('\\x', '').decode('hex')
How to select the last column of dataframe
df[df.columns[-1]]
How to get a value from a Pandas DataFrame and not the index and object type
df.loc[df['Letters'] == 'C', 'Letters'].values[0]
Converting two lists into a matrix
np.column_stack(([1, 2, 3], [4, 5, 6]))
determine the variable type
type(i)
determine the variable type
type(v)
determine the variable type
type(v)
determine the variable type
type(v)
determine the variable type
type(v)
determine the variable type
print(type(variable_name))
Get the nth item of a generator in Python
next(itertools.islice(range(10), 5, 5 + 1))
printing double quotes around a variable
print('"{}"'.format(word))