text stringlengths 4 1.08k |
|---|
Python: converting radians to degrees,math.cos(math.radians(1)) |
Python - arranging words in alphabetical order,sentence = [word.lower() for word in sentence] |
How to parse dates with -0400 timezone string in python?,"datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z')" |
Different levels of logging in python,logger.setLevel(logging.DEBUG) |
Convert List to a list of tuples python,"zip(it, it, it)" |
String manipulation in Cython,"re.sub(' +', ' ', s)" |
Insert 0s into 2d array,"array([[-1, -2, -1, 2], [0, -1, 0, 3], [1, 0, 1, 4]])" |
Build Dictionary in Python Loop - List and Dictionary Comprehensions,{_key: _value(_key) for _key in _container} |
Efficient way to create strings from a list,"list(product(['Long', 'Med'], ['Yes', 'No']))" |
Pandas/Python: How to concatenate two dataframes without duplicates?,"pandas.concat([df1, df2]).drop_duplicates().reset_index(drop=True)" |
Find max overlap in list of lists,return [list(x) for x in list(results.values())] |
How to show the whole image when using OpenCV warpPerspective,cv2.waitKey() |
How to parse DST date in Python?,"sorted(d['11163722404385'], key=lambda x: x[-1].date())" |
How can I do multiple substitutions using regex in python?,"re.sub('(.)', '\\1\\1', text.read(), 0, re.S)" |
How to decode a 'url-encoded' string in python,urllib.parse.unquote(urllib.parse.unquote(some_string)) |
Python converting a tuple (of strings) of unknown length into a list of strings,"['text', 'othertext', 'moretext', 'yetmoretext']" |
How do I get a list of all the duplicate items using pandas in python?,"pd.concat(g for _, g in df.groupby('ID') if len(g) > 1)" |
Unpack NumPy array by column,"x = np.arange(15).reshape(5, 3)" |
Getting the row index for a 2D numPy array when multiple column values are known,np.where((a[0] == 2) & (a[1] == 5)) |
convert dictionaries into string python,""""""", """""".join([(str(k) + ' ' + str(v)) for k, v in list(a.items())])" |
Can I use an alias to execute a program from a python script,os.system('source .bashrc; shopt -s expand_aliases; nuke -x scriptPath') |
Python - best way to set a column in a 2d array to a specific value,"data = [[0, 0], [0, 0], [0, 0]]" |
Matplotlib.animation: how to remove white margin,"fig.set_size_inches(w, h, forward=True)" |
How can I check if a string contains ANY letters from the alphabet?,"re.search('[a-zA-Z]', the_string)" |
In pandas Dataframe with multiindex how can I filter by order?,"df.groupby(level=0, as_index=False).nth(0)" |
Add tuple to a list of tuples,"[(10, 21, 32), (13, 24, 35), (16, 27, 38)]" |
How to pass a list as an input of a function in Python,"print(square([1, 2, 3]))" |
Print the complete string of a pandas dataframe,"df.iloc[2, 0]" |
How do I select a random element from an array in Python?,"random.choice([1, 2, 3])" |
Layout images in form of a number,"img.save('/tmp/out.png', 'PNG')" |
Add element to a json in python,data[0]['f'] = var |
Format time string in Python 3.3,time.strftime('{%Y-%m-%d %H:%M:%S}') |
Remove duplicate chars using regex?,"re.sub('([a-z])\\1+', '\\1', 'ffffffbbbbbbbqqq')" |
Python: find index of first digit in string?,"{c: i for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()}" |
Python using custom color in plot,"ax.plot(x, mpt1, color='dbz53', label='53 dBz')" |
passing variables from python to bash shell script via os.system,os.system('echo $probe1') |
Python Embedding in C++ : ImportError: No module named pyfunction,"sys.path.insert(0, './path/to/your/modules/')" |
Slicing a list in Django template,{{(mylist | slice): '3:8'}} |
Connecting a slot to a button in QDialogButtonBox,self.buttonBox.button(QtGui.QDialogButtonBox.Reset).clicked.connect(foo) |
Pandas reset index on series to remove multiindex,s.reset_index(0).reset_index(drop=True) |
How would I use django.forms to prepopulate a choice field with rows from a model?,user2 = forms.ModelChoiceField(queryset=User.objects.all()) |
Python: changing IDLE's path in WIN7,sys.path.append('.') |
How to disable query cache with mysql.connector,con.commit() |
converting integer to list in python,list(str(123)) |
How to create matplotlib colormap that treats one value specially?,plt.show() |
pandas HDFStore - how to reopen?,"df1 = pd.read_hdf('/home/.../data.h5', 'firstSet')" |
how to set global const variables in python,GRAVITY = 9.8 |
How to invoke a specific Python version WITHIN a script.py -- Windows,print('World') |
Is there a more pythonic way of exploding a list over a function's arguments?,foo(*i) |
How can a pandas merge preserve order?,"x.merge(x.merge(y, how='left', on='state', sort=False))" |
How to use Selenium with Python?,from selenium import webdriver |
Setting the limits on a colorbar in matplotlib,plt.show() |
How to remove 0's converting pandas dataframe to record,df.to_sparse(0) |
"Flask, blue_print, current_app",app.run(debug=True) |
How would I sum a multi-dimensional array in the most succinct python?,"sum([sum(x) for x in [[1, 2, 3, 4], [2, 4, 5, 6]]])" |
SymPy : creating a numpy function from diagonal matrix that takes a numpy array,"Matrix([[32.4, 32.4, 32.4], [32.8, 32.8, 32.8], [33.2, 33.2, 33.2]])" |
Python - NumPy - deleting multiple rows and columns from an array,"np.count_nonzero(a[np.ix_([0, 3], [0, 3])])" |
how to pass argparse arguments to a class,args = parser.parse_args() |
How do I convert a string 2 bytes long to an integer in python,"struct.unpack('h', pS[0:2])" |
Summarizing dataframe into a dictionary,df.groupby('date')['level'].first().apply(np.ceil).to_dict() |
How can I find the IP address of a host using mdns?,"sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)" |
Python - how to sort a list of numerical values in ascending order,"sorted(['10', '3', '2'], key=int)" |
How can I insert data into a MySQL database?,db.close() |
Using BeautifulSoup to search html for string,soup.body.findAll(text='Python') |
Possible to get user input without inserting a new line?,"print('Hello, {0}, how do you do?'.format(input('Enter name here: ')))" |
Route to worker depending on result in Celery?,"my_task.apply_async(exchange='C.dq', routing_key=host)" |
Using anchors in python regex to get exact match,"""""""^v\\d+$""""""" |
Remove the first word in a Python string?,"s.split(' ', 1)[1]" |
How to implement jump in Pygame without sprites?,pygame.display.flip() |
Find the indices of elements greater than x,"[i for i, v in enumerate(a) if v > 4]" |
How do I remove the background from this kind of image?,cv2.waitKey() |
in python how do I convert a single digit number into a double digits string?,print('{0}'.format('5'.zfill(2))) |
How to convert decimal to binary list in python,list('{0:0b}'.format(8)) |
Find the indices of elements greater than x,"[(i, j) for i, j in zip(a, x)]" |
plotting 3d scatter in matplotlib,plt.show() |
Sorting files in a list,files.sort(key=file_number) |
Fastest way to remove first and last lines from a Python string,s[s.find('\n') + 1:s.rfind('\n')] |
Formatting text to be justified in Python 3.3 with .format() method,"""""""{:>7s}"""""".format(mystring)" |
How to sort a dictionary having keys as a string of numbers in Python,"sortedlist = [(k, a[k]) for k in sorted(a)]" |
How to remove square bracket from pandas dataframe,df['value'] = df['value'].str[0] |
Python Pandas How to select rows with one or more nulls from a DataFrame without listing columns explicitly?,df[pd.isnull(df).any(axis=1)] |
Can I export a Python Pandas dataframe to MS SQL?,conn.commit() |
List of all unique characters in a string?,""""""""""""".join(list(OrderedDict.fromkeys('aaabcabccd').keys()))" |
How to get column by number in Pandas?,"df.loc[:, ('b')]" |
Removing backslashes from a string in Python,"result = result.replace('\\', '')" |
How can I convert literal escape sequences in a string to the corresponding bytes?,"""""""\\xc3\\x85あ"""""".encode('utf-8').decode('unicode_escape')" |
Download a remote image and save it to a Django model,request.FILES['imgfield'] |
Creating a list of dictionaries in python,"all_examples = ['A,1,1,1', 'B,2,1,2', 'C,4,4,3', 'D,4,5,6']" |
Progress Line in Matplotlib Graphs,plt.show() |
"Concatenating Unicode with string: print '£' + '1' works, but print '£' + u'1' throws UnicodeDecodeError",print('\xc2\xa3'.decode('utf8') + '1') |
How can I get an array of alternating values in python?,a[1::2] = -1 |
How to mount and unmount on windows,os.system('mount /dev/dvdrom /mount-point') |
How to strip comma in Python string,"s = s.replace(',', '')" |
python pexpect sendcontrol key characters,id.sendline('') |
Sum one number to every element in a list (or array) in Python,"[3, 3, 3, 3, 3]" |
Find string with regular expression in python,print(pattern.search(url).group(1)) |
wxPython: How to make a TextCtrl fill a Panel,self.SetSizerAndFit(bsizer) |
How to sort in decreasing value first then increasing in second value,"print(sorted(student_tuples, key=lambda t: (-t[2], t[0])))" |
how do you filter pandas dataframes by multiple columns,males = df[(df[Gender] == 'Male') & (df[Year] == 2014)] |
Replacing few values in a pandas dataframe column with another value,"df['BrandName'].replace(['ABC', 'AB'], 'A')" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.