text
stringlengths 4
1.08k
|
---|
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))" |
Python concat string with list,""""""" """""".join(list)" |
Extending a list of lists in Python?,y = [[] for n in range(2)] |
How do you read a file into a list in Python?,"data = [line.strip() for line in open('C:/name/MyDocuments/numbers', 'r')]" |
How to delete all instances of a character in a string in python?,""""""""""""".join([char for char in 'it is icy' if char != 'i'])" |
How to delete all instances of a character in a string in python?,"re.sub('i', '', 'it is icy')" |
How to delete all instances of a character in a string in python?,"""""""it is icy"""""".replace('i', '')" |
How to delete all instances of a character in a string in python?,""""""""""""".join([char for char in 'it is icy' if char != 'i'])" |
How to drop rows of Pandas DataFrame whose value in certain columns is NaN,df.dropna(subset=[1]) |
Searching a list of objects in Python,[x for x in myList if x.n == 30] |
converting list of string to list of integer,nums = [int(x) for x in intstringlist] |
converting list of string to list of integer,"map(int, eval(input('Enter the unfriendly numbers: ')))" |
print in Python without newline or space,sys.stdout.write('.') |
Python float to int conversion,int(round(2.51 * 100)) |
Find all files in directory with extension .txt,"os.chdir('/mydir') |
for file in glob.glob('*.txt'): |
pass" |
Find all files in directory with extension .txt,"for file in os.listdir('/mydir'): |
if file.endswith('.txt'): |
pass" |
Find all files in directory with extension .txt,"for (root, dirs, files) in os.walk('/mydir'): |
for file in files: |
if file.endswith('.txt'): |
pass" |
Pandas (python) plot() without a legend,df.plot(legend=False) |
loop through an IP address range,"for i in range(256): |
for j in range(256): |
ip = ('192.168.%d.%d' % (i, j)) |
print(ip)" |
loop through an IP address range,"for (i, j) in product(list(range(256)), list(range(256))): |
pass" |
loop through an IP address range,"generator = iter_iprange('192.168.1.1', '192.168.255.255', step=1)" |
Python/Numpy: Convert list of bools to unsigned int,"sum(1 << i for i, b in enumerate(x) if b)" |
Python: How to write multiple strings in one line?,"target.write('%r\n%r\n%r\n' % (line1, line2, line3))" |
How to flatten a hetrogenous list of list into a single list in python?,"[y for x in data for y in (x if isinstance(x, list) else [x])]" |
"In Python, is it possible to escape newline characters when printing a string?",print('foo\nbar'.encode('string_escape')) |
String Slicing Python,""""""""""""".join(s.rsplit(',', 1))" |
Middle point of each pair of an numpy.array,(x[1:] + x[:-1]) / 2 |
Middle point of each pair of an numpy.array,x[:-1] + (x[1:] - x[:-1]) / 2 |
Reading unicode elements into numpy array,"arr = numpy.fromiter(codecs.open('new.txt', encoding='utf-8'), dtype='<U2')" |
How to sort this list in Python?,"l = sorted(l, key=itemgetter('time'), reverse=True)" |
How to sort this list in Python?,"l = sorted(l, key=lambda a: a['time'], reverse=True)" |
pandas DataFrame filter regex,df.loc[df[0].str.contains('(Hel|Just)')] |
How do I find the string between two special characters?,"re.search('\\[(.*)\\]', your_string).group(1)" |
How to create a list of date string in 'yyyymmdd' format with Python Pandas?,"[d.strftime('%Y%m%d') for d in pandas.date_range('20130226', '20130302')]" |
How to count the number of times something occurs inside a certain string?,"""""""The big brown fox is brown"""""".count('brown')" |
Sending post data from angularjs to django as JSON and not as raw content,json.loads(request.body) |
Download file from web in Python 3,"urllib.request.urlretrieve(url, file_name)" |
Split string into a list,text.split() |
Split string into a list,"text.split(',')" |
Split string into a list,line.split() |
Replacing characters in a regex,"[re.sub('(?<!\\d)\\.(?!\\d)', ' ', i) for i in s]" |
Sort A list of Strings Based on certain field,"sorted(list_of_strings, key=lambda s: s.split(',')[1])" |
how to call multiple bash functions using | in python,"subprocess.check_call('vasp | tee tee_output', shell=True)" |
How to eliminate all strings from a list,"[element for element in lst if isinstance(element, int)]" |
How to eliminate all strings from a list,"[element for element in lst if not isinstance(element, str)]" |
How do I sort a list of dictionaries by values of the dictionary in Python?,"newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])" |
How do I sort a list of dictionaries by values of the dictionary in Python?,"newlist = sorted(l, key=itemgetter('name'), reverse=True)" |
How do I sort a list of dictionaries by values of the dictionary in Python?,list_of_dicts.sort(key=operator.itemgetter('name')) |
How do I sort a list of dictionaries by values of the dictionary in Python?,list_of_dicts.sort(key=operator.itemgetter('age')) |
How to sort a Dataframe by the ocurrences in a column in Python (pandas),"df.groupby('prots').sum().sort('scores', ascending=False)" |
How can I access elements inside a list within a dictionary python?,""""""","""""".join(trans['category'])" |
Variants of string concatenation?,""""""""""""".join(['A', 'B', 'C', 'D'])" |
How do I get JSON data from RESTful service using Python?,json.load(urllib.request.urlopen('url')) |
Removing an item from list matching a substring - Python,[x for x in sents if not x.startswith('@$\t') and not x.startswith('#')] |
Django filter by hour,Entry.objects.filter(pub_date__contains='08:00') |
sort a list of dicts by x then by y,"list.sort(key=lambda item: (item['points'], item['time']))" |
How to convert a Python datetime object to seconds,"(t - datetime.datetime(1970, 1, 1)).total_seconds()" |
Subsets and Splits