text stringlengths 4 1.08k |
|---|
Slicing a list into a list of sub-lists,"list(grouper(2, [1, 2, 3, 4, 5, 6, 7]))" |
Slicing a list into a list of sub-lists,"[input[i:i + n] for i in range(0, len(input), n)]" |
Sorting numbers in string format with Python,"keys.sort(key=lambda x: map(int, x.split('.')))" |
Sorting numbers in string format with Python,keys.sort(key=lambda x: [int(y) for y in x.split('.')]) |
numpy with python: convert 3d array to 2d,"img.transpose(2, 0, 1).reshape(3, -1)" |
Replacing few values in a pandas dataframe column with another value,"df['BrandName'].replace(['ABC', 'AB'], 'A')" |
Replacing few values in a pandas dataframe column with another value,"df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')" |
Pandas: Subtract row mean from each element in row,"df.sub(df.mean(axis=1), axis=0)" |
"Python, remove all non-alphabet chars from string",""""""""""""".join([i for i in s if i.isalpha()])" |
How to split a string into integers in Python?,l = (int(x) for x in s.split()) |
How to split a string into integers in Python?,"""""""42 0"""""".split()" |
How to split a string into integers in Python?,"map(int, '42 0'.split())" |
Get the indexes of truthy elements of a boolean list as a list/tuple,"[i for i, elem in enumerate(bool_list, 1) if elem]" |
How to group pandas DataFrame entries by date in a non-unique column,data.groupby(data['date'].map(lambda x: x.year)) |
Getting the indices of several elements in a NumPy array at once,"np.in1d(b, a).nonzero()[0]" |
"In Python, how to display current time in readable format","time.strftime('%l:%M%p %z on %b %d, %Y')" |
Rotate axis text in python matplotlib,"ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)" |
How does python do string magic?,""""""""""""".join(['x', 'x', 'x'])" |
Array indexing in numpy,"x[(np.arange(x.shape[0]) != 1), :, :]" |
How do I pull a recurring key from a JSON?,print(item['name']) |
Read a File from redirected stdin with python,result = sys.stdin.read() |
How to get the content of a Html page in Python,""""""""""""".join(soup.findAll(text=True))" |
Extracting all rows from pandas Dataframe that have certain value in a specific column,data[data['Value'] == True] |
Removing duplicate characters from a string,""""""""""""".join(set(foo))" |
how to sort by a computed value in django,"sorted(Profile.objects.all(), key=lambda p: p.reputation)" |
python pandas flatten a dataframe to a list,df.values.flatten() |
how do I sort a python list of dictionaries given a list of ids with the desired order?,users.sort(key=lambda x: order.index(x['id'])) |
how do I sort a python list of dictionaries given a list of ids with the desired order?,users.sort(key=lambda x: order.index(x['id'])) |
Python requests library how to pass Authorization header with single token,"r = requests.get('<MY_URI>', headers={'Authorization': 'TOK:<MY_TOKEN>'})" |
How do I un-escape a backslash-escaped string in python?,"print('""Hello,\\nworld!""'.decode('string_escape'))" |
Can I have a non-greedy regex with dotall?,"re.findall('a*?bc*?', 'aabcc', re.DOTALL)" |
python/numpy: how to get 2D array column length?,a.shape[1] |
Adding calculated column(s) to a dataframe in pandas,"d.apply(lambda row: min([row['A'], row['B']]) - row['C'], axis=1)" |
Count number of occurrences of a given substring in a string,"""""""abcdabcva"""""".count('ab')" |
Get a list of values from a list of dictionaries in python,[d['key'] for d in l if 'key' in d] |
Get a list of values from a list of dictionaries in python,[d['key'] for d in l] |
Get a list of values from a list of dictionaries in python,[d['key'] for d in l] |
How to order a list of lists by the first value,l1.sort(key=lambda x: int(x[0])) |
How to order a list of lists by the first value,"sorted([[1, 'mike'], [1, 'bob']])" |
case sensitive string replacement in Python,"""""""Abc"""""".translate(maketrans('abcABC', 'defDEF'))" |
"python: dictionary to string, custom format?","""""""<br/>"""""".join([('%s:: %s' % (key, value)) for key, value in list(d.items())])" |
how to write a unicode csv in Python 2.7,self.writer.writerow([str(s).encode('utf-8') for s in row]) |
how to clear the screen in python,os.system('cls') |
how to clear the screen in python,os.system('clear') |
"In python 2.4, how can I execute external commands with csh instead of bash?",os.system('tcsh your_own_script') |
"In python 2.4, how can I execute external commands with csh instead of bash?","os.system(""zsh -c 'echo $0'"")" |
"Updating a list of python dictionaries with a key, value pair from another list","[dict(d, count=n) for d, n in zip(l1, l2)]" |
sum each value in a list of tuples,[sum(x) for x in zip(*l)] |
sum each value in a list of tuples,"map(sum, zip(*l))" |
Counting the number of non-NaN elements in a numpy ndarray matrix in Python,np.count_nonzero(~np.isnan(data)) |
Python: transform a list of lists of tuples,"map(list, zip(*main_list))" |
Django - taking values from POST request,"request.POST.get('title', '')" |
Check if string ends with one of the strings from a list,"""""""test.mp3"""""".endswith(('.mp3', '.avi'))" |
Splitting strings in python,"re.findall('\\[[^\\]]*\\]|""[^""]*""|\\S+', s)" |
Get top biggest values from each column of the pandas.DataFrame,"data.apply(lambda x: sorted(x, 3))" |
How do I permanently set the current directory to the Desktop in Python?,os.chdir('C:/Users/Name/Desktop') |
getting string between 2 characters in python,"re.findall('\\$([^$]*)\\$', string)" |
getting string between 2 characters in python,"re.findall('\\$(.*?)\\$', '$sin (x)$ is an function of x')" |
how to format date in ISO using python?,"datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()" |
Selecting specific column in each row from array,"A[[0, 1], [0, 1]]" |
Selecting specific column in each row from array,"a[np.arange(3), (0, 1, 0)]" |
Counting values in dictionary,"[k for k, v in dictA.items() if v.count('duck') > 1]" |
Sub matrix of a list of lists (without numpy),"[[2, 3, 4], [2, 3, 4], [2, 3, 4]]" |
How to call an element in an numpy array?,"print(arr[1, 1])" |
Setting matplotlib colorbar range,"quadmesh.set_clim(vmin=0, vmax=15)" |
read csv into record array in numpy,"my_data = genfromtxt('my_file.csv', delimiter=',')" |
read csv into record array in numpy,"df = pd.read_csv('myfile.csv', sep=',', header=None)" |
read csv into record array in numpy,"np.genfromtxt('myfile.csv', delimiter=',')" |
read csv into record array,"np.genfromtxt('myfile.csv', delimiter=',', dtype=None)" |
How do I read the first line of a string?,my_string.splitlines()[0] |
How do I read the first line of a string?,"my_string.split('\n', 1)[0]" |
How to generate a list from a pandas DataFrame with the column name and column values?,df.values.tolist() |
How to replace repeated instances of a character with a single instance of that character in python,"re.sub('\\*\\*+', '*', text)" |
How to replace repeated instances of a character with a single instance of that character in python,"re.sub('\\*+', '*', text)" |
Multiplying values from two different dictionaries together in Python,"dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2)" |
Random strings in Python,return ''.join(random.choice(string.lowercase) for i in range(length)) |
How to count all elements in a nested dictionary?,sum(len(x) for x in list(food_colors.values())) |
How to count all elements in a nested dictionary?,sum(len(v) for v in food_colors.values()) |
How to apply a logical operator to all elements in a python list,all(a_list) |
Removing characters from string Python,""""""""""""".join(c for c in text if c not in 'aeiouAEIOU')" |
Divide two lists in python,"[(x / y) for x, y in zip(a, b)]" |
Capturing group with findall?,"re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')" |
applying functions to groups in pandas dataframe,df.groupby('type').apply(lambda x: np.mean(np.log2(x['v']))) |
"Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)","[key for key, value in list(my_dict.items()) if set(value).intersection(lst)]" |
"Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)","[key for item in lst for key, value in list(my_dict.items()) if item in value]" |
Add tuple to a list of tuples,"c = [[(i + j) for i, j in zip(e, b)] for e in a]" |
Python: Get relative path from comparing two absolute paths,"os.path.commonprefix(['/usr/var', '/usr/var2/log'])" |
Python: Get relative path from comparing two absolute paths,"print(os.path.relpath('/usr/var/log/', '/usr/var'))" |
filtering grouped df in pandas,grouped.filter(lambda x: len(x) > 1) |
Python: sorting a dictionary of lists,"sorted(list(myDict.items()), key=lambda e: e[1][2])" |
What is the most pythonic way to avoid specifying the same value in a string,"""""""hello {name}, how are you {name}, welcome {name}"""""".format(name='john')" |
How to reorder indexed rows based on a list in Pandas data frame,"df.reindex(['Z', 'C', 'A'])" |
determine if a list contains other lists,"any(isinstance(el, list) for el in input_list)" |
get the size of a list,len(items) |
get the size of a list,"len([1, 2, 3])" |
get the size of a list,items.__len__() |
get the size of a list,len() |
get the size of a list,len(s) |
Fastest way to sort each row in a pandas dataframe,"df.sort(axis=1, ascending=False)" |
Fastest way to sort each row in a pandas dataframe,"df.sort(df.columns, axis=1, ascending=False)" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.