text
stringlengths
4
1.08k
How can I use a string with the same name of an object in Python to access the object itself?,locals()[x]
how to get content of a small ascii file in python?,return f.read()
"how to change [1,2,3,4] to '1234' using python",""""""""""""".join(str(i) for i in [1, 2, 3, 4])"
Python - Finding index of first non-empty item in a list,"next((i for i, j in enumerate(lst) if j == 2), 42)"
Finding consecutive consonants in a word,"re.findall('[^aeiou]+', '123concertation')"
How do you create nested dict in Python?,dict(d)
Python Selenium get current window handle,driver.current_window_handle
How to check if a string is at the beginning of line in spite of tabs or whitespaces?,"re.match('^\\s*word', line)"
Print specific lines of multiple files in Python,f.close()
Coverting Index into MultiIndex (hierachical index) in Pandas,"df.set_index(['e-mail', 'date'])"
Pandas: aggregate based on filter on another column,"df.groupby(['Fruit', 'Month'])['Sales'].sum().unstack('Month', fill_value=0)"
How to print a list of tuples,"a, b, c = 'a', 'b', 'c'"
Fill multi-index Pandas DataFrame with interpolation,df.unstack(level=1)
Reverse sort of Numpy array with NaN values,"np.concatenate((np.sort(a[~np.isnan(a)])[::-1], [np.nan] * np.isnan(a).sum()))"
How to merge two dataframe in pandas to replace nan,"a.where(~np.isnan(a), other=b, inplace=True)"
Writing hex data into a file,f.write(chr(i))
argparse module How to add option without any argument?,"parser.add_argument('-s', '--simulate', action='store_true')"
Disable/Remove argument in argparse,"parser.add_argument('--arg1', help=argparse.SUPPRESS)"
"Python: How to ""fork"" a session in django","return render(request, 'organisation/wall_post.html', {'form': form})"
Access item in a list of lists,50 - list1[0][0] + list1[0][1] - list1[0][2]
How can I get href links from HTML using Python?,print(link.get('href'))
How to print like printf in python3?,"print('a=%d,b=%d' % (f(x, n), g(x, n)))"
Interleaving Lists in Python,"[x for t in zip(list_a, list_b) for x in t]"
Sorting the content of a dictionary by the value and by the key,"sorted(list(d.items()), key=lambda x: x[::-1])"
Make a 2D pixel plot with matplotlib,plt.show()
Python String replace based on chars NOT in RegEx,"re.sub('[^a-zA-Z0-9]', '_', filename)"
How do I get the full XML or HTML content of an element using ElementTree?,""""""""""""".join([t.text] + [xml.tostring(e) for e in t.getchildren()])"
Working with NaN values in matplotlib,plt.show()
plotting seismic wiggle traces using matplotlib,plt.show()
How to get the first column of a pandas DataFrame as a Series?,"df.iloc[:, (0)]"
How to strip all whitespace from string,""""""""""""".join(s.split())"
Splitting dictionary/list inside a Pandas Column into Separate Columns,"pd.concat([df.drop(['b'], axis=1), df['b'].apply(pd.Series)], axis=1)"
How do I construct and populate a wx.Grid with data from a database (python/wxpython),"mygrid.SetCellValue(row, col, databasevalue4rowcol)"
Pandas Dataframe Bar Plot - Qualitative Variable?,df.groupby('source')['retweet_count'].sum().plot(kind='bar')
"How to bind multiple widgets with one ""bind"" in Tkinter?",root.mainloop()
How to get a random value in python dictionary,random.choice(list(d.keys()))
How to get the union of two lists using list comprehension?,list(set(a).union(b))
Including a Django app's url.py is resulting in a 404,"urlpatterns = patterns('', ('^gallery/', include('mysite.gallery.urls')))"
How to obtain the last index of a list?,last_index = len(list1) - 1
How to make Python format floats with certain amount of significant digits?,"print('%.6g' % (i,))"
Parse XML file into Python object,"[(ch.tag, ch.text) for e in tree.findall('file') for ch in e.getchildren()]"
"How to make a python script ""pipeable"" in bash?",sys.stdout.write(line)
How to conditionally update DataFrame column in Pandas,"df.loc[df['line_race'] == 0, 'rating'] = 0"
Regex. Match words that contain special characters or 'http://',"re.findall('(http://\\S+|\\S*[^\\w\\s]\\S*)', a)"
Replacing instances of a character in a string,"line = line[:10].replace(';', ':') + line[10:]"
python: create list of tuples from lists,"z = zip(x, y)"
How can I use a string with the same name of an object in Python to access the object itself?,locals()[x]
How to use sadd with multiple elements in Redis using Python API?,"r.sadd('a', *set([3, 4]))"
Get the immediate minimum among a list of numbers in python,a = list(a)
How can I get dict from sqlite query?,print(cur.fetchone()['a'])
Removing elements from an array that are in another array,A = [i for i in A if i not in B]
How can I find the first occurrence of a sub-string in a python string?,s.find('dude')
Slicing a NumPy array within a loop,"array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])"
Print output in a single line,"print('{0} / {1}, '.format(x + 1, y), end=' ')"
"django-social-auth : connected successfully, how to query for users now?",user.social_auth.filter(provider='...')
Beautiful Soup Using Regex to Find Tags?,soup.find_all(re.compile('(a|div)'))
Getting a list of all subdirectories in the current directory,next(os.walk('.'))[1]
Applying uppercase to a column in pandas dataframe,"df['1/2 ID'].apply(lambda x: x.upper(), inplace=True)"
How do I run multiple Python test cases in a loop?,unittest.main()
How to make two markers share the same label in the legend using matplotlib?,plt.show()
Remove strings from a list that contains numbers in python,my_list = [item for item in my_list if item.isalpha()]
Scale image in matplotlib without changing the axis,plt.show()
How can I count the occurrences of an item in a list of dictionaries?,sum(1 for d in my_list if d.get('id') == 20)
Matplotlib custom marker/symbol,plt.show()
Find out how many times a regex matches in a string in Python,"len(re.findall(pattern, string_to_search))"
How do I use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*$', 'A')"
Python/Matplotlib - Is there a way to make a discontinuous axis?,ax2.spines['left'].set_visible(False)
Python: Converting from binary to String,"struct.pack('>I', 1633837924)"
How to deal with certificates using Selenium?,driver.close()
concatenate an arbitrary number of lists in a function in Python,"join_lists([1, 2, 3], [4, 5, 6])"
How Do I Use A Decimal Number In A Django URL Pattern?,"""""""^/item/value/(\\d+\\.\\d+)$"""""""
"Image embossing in Python with PIL -- adding depth, azimuth, etc","ImageFilter.EMBOSS.filterargs = (3, 3), 1, 128, (-1, 0, 0, 0, 1, 0, 0, 0, 0)"
How do I insert a list at the front of another list?,a[0:0] = k
string.lower in Python 3,"""""""FOo"""""".lower()"
How do I change the axis tick font in a matplotlib plot when rendering using Latex?,"rc('text.latex', preamble='\\usepackage{cmbright}')"
How to update DjangoItem in Scrapy,ITEM_PIPELINES = {'apps.scrapy.pipelines.ItemPersistencePipeline': 999}
Comparing values in a Python dict of lists,"{k: [lookup[n] for n in v] for k, v in list(my_dict.items())}"
Append 2 dimensional arrays to one single array,"array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])"
How to normalize by another row in a pandas DataFrame?,"df.loc[:, (cols)] / df.loc[ii, cols].values"
Return a tuple of arguments to be fed to string.format(),"print('Two pair, {0}s and {1}s'.format(*cards))"
Static html Files in Cherrypy,raise cherrypy.HTTPRedirect('/device')
Element-wise minimum of multiple vectors in numpy,"np.amin(V, axis=0)"
How to get the size of a string in Python?,print(len('please anwser my question'))
"Extract file name from path, no matter what the os/path format",print(os.path.basename(your_path))
Adding a string to a list,b.append(c)
Python equivalent of piping zcat result to filehandle in Perl,"zcat = subprocess.Popen(['zcat', path], stdout=subprocess.PIPE)"
shuffle string in python,""""""""""""".join(random.sample(s, len(s)))"
Removing JSON property in array of objects with Python,[item for item in data if not item['imageData']]
How do I split an ndarray based on array of indexes?,"array([[0, 1], [2, 3], [6, 7], [8, 9], [10, 11]])"
How to set same color for markers and lines in a matplotlib plot loop?,plt.savefig('test2.png')
Print the concatenation of the digits of two numbers in Python,"print('{0}{1}'.format(2, 1))"
Hashing (hiding) strings in Python,hash('moo')
How can I assign a new class attribute via __dict__ in python?,"setattr(test, attr_name, 10)"
Correct code to remove the vowels from a string in Python,""""""""""""".join([l for l in c if l not in vowels])"
Python: split on either a space or a hyphen?,"re.split('[\\s-]+', text)"
How do you convert a python time.struct_time object into a ISO string?,"time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)"
Opposite of melt in python pandas,"origin.groupby(['label', 'type'])['value'].aggregate('mean').unstack()"
Playing a Lot of Sounds at Once,pg.mixer.init()
Sort a sublist of elements in a list leaving the rest in place,"['X', 'B', 'B1', 'B2', 'B11', 'B21', 'B22', 'C', 'Q1', 'C11', 'C2']"
Sort a sublist of elements in a list leaving the rest in place,"['X', 'B', 'B1', 'B11', 'B2', 'B22', 'C', 'Q1', 'C11', 'C2', 'B21']"