text
stringlengths 4
1.08k
|
|---|
Extracting a URL in Python,"re.findall('(https?://\\S+)', s)"
|
How do I check if a list is sorted?,mylist.sort()
|
How to zip two lists of lists in Python?,"[sum(x, []) for x in zip(L1, L2)]"
|
Extract all keys from a list of dictionaries,all_keys = set().union(*(list(d.keys()) for d in mylist))
|
Remove the first word in a Python string?,"print(re.sub('^\\W*\\w+\\W*', '', text))"
|
a list > a list of lists,"[['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]"
|
Python how to sort this list?,lst.sort(reverse=True)
|
Writing multi-line strings into cells using openpyxl,workbook.close()
|
Finding Nth item of unsorted list without sorting the list,list(sorted(iter))[-10]
|
How to write to an existing excel file without overwriting data (using pandas)?,"writer = pd.ExcelWriter(excel_file, engine='openpyxl')"
|
Getting one value from a python tuple,i = 5 + Tup()[0]
|
Is there a need to close files that have no reference to them?,"open(to_file, 'w').write(indata)"
|
Python getting a string (key + value) from Python Dictionary,"['{}_{}'.format(k, v) for k, v in d.items()]"
|
Python: How to sort a list of dictionaries by several values?,"sorted(A, key=itemgetter('name', 'age'))"
|
Concatenating two one-dimensional NumPy arrays,"numpy.concatenate((a, b))"
|
Using Extensions with Selenium (Python),driver.quit()
|
Converting Python Dictionary to List,list(dict.items())
|
How to convert numpy datetime64 into datetime,x.astype('M8[ms]').astype('O')
|
Join float list into space-separated string in Python,"print(''.join(format(x, '10.3f') for x in a))"
|
Efficient calculation on a pandas dataframe,"C = pd.merge(C, B, on=['Marca', 'Formato'])"
|
How to create a number of empty nested lists in python,lst = [[] for _ in range(a)]
|
Organizing list of tuples,"[(1, 4), (4, 8), (8, 10)]"
|
Finding index of maximum element from Python list,"from functools import reduce
|
reduce(lambda a, b: [a, b], [1, 2, 3, 4])"
|
converting a time string to seconds in python,"time.strptime('00:00:00,000'.split(',')[0], '%H:%M:%S')"
|
Remove items from a list while iterating without using extra memory in Python,li = [x for x in li if condition(x)]
|
Get index of the top n values of a list in python,"zip(*heapq.nlargest(2, enumerate(a), key=operator.itemgetter(1)))[0]"
|
"How to split but ignore separators in quoted strings, in python?","re.split(';(?=(?:[^\'""]|\'[^\']*\'|""[^""]*"")*$)', data)"
|
in Python and linux how to get given user's id,pwd.getpwnam('aix').pw_uid
|
Change specific value in CSV file via Python,"df.to_csv('test.csv', index=False)"
|
"Find ""one letter that appears twice"" in a string","[i[0] for i in re.findall('(([a-z])\\2)', 'abbbbcppq')]"
|
Converting ConfigParser values to python data types,"literal_eval(""{'key': 10}"")"
|
Bits list to integer in Python,"int(''.join(str(i) for i in my_list), 2)"
|
Dividing a string into a list of smaller strings of certain length,"[mystr[i:i + 8] for i in range(0, len(mystr), 8)]"
|
Redirecting stdio from a command in os.system() in Python,os.system(cmd + '> /dev/null 2>&1')
|
Sorting JSON in python by a specific value,sorted_list_of_values = [item[1] for item in sorted_list_of_keyvalues]
|
"Is it possible to take an ordered ""slice"" of a dictionary in Python based on a list of keys?","res = [(x, my_dictionary[x]) for x in my_list]"
|
How to find all possible sequences of elements in a list?,"list(permutations([2, 3, 4]))"
|
Remove a level from a pandas MultiIndex,MultiIndex.from_tuples(index_3levels.droplevel('l3').unique())
|
How to use pandas dataframes and numpy arrays in Rpy2?,"r.plot([1, 2, 3], [1, 2, 3], xlab='X', ylab='Y')"
|
How to remove duplicates from a dataframe?,"df.sort_values(by=['a', 'b']).groupby(df.a).first()[['b']].reset_index()"
|
Removing list of words from a string,""""""" """""".join([x for x in query.split() if x.lower() not in stopwords])"
|
How can I return a default value for an attribute?,"a = getattr(myobject, 'id', None)"
|
python: regular expression search pattern for binary files (half a byte),pattern = re.compile('[@-O]')
|
python convert a list of float to string,"map(lambda n: '%.2f' % n, [1883.95, 1878.33, 1869.43, 1863.4])"
|
How can I color Python logging output?,"logging.Logger.__init__(self, name, logging.DEBUG)"
|
Django: How do I get the model a model inherits from?,StreetCat._meta.get_parent_list()
|
How to sort pandas data frame using values from several columns?,"df.sort(['c1', 'c2'], ascending=[False, True])"
|
How to group pandas DataFrame entries by date in a non-unique column,data.groupby(lambda x: data['date'][x].year)
|
ValueError: invalid literal for int() with base 10: '',float('55063.000000')
|
How to determine the order of bars in a matplotlib bar chart,plt.show()
|
Averaging over every n elements of a numpy array,"np.mean(arr.reshape(-1, 3), axis=1)"
|
Subsetting a 2D numpy array,"np.meshgrid([1, 2, 3], [1, 2, 3], indexing='ij')"
|
Split array at value in numpy,"B = np.split(A, np.where(A[:, (0)] == 0.0)[0][1:])"
|
Multi Index Sorting in Pandas,"df.sort([('Group1', 'C')], ascending=False)"
|
Generate a sequence of numbers in Python,""""""","""""".join('{},{}'.format(i, i + 1) for i in range(1, 100, 4))"
|
Drawing lines between two plots in Matplotlib,plt.show()
|
Print letters in specific pattern in Python,""""""""""""".join(i[1:] * int(i[0]) if i[0].isdigit() else i for i in l)"
|
How do I add space between two variables after a print in Python,"print('{0} {1}'.format(count, conv))"
|
Removing Trailing Zeros in Python,int('0000')
|
Removing Duplicates from Nested List Based on First 2 Elements,"list(dict(((x[0], x[1]), x) for x in L).values())"
|
conversion of bytes to string,binascii.b2a_hex('\x02P\x1cA\xd1\x00\x00\x02\xcb\x11\x00').decode('ascii')
|
Return common element indices between two numpy arrays,"numpy.nonzero(numpy.in1d(a2, a1))[0]"
|
Replace the single quote (') character from a string,"re.sub(""'"", '', ""A single ' char"")"
|
Parsing TCL lists in Python,re.compile('(?<=}})\\s+(?={{)')
|
How to know the position of items in a Python's ordered dictionary ,list(x.keys()).index('c')
|
python - How to format variable number of arguments into a string?,"'Hello %s' % ', '.join(map(str, my_args))"
|
What's the maximum number of repetitions allowed in a Python regex?,"re.search('a{1,65536}', 'aaa')"
|
Pythonic way to insert every 2 elements in a string,"list(zip(s[::2], s[1::2]))"
|
pupil detection in OpenCV & Python,contour = cv2.convexHull(contour)
|
How to flush the printed statements in IPython,sys.stdout.flush()
|
Sorting associative arrays in Python,"sorted(people, key=operator.itemgetter('name'))"
|
How to multiply all integers inside list,l = [(x * 2) for x in l]
|
Convert alphabet letters to number in Python,print([(ord(char) - 96) for char in input('Write Text: ').lower()])
|
base64 png in python on Windows,"open('icon.png', 'rb')"
|
How to make an immutable object in Python?,"Immutable = collections.namedtuple('Immutable', ['a', 'b'])"
|
Fastest way to convert an iterator to a list,list(your_iterator)
|
Intersection of 2d and 1d Numpy array,"A[:, 3:][np.in1d(A[:, 3:], B).reshape(A.shape[0], -1)] = 0"
|
Map two lists into a dictionary in Python,"new_dict = dict(zip(keys, values))"
|
How to drop duplicate from DataFrame taking into account value of another column,"df.drop_duplicates('name', keep='last')"
|
How can I convert nested dictionary keys to strings?,"{'1': {}, '2': {'101': 'OneZeroOne', '202': 'TwoZeroTwo'}}"
|
Applying a function to values in dict,"d2 = dict((k, f(v)) for k, v in list(d1.items()))"
|
Efficient way to convert numpy record array to a list of dictionary,"[dict(zip(r.dtype.names, x)) for x in r]"
|
Mass string replace in python?,""""""""""""".join(myparts)"
|
How to remove negative values from a list using lambda functions by python,[x for x in L if x >= 0]
|
Can you plot live data in matplotlib?,plt.show()
|
Python list comprehensions: set all elements in an array to 0 or 1,"[0, 1, 0, 1, 0, 0, 1, 0]"
|
Disable DSUSP in Python,time.sleep(2)
|
How can I configure Pyramid's JSON encoding?,"return {'color': 'color', 'message': 'message'}"
|
How to connect a progress bar to a function?,app.mainloop()
|
Equivelant to rindex for lists in Python,len(a) - a[-1::-1].index('hello') - 1
|
converting file from .txt to .csv doesn't write last column of data,writer.writerows(row.strip().split() for row in infile if row.strip())
|
How to resize window in opencv2 python,"cv2.namedWindow('main', cv2.WINDOW_NORMAL)"
|
Why do I need lambda to apply functions to a Pandas Dataframe?,df['SR'] = df['Info'].apply(foo)
|
Generate big random sequence of unique numbers,random.shuffle(a)
|
Multiple positional arguments with Python and argparse,"parser.parse_args(['-a', '-b', 'fileone', 'filetwo', 'filethree'])"
|
Running Python code contained in a string,"eval(""print('Hello, %s'%name)"", {}, {'name': 'person-b'})"
|
How to iterate and update documents with PyMongo?,cursor = collection.find({'$snapshot': True})
|
Remove small words using Python,""""""" """""".join(word for word in anytext.split() if len(word) > 3)"
|
How can I backup and restore MongoDB by using pymongo?,db.col.find({'price': {'$lt': 100}})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.