text
stringlengths 4
1.08k
|
|---|
Python Regex to find a string in double quotes within a string,"""""""String 1,String 2,String3"""""""
|
How to swap a group of column headings with their values in Pandas,"df = df.assign(a5=['Foo', 'Bar', 'Baz'])"
|
Greedy match with negative lookahead in a regular expression,"re.findall('[a-zA-Z]+\\b(?!\\()', 'movav(x/2, 2)*movsum(y, 3)*z')"
|
How to plot data against specific dates on the x-axis using matplotlib,plt.show()
|
How do convert unicode escape sequences to unicode characters in a python string,name.decode('latin-1')
|
Elegantly changing the color of a plot frame in matplotlib,"plt.setp([ax.get_xticklines(), ax.get_yticklines()], color=color)"
|
How to merge two Python dictionaries in a single expression?,"z = merge_two_dicts(x, y)"
|
python: read lines from compressed text files,gzip.open('myfile.gz')
|
"Python, how to pass an argument to a function pointer parameter?",f(*args)
|
How can I add an additional row and column to an array?,"L = [[1, 2, 3], [4, 5, 6]]"
|
How can I do a batch insert into an Oracle database using Python?,cursor.close()
|
Python Finding Index of Maximum in List,a.index(max(a))
|
Python subprocess in parallel,p.wait()
|
Convert binary data to signed integer,"struct.unpack('!h', p0 + p1)[0]"
|
How to make print statement one line in python?,"print('If a hippo ways 2000 pounds, gives birth to a 100 pound calf and ' + 'then eats a 50 pound meal how much does she weigh?')"
|
How do I stack vectors of different lengths in NumPy?,"ma.vstack([a, ma.array(np.resize(b, a.shape[0]), mask=[False, False, True])])"
|
Python: sorting items in a dictionary by a part of a key?,"[('Mary XXIV', 24), ('Robert III', 3)]"
|
Django REST framework: Basic Auth without debug,ALLOWED_HOSTS = ['*']
|
Python serial communication,s.write(str(25) + '\n')
|
Concatenate elements of a tuple in a list in python,new_data = (' '.join(w) for w in sixgrams)
|
Python: How to import other Python files,__init__.py
|
How to improve the performance of this Python code?,"G[i, j] = C_abs[i, j] + C_abs[j, i]"
|
Pandas: how to get the unique values of a column that contains a list of values?,"pd.merge(df, uniq_df, on='col', how='left')"
|
How to round a number to significant figures in Python,"round(1234, -3)"
|
Creating a relative symlink in python without using os.chdir(),"os.symlink('file.ext', '/path/to/some/directory/symlink')"
|
How to change end-of-line conventions?,"df.to_csv('filename.txt', sep='\t', mode='wb', encoding='utf8')"
|
Joining a list that has Integer values with Python,""""""", """""".join(map(str, myList))"
|
How to convert numpy datetime64 into datetime,"np.array([[x, x], [x, x]], dtype='M8[ms]').astype('O')[0, 1]"
|
Generate random UTF-8 string in Python,return ''.join(random.choice(alphabet) for i in range(length))
|
How to hide output of subprocess in Python 2.7,"retcode = os.system(""echo 'foo' &> /dev/null"")"
|
Is there a way to set all values of a dictionary to zero?,{x: (0) for x in string.printable}
|
How to compare dates in Django,return {'date_now': datetime.datetime.now()}
|
Django - Get only date from datetime.strptime,"datetime.strptime('2014-12-04', '%Y-%m-%d').date()"
|
Possible to capture the returned value from a Python list comprehension for use a condition?,[expensive_function(x) for x in range(5) if expensive_function(x) % 2 == 0]
|
Split a string and add into `tuple`,"tuple(s[i:i + 2] for i in range(0, len(s), 2))"
|
Python: One-liner to perform an operation upon elements in a 2d array (list of lists)?,"[map(int, x) for x in values]"
|
How can I slice each element of a numpy array of strings?,"a.view('U1').reshape(4, -1)[:, 1:3]"
|
How to replace HTML comments with custom <comment> elements,"re.sub('(<!--)|(<!--)', '<comment>', child.text, flags=re.MULTILINE)"
|
Python numpy: cannot convert datetime64[ns] to datetime64[D] (to use with Numba),df['month_15'].astype('datetime64[D]').tolist()
|
How to convert from infix to postfix/prefix using AST python module?,"['sin', '*', 'w', 'time']"
|
One hour difference in Python,var < datetime.datetime.today() - datetime.timedelta(hours=1)
|
How to convert a pandas DataFrame subset of columns AND rows into a numpy array?,"df[df['c'] > 0.5][['b', 'e']].values"
|
split list by condition in python,"aList, bList = [[x for x in a if x[0] == i] for i in (0, 1)]"
|
Print a string as hex bytes?,""""""":"""""".join(x.encode('hex') for x in 'Hello World!')"
|
multiprocessing.Pool with a global variable,"pool = Pool(4, initializer, ())"
|
Two subplots in Python (matplotlib),df['STD'].plot(ax=axarr[1])
|
Efficient way to convert a list to dictionary,dict(x.split(':') for x in lis)
|
"how to insert to a mysql table using mysaldb, where the table name is in a python variable?",'%%s %s' % 'x'
|
How do I format axis number format to thousands with a comma in matplotlib?,"""""""{:,}"""""".format(10000.21)"
|
How do I make a pop up in Tkinter when a button is clicked?,app.mainloop()
|
"Python Selenium Safari, disable logging",browser = webdriver.Safari()
|
How do you round UP a number in Python?,print(math.ceil(4.2))
|
Sending JSON request with Python,"r = requests.get('http://myserver/emoncms2/api/post', data=payload)"
|
how to set rmse cost function in tensorflow,"tf.sqrt(tf.reduce_mean(tf.square(tf.sub(targets, outputs))))"
|
How to format print output into fixed width?,"""""""{0: >5}"""""".format('ss')"
|
Django CSRF check failing with an Ajax POST request,"request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')"
|
Open document with default application in Python,os.system('open ' + filename)
|
Python - how to sort a list of numerical values in ascending order,"sorted([10, 3, 2])"
|
python - iterating over a subset of a list of tuples,"ones = [(x, y) for x, y in l if y == 1]"
|
Python string interpolation with tuple slices?,"'Dealer has %s showing.' % (self.dealer[0], self.dealer[1])"
|
Pygtk color for drag_highlight,gtk.main()
|
Appending the same string to a list of strings in Python,[(s + mystring) for s in mylist]
|
Python Serial: How to use the read or readline function to read more than 1 character at a time,ser.readline()
|
Is there a random letter generator with a range?,"random.choice(['A', 'B', 'C', 'D'])"
|
"python, lxml and xpath - html table parsing",return [process_row(row) for row in table.xpath('./tr')]
|
Python: how to calculate the sum of a list without creating the whole list first?,"result = sum(x for x in range(1, 401, 4))"
|
Python: How to check if keys exists and retrieve value from Dictionary in descending priority,"value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName')))"
|
How do I include unicode strings in Python doctests?,doctest.testmod()
|
python float to in int conversion,int(float('20.0'))
|
How to change file access permissions in linux?,"os.chmod(path, mode)"
|
Calculate delta from values in dataframe,"df.pivot(index='client_id', columns='month', values='deltas')"
|
How to calculate the percentage of each element in a list?,"[[0.4, 0.6, 0.0, 0.0], [0.2, 0.4, 0.4, 0.0], [0.0, 0.0, 0.4, 0.6]]"
|
How to do Pearson correlation of selected columns of a Pandas data frame,"df.corr().iloc[:-1, (-1)]"
|
List of zeros in python,[0] * 4
|
Pandas Series to Excel,"s.to_frame(name='column_name').to_excel('xlfile.xlsx', sheet_name='s')"
|
Categorize list in Python,"list([x for x in totalist if x[:2] == ['A', 'B']])"
|
String replace python,"newString = re.sub('\\boldword\\b', 'newword', oldString)"
|
how to sort a tuple with lambda,"sorted(l, key=lambda i: hypot(i[0] - pt[0], i[1] - pt[1]))"
|
How to implement simple sessions for Google App Engine?,session = Session.get_by_id(sid)
|
Unicode values in strings are escaped when dumping to JSON in Python,"print(json.dumps('r\xc5\xaf\xc5\xbee', ensure_ascii=False))"
|
How can I add a comment to a YAML file in Python,f.write('# Data for Class A\n')
|
Python regex returns a part of the match when used with re.findall,"""""""\\$\\d+(?:\\.\\d{2})?"""""""
|
Replace the single quote (') character from a string,"""""""A single ' char"""""".replace(""'"", '')"
|
Limit the number of sentences in a string,""""""" """""".join(re.split('(?<=[.?!])\\s+', phrase, 2)[:-1])"
|
how to remove u from sqlite3 cursor.fetchall() in python,ar = [r[0] for r in cur.fetchall()]
|
Find the newest folder in a directory in Python,all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]
|
Using a Python Dictionary as a Key (Non-nested),frozenset(list(a.items()))
|
python base64 string decoding,base64.b64decode('AME=').decode('UTF-16BE')
|
How to get pandas.read_csv() to infer datetime and timedelta types from CSV file columns?,"df = pd.read_csv('c:\\temp1.txt', parse_dates=[0], infer_datetime_format=True)"
|
Accessing function arguments from decorator,MyClass().say('hello')
|
build a DataFrame with columns from tuple of arrays,"pd.DataFrame(np.vstack(someTuple).T, columns=['birdType', 'birdCount'])"
|
Python JSON encoding,"{'apple': 'cat', 'banana': 'dog'}"
|
pop/remove items out of a python tuple,tupleX = [x for x in tupleX if x > 5]
|
How to calculate cumulative normal distribution in Python,norm.ppf(norm.cdf(1.96))
|
Confusing with the usage of regex in Python,"re.findall('[a-z]*', '123abc789')"
|
Confusing with the usage of regex in Python,"re.findall('[a-z]*', '123456789')"
|
Draw lines from x axis to points,plt.show()
|
Read an xml file in Python,root = tree.getroot()
|
Run Rsync from Python,"subprocess.call(['ls', '-l'])"
|
How to transform a pair of values into a sorted unique array?,sorted(set().union(*input_list))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.