text
stringlengths 4
1.08k
|
|---|
Equivalent of Bash Backticks in Python,output = os.popen('cat /tmp/baz').read()
|
How to get the size of a string in Python?,len(s)
|
Replace single instances of a character that is sometimes doubled,"s.replace('||', '|||')[::2]"
|
how to print dataframe without index,print(df.to_string(index=False))
|
more pythonic way to format a JSON string from a list of tuples,"(lambda lst: json.dumps({item[0]: item[1] for item in lst}))([(1, 2), (3, 4)])"
|
Can you plot live data in matplotlib?,plt.draw()
|
How to iterate over DataFrame and generate a new DataFrame,"df2 = df[~pd.isnull(df.L)].loc[:, (['P', 'L'])].set_index('P')"
|
Matplotlib 3D Scatter Plot with Colorbar,"ax.scatter(xs, ys, zs, c=cs, marker=m)"
|
python: sort a list of lists by an item in the sublist,"sorted(a, key=lambda x: x[1], reverse=True)"
|
How to achieve two separate list of lists from a single list of lists of tuple with list comprehension?,"[y for sublist in l for x, y in sublist]"
|
How to print a file to paper in Python 3 on windows XP/7?,"subprocess.call(['notepad', '/p', filename])"
|
remove None value from a list without removing the 0 value,[x for x in L if x is not None]
|
Defining the midpoint of a colormap in matplotlib,plt.show()
|
Create a Pandas DataFrame from deeply nested JSON,res.drop_duplicates()
|
Change string list to list,"ast.literal_eval('[1,2,3]')"
|
How can I get the product of all elements in a one dimensional numpy array,numpy.prod(a)
|
How to re.sub() a optional matching group using regex in Python?,"re.sub('url(#*.*)', 'url\\1', test1)"
|
Is there a way to disable built-in deadlines on App Engine dev_appserver?,urlfetch.set_default_fetch_deadline(60)
|
Convert Year/Month/Day to Day of Year in Python,day_of_year = datetime.now().timetuple().tm_yday
|
How do I remove a node in xml using ElementTree in Python?,tree.remove(tree.findall('.//B')[1])
|
mysql Compress() with sqlalchemy,session.commit()
|
Python: insert 2D array into MySQL table,db.commit()
|
How can I set the mouse position in a tkinter window,"win32api.SetCursorPos((50, 50))"
|
Python: Split string with multiple delimiters,"re.split('; |, |\\*|\n', a)"
|
How to print more than one value in a list comprehension?,"output = [[word, len(word), word.upper()] for word in sent]"
|
How can I get part of regex match as a variable in python?,p.match('lalalaI want this partlalala').group(1)
|
How to use a dot in Python format strings?,"""""""Hello {user[name]}"""""".format(**{'user': {'name': 'Markus'}})"
|
How can you group a very specfic pattern with regex?,rgx = re.compile('(?<!\\+)[a-zA-Z]|[a-zA-Z](?!\\+)')
|
How do I find the distance between two points?,dist = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
|
Using savepoints in python sqlite3,"conn.execute('create table example (A, B);')"
|
Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?,"df.loc[0, 'C'] = df.loc[0, 'D']"
|
Matrix multiplication in pandas,"np.dot(x, y)"
|
Removing items from a nested list Python,[[j for j in families[i] if i != j] for i in range(len(families))]
|
How to remove leading and trailing spaces from strings in a Python list,row = [x.strip() for x in row]
|
Printing list elements on separated lines in Python,print('\n'.join(sys.path))
|
Convert list of tuples to list?,[i[0] for i in e]
|
How do I execute a program from python? os.system fails due to spaces in path,"os.system('""C://Temp/a b c/Notepad.exe""')"
|
Check if a list has one or more strings that match a regex,"[re.search('\\d', s) for s in lst]"
|
Is there a simple way to change a column of yes/no to 1/0 in a Pandas dataframe?,"pd.Series(np.where(sample.housing.values == 'yes', 1, 0), sample.index)"
|
How to crop zero edges of a numpy array?,"array([[1, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 0]])"
|
Delete final line in file with python,file.close()
|
I want to create a column of value_counts in my pandas dataframe,df['Counts'] = df.groupby(['Color'])['Value'].transform('count')
|
Web scraping with Python,print(soup.prettify())
|
Is there a way to copy only the structure (not the data) of a Pandas DataFrame?,"df2 = pd.DataFrame(data=None, columns=df1.columns, index=df1.index)"
|
GradientBoostingClassifier with a BaseEstimator in scikit-learn?,"self.est.fit(X, y)"
|
Efficiently finding the last line in a text file,"line = subprocess.check_output(['tail', '-1', filename])"
|
"Difference between using commas, concatenation, and string formatters in Python","print('I am printing {x} and {y}'.format(x=x, y=y))"
|
How can I clear the Python pdb screen?,os.system('clear')
|
How to write a lambda function that is conditional on two variables (columns) in python,"df['dummyVar '] = df['x'].where((df['x'] > 100) & (df['y'] < 50), df['y'])"
|
More elegant way to create a 2D matrix in Python,a = [[(0) for y in range(8)] for x in range(8)]
|
Append element to a list inside nested list - python,"[['google', ['http://google.com']], ['computing', ['http://acm.org']]]"
|
"Distance between numpy arrays, columnwise","numpy.apply_along_axis(numpy.linalg.norm, 1, dist)"
|
Python lists with scandinavic letters,"['Hello', 'world']"
|
How to deal with unstable data received from RFID reader?,cache.get('data')
|
Is there a portable way to get the current username in Python?,getpass.getuser()
|
Convert sets to frozensets as values of a dictionary,"d.update((k, frozenset(v)) for k, v in d.items())"
|
Matplotlib: no effect of set_data in imshow for the plot,plt.show()
|
How can I find all subclasses of a class given its name?,print([cls.__name__ for cls in vars()['Foo'].__subclasses__()])
|
Union of dict objects in Python,"dict({'a': 'y[a]'}, **{'a', 'x[a]'}) == {'a': 'x[a]'}"
|
Fetching most recent related object for set of objects in Peewee,q = B.select().join(A).group_by(A).having(fn.Max(B.date) == B.date)
|
Python - Removing vertical bar lines from histogram,plt.show()
|
How to make a numpy array from an array of arrays?,np.vstack(a)
|
reverse mapping of dictionary with Python,"dict(map(lambda a: [a[1], a[0]], iter(d.items())))"
|
"graphing multiple types of plots (line, scatter, bar etc) in the same window",plt.show()
|
Removing nan values from a Python List,cleanlist = [(0.0 if math.isnan(x) else x) for x in oldlist]
|
python: read json and loop dictionary,output_json = json.load(open('/tmp/output.json'))
|
How to assign equal scaling on the x-axis in Matplotlib?,"[0, 1, 2, 2, 3, 4, 5, 5, 5, 6]"
|
Efficient way to extract text from between tags,"re.findall('(?<=>)([^<]+)(?=</a>[^<]*</li)', var, re.S)"
|
Capitalizing non-ASCII words in Python,print('\xe9'.capitalize())
|
Delete a key and value from an OrderedDict,del dct[key]
|
Shade 'cells' in polar plot with matplotlib,plt.show()
|
Get the address of a ctypes object,ctypes.addressof(bufstr)
|
How do I create a web interface to a simple python script?,app.run()
|
"How do I sort a list with ""Nones last""","groups = sorted(groups, key=lambda a: (a['name'] is None, a['name']))"
|
Efficiently change a key of a Python dict,"a_send = dict((k[0], v) for k, v in list(a.items()))"
|
matplotlib chart - creating horizontal bar chart,plt.show()
|
How to close a Tkinter window by pressing a Button?,"button = Button(frame, text='Good-bye.', command=window.destroy)"
|
How to download file from ftp?,"ftp.retrbinary('RETR README', open('README', 'wb').write)"
|
How to sort OrderedDict of OrderedDict - Python,"OrderedDict(sorted(list(od.items()), key=lambda item: item[1]['depth']))"
|
Convert Variable Name to String?,get_indentifier_name_missing_function()
|
How do you concatenate two differently named columns together in pandas?,"pd.lreshape(df, {'D': ['B', 'C']})"
|
"For each row, what is the fastest way to find the column holding nth element that is not NaN?",(df.notnull().cumsum(axis=1) == 4).idxmax(axis=1)
|
Turning tuples into a pairwise string,""""""", """""".join('%s(%.02f)' % (x, y) for x, y in tuplelist)"
|
How to render a doctype with Python's xml.dom.minidom?,print(doc.toxml())
|
count each element in list without .count,"Counter(['a', 'b', 'a', 'c', 'b', 'a', 'c'])"
|
Reading data from a CSV file online in Python 3,datareader = csv.reader(webpage.read().decode('utf-8').splitlines())
|
Python float to Decimal conversion,"format(f, '.15g')"
|
How do I limit the border size on a matplotlib graph?,ax.set_title('Title')
|
Pythonic way to append list of strings to an array,entry_list.extend([entry.title.text for entry in feed.entry])
|
How to switch two elements in string using Python RegEx?,"pattern.sub('A*\\3\\2\\1*', s)"
|
Cut within a pattern using Python regex,"re.split('(?<=CDE)(\\w+)(?=FG)', s)"
|
stack bar plot in matplotlib and add label to each section (and suggestions),plt.show()
|
Get browser version using selenium webdriver,print(driver.capabilities['version'])
|
python filter list of dictionaries based on key value,list([d for d in exampleSet if d['type'] in keyValList])
|
Set legend symbol opacity with matplotlib?,plt.legend()
|
How can I use a pseudoterminal in python to emulate a serial port?,time.sleep(3)
|
Maintain strings when converting python list into numpy structured array,"numpy.array(data, dtype=[('label', str), ('x', float), ('y', float)])"
|
Flask instanciation app = Flask(),app = Flask(__name__)
|
Delete Column in Pandas based on Condition,"df = df.loc[:, ((df != 0).any(axis=0))]"
|
What is the most pythonic way to avoid specifying the same value in a string,"""""""hello {0}, how are you {0}, welcome {0}"""""".format('john')"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.