text
stringlengths 4
1.08k
|
---|
How do I perform secondary sorting in python?,"sorted(list5, lambda x: (degree(x), x))" |
How do I perform secondary sorting in python?,"sorted(list5, key=lambda vertex: (degree(vertex), vertex))" |
Python: convert list to generator,"(n for n in [1, 2, 3, 5])" |
Remove multiple items from list in Python,"newlist = [v for i, v in enumerate(oldlist) if i not in removelist]" |
Deleting a specific line in a file (python),"f = open('yourfile.txt', 'w')" |
Attribute getters in python,"getattr(obj, 'attr')" |
How do I convert tuple of tuples to list in one line (pythonic)?,"from functools import reduce |
reduce(lambda a, b: a + b, (('aa',), ('bb',), ('cc',)))" |
How do I convert tuple of tuples to list in one line (pythonic)?,"map(lambda a: a[0], (('aa',), ('bb',), ('cc',)))" |
Python Pandas: How to replace a characters in a column of a dataframe?,"df['range'].replace(',', '-', inplace=True)" |
inverse of zip,"zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])" |
inverse of zip,"zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])" |
inverse of zip,"result = ([a for (a, b) in original], [b for (a, b) in original])" |
inverse of zip,"result = ((a for (a, b) in original), (b for (a, b) in original))" |
inverse of zip,"zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)])" |
inverse of zip,"map(None, *[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)])" |
Python JSON serialize a Decimal object,json.dumps(Decimal('3.9')) |
Add key to a dictionary,d['mynewkey'] = 'mynewvalue' |
Add key to a dictionary,"data.update({'a': 1, })" |
Add key to a dictionary,data.update(dict(a=1)) |
Add key to a dictionary,data.update(a=1) |
Is there a one line code to find maximal value in a matrix?,max([max(i) for i in matrix]) |
Python - how to round down to 2 decimals,"answer = str(round(answer, 2))" |
Extract IP address from an html string (python),"ip = re.findall('[0-9]+(?:\\.[0-9]+){3}', s)" |
How do I filter a pandas DataFrame based on value counts?,df.groupby('A').filter(lambda x: len(x) > 1) |
Converting a string into a list in Python,[x for x in myfile.splitlines() if x != ''] |
Converting a string into a list in Python,"lst = map(int, open('filename.txt').readlines())" |
Adding Colorbar to a Spectrogram,"plt.colorbar(mappable=mappable, cax=ax3)" |
Count most frequent 100 words from sentences in Dataframe Pandas,Counter(' '.join(df['text']).split()).most_common(100) |
Python split a string using regex,"re.findall('(.+?):(.+?)\\b ?', text)" |
Generate all subsets of size k (containing k elements) in Python,"list(itertools.combinations((1, 2, 3), 2))" |
"Python: How to get a value of datetime.today() that is ""timezone aware""?",datetime.now(pytz.utc) |
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))" |
Subsets and Splits