text stringlengths 4 1.08k |
|---|
How to remove \n from a list element?,"map(lambda x: x.strip(), l)" |
how do I insert a column at a specific column index in pandas?,"df.insert(idx, col_name, value)" |
Function changes list values and not variable values in Python,return [(x + 1) for x in y] |
Doing math to a list in python,"[(3 * x) for x in [111, 222, 333]]" |
"defaultdict of defaultdict, nested",defaultdict(lambda : defaultdict(dict)) |
Scatter plot and Color mapping in Python,"plt.scatter(x, y, c=t, cmap='jet')" |
Pandas Convert 'NA' to NaN,pd.read_csv('test') |
"Pre-Populate a WTforms in flask, with data from a SQLAlchemy object",db.session.add(query) |
Calculate within categories: Equivalent of R's ddply in Python?,df.groupby('d').apply(f) |
Getting the first item item in a many-to-many relation in Django,Group.objects.get(id=1).members.filter(is_main_user=True)[0] |
is there a simple to get group names of a user in django,"l = request.user.groups.values_list('name', flat=True)" |
Django Haystack - How to filter search results by a boolean field?,sqs.filter(has_been_sent=True) |
How to hide ticks label in python but keep the ticks in place?,plt.show() |
python - regex search and findall,"regex = re.compile('\\d+(?:,\\d+)*')" |
Pandas changing cell values based on another cell,b = df[(df['time'] > X) & (df['time'] < Y)] |
Matplotlib: -- how to show all digits on ticks?,plt.show() |
Get webpage contents with Python?,urllib.request.urlopen('http://www.python.org/') |
How do I generate dynamic fields in WTForms,"return render_template('recipes/createRecipe.html', form=form)" |
How can I make this timer run forever?,time.sleep(30.0) |
Add a column with a groupby on a hierarchical dataframe,"rdf.unstack(['First', 'Third'])" |
Using Django auth User model as a Foreignkey and reverse relations,Post.objects.filter(user=request.user).order_by('-timestamp') |
python pandas dataframe slicing by date conditions,df.sort_index() |
Making a list of evenly spaced numbers in a certain range in python,"np.linspace(0, 5, 10)" |
Matplotlib: Formatting dates on the x-axis in a 3D Bar graph,ax.set_zlabel('Amount') |
Update json file,json_file.write('{}\n'.format(json.dumps(new_data))) |
Numpy: cartesian product of x and y array points into single array of 2D points,"numpy.transpose([numpy.tile(x, len(y)), numpy.repeat(y, len(x))])" |
How do I sort a list of strings in Python?,"mylist = ['b', 'C', 'A'] |
mylist.sort()" |
NumPy - Efficient conversion from tuple to array?,"np.array(x).reshape(2, 2, 4)" |
'PipelinedRDD' object has no attribute 'toDF' in PySpark,rdd.toDF().show() |
Search for the last occurence in multiple columns in a dataframe,df.stack(level=0).groupby('team').tail(1) |
Case Insensitive Python string split() method,regex = re.compile('\\s*[Ff]eat\\.\\s*') |
How to run sudo with paramiko? (Python),"ssh.connect('127.0.0.1', username='jesse', password='lol')" |
Remove default apps from Django-admin,admin.site.unregister(Site) |
How would one add a colorbar to this example?,"plt.figure(figsize=(5, 6))" |
How to append rows in a pandas dataframe in a for loop?,print('{}\n'.format(df)) |
Creating a dictionary from an iterable,"{i: (0) for i in range(0, 10)}" |
Removing data between double squiggly brackets with nested sub brackets in python,"re.sub('\\{\\{.*\\}\\} ', '', s)" |
"In python, how do I take the highest occurrence of something in a list, and sort it that way?","print(Counter([3, 3, 3, 4, 4, 2]).most_common())" |
Python: String formatting a regex string that uses both '%' and '{' as characters,"""""""([0-9]{{1,3}}[%])([{0}]?)"""""".format(config.SERIES)" |
How to run a python script from IDLE interactive shell?,"subprocess.call(['python', 'helloworld.py'])" |
Can I run a Python script as a service?,os.setsid() |
Flask application traceback doesn't show up in server log,app.debug = true |
Splitting a string into 2-letter segments,"re.findall('.{1,2}', s, re.DOTALL)" |
Matplotlib plot pulse propagation in 3d,"drawPropagation(1.0, 1.0, numpy.linspace(-2, 2, 10))" |
How to run a function/thread in a different terminal window in python?,proc.wait() |
Create NTFS junction point in Python,"kdll.CreateSymbolicLinkA('d:\testdir', 'd:\testdir_link', 1)" |
Deleting mulitple columns in Pandas,"df.drop(df.ix[:, 'Unnamed: 24':'Unnamed: 60'].head(0).columns, axis=1)" |
understanding list comprehension for flattening list of lists in python,[item for sublist in (list_of_lists for item in sublist)] |
Django models - how to filter number of ForeignKey objects,[a for a in A.objects.all() if a.b_set.count() < 2] |
How to change attributes of a networkx / matplotlib graph drawing?,plt.show() |
Python dryscrape scrape page with cookies,session.visit('<url to visit with proper cookies>') |
How to merge two Python dictionaries in a single expression?,"z = merge_dicts(a, b, c, d, e, f, g)" |
Python: Pandas Dataframe how to multiply entire column with a scalar,df['quantity'] = df['quantity'].apply(lambda x: x * -1) |
How to set different levels for different python log handlers,logging.basicConfig(level=logging.DEBUG) |
Moving x-axis to the top of a plot in matplotlib,ax.set_xlabel('X LABEL') |
How to convert a string representing a binary fraction to a number in Python,"return int(s[1:], 2) / 2.0 ** (len(s) - 1)" |
Split filenames with python,os.path.splitext(os.path.basename(f)) |
First parameter of os.exec*,"os.execv('/bin/echo', ['echo', 'foo', 'bar'])" |
Python implementation of Jenkins Hash?,"print('""%s"": %x' % (hashstr, hash))" |
How to search a list of tuples in Python,[x[0] for x in a] |
How to check a string for specific characters?,"any(i in '<string>' for i in ('11', '22', '33'))" |
How to retrieve only arabic texts from a string using regular expression?,"print(re.sub('[a-zA-Z?]', '', my_string).strip())" |
Matplotlib - label each bin,plt.show() |
Tuple list from dict in Python,list(my_dict.items()) |
Arrow on a line plot with matplotlib,plt.show() |
Reading a CSV into pandas where one column is a json string,df[list(df['stats'][0].keys())] = df['stats'].apply(pandas.Series) |
how to copy only upper triangular values into array from numpy.triu()?,list(A[np.triu_indices(3)]) |
"to read line from file in python without getting ""\n"" appended at the end",line = line.rstrip('\n') |
Selecting specific column in each row from array,"array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0])" |
"Histogram in matplotlib, time on x-Axis",plt.show() |
"Extracting words from a string, removing punctuation and returning a list with separated words in Python","[w for w in re.split('\\W', 'Hello world, my name is...James!') if w]" |
Python: get the position of the biggest item in a numpy array,numpy.argwhere(a.max() == a) |
Insert to cassandra from python using cql,"connection = cql.connect('localhost:9160', cql_version='3.0.0')" |
Remove all the elements that occur in one list from another,l3 = [x for x in l1 if x not in l2] |
blank lines in file after sorting content of a text file in python,lines.sort() |
python-numpy: Apply a function to each row of a ndarray,np.random.seed(1) |
How to convert string to class sub-attribute with Python,"getattr(getattr(getattr(f, 'bar'), 'baz'), 'quux')" |
How to match beginning of string or character in Python,return [t[len(parm):] for t in dir.split('_') if t.startswith(parm)] |
Changing tick label line spacing in matplotlib,plt.show() |
Convert date format python,"datetime.datetime.strptime('5/10/1955', '%d/%m/%Y').strftime('%Y-%m-%d')" |
Filtering a dictionary by multiple values,"filtered_dict = {k: v for k, v in my_dict.items() if not st.isdisjoint(v)}" |
Passing a python dictionary to a psycopg2 cursor,"cur.execute('SELECT add_user(%(nr)s, %(email)s, ...) ...', user)" |
Creating a list of objects in Python,simplelist = [SimpleClass(count) for count in range(4)] |
How do I draw a grid onto a plot in Python?,"plt.rc('grid', linestyle='-', color='black')" |
lambda in python,"(lambda x, y: x + y)(1, 2)" |
How to select/reduce a list of dictionaries in Flask/Jinja,"{{users | selectattr('email', 'equalto', 'foo@bar.invalid')}}" |
Pandas: Replacing column values in dataframe,"w['female'] = w['female'].map({'female': 1, 'male': 0})" |
Plot x-y data if x entry meets condition python,plt.show() |
Sorting the letters of a one worded string in Python?,""""""""""""".join(sorted(x))" |
How to do multiple arguments to map function where one remains the same in python?,"[add(x, 2) for x in [1, 2, 3]]" |
Python: Extract numbers from a string,"re.findall('\\d+', ""hello 42 I'm a 32 string 30"")" |
Pulling a random word/string from a line in a text file in python,print(random.choice(open('WordsForGames.txt').readline().split())) |
How to detect a sign change for elements in a numpy array,"array([0, 0, 1, 0, 0, 1, 0])" |
JSON to model a class using Django,"[{'model': 'myapp.user', 'pk': '89900', 'fields': {'name': 'Clelio de Paula'}}]" |
Removing the Label From Django's TextArea Widget,"comment = forms.CharField(label='', help_text='', widget=forms.Textarea())" |
"pandas, multiply all the numeric values in the data frame by a constant","df.ix[:, (~np.in1d(df.dtypes, ['object', 'datetime']))] *= 3" |
Put a gap/break in a line plot,plt.show() |
How to modify pandas plotting integration?,ax.set_xticks([]) |
How to replace pairs of tokens in a string?,doctest.testmod() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.