text
stringlengths
4
1.08k
"conda - How to install R packages that are not available in ""R-essentials""?","install.packages('png', '/home/user/anaconda3/lib/R/library')"
How can I make an animation with contourf()?,plt.show()
Animating 3d scatterplot in matplotlib,plt.show()
How to create an ec2 instance using boto3,"ec2.create_instances(ImageId='<ami-image-id>', MinCount=1, MaxCount=5)"
"How to get value on a certain index, in a python list?","dictionary = dict([(List[i], List[i + 1]) for i in range(0, len(List), 2)])"
matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3D Plot?,plt.show()
python pandas datetime.time - datetime.time,df.applymap(time.isoformat).apply(pd.to_timedelta)
Pandas: Mean of columns with the same names,"df.groupby(by=df.columns, axis=1).apply(gf)"
Group by multiple time units in pandas data frame,dfts = df.set_index('date_time')
How do I plot multiple X or Y axes in matplotlib?,plt.xlabel('Dose')
How to designate unreachable python code,"raise ValueError(""Unexpected gender; expected 'm' or 'f', got %s"" % gender)"
How can I plot hysteresis in matplotlib?,"ax = fig.add_subplot(111, projection='3d')"
Strip Non alpha numeric characters from string in python but keeping special characters,"re.sub('_', '', re.sub(pattern, '', x))"
How to create python bytes object from long hex string?,s.decode('hex')
How to multiply all integers inside list,"l = map(lambda x: x * 2, l)"
How to read multiple files and merge them into a single pandas data frame?,dfs = pd.concat([pd.read_csv('data/' + f) for f in files])
pandas: How to find the max n values for each category in a column,"[['A', 'Book2', '10'], ['B', 'Book1', '7'], ['B', 'Book2', '5']]"
Best way to permute contents of each column in numpy,"array([[12, 1, 14, 11], [4, 9, 10, 7], [8, 5, 6, 15], [0, 13, 2, 3]])"
Convert integer to hex-string with specific format,hex(x)[2:].decode('hex')
Formatting text to be justified in Python 3.3 with .format() method,"""""""{:20s}"""""".format(mystring)"
Custom keys for Google App Engine models (Python),kwargs['key_name'] = kwargs['name']
How to format a floating number to fixed width in Python,print('{:10.4f}'.format(x))
Get Traceback of warnings,warnings.simplefilter('always')
How to get first element in a list of tuples?,new_list = [seq[0] for seq in yourlist]
collapsing whitespace in a string,"re.sub('[_\\W]+', ' ', s).strip().upper()"
Mapping over values in a python dictionary,"my_dictionary = {k: f(v) for k, v in list(my_dictionary.items())}"
Grouping Pandas DataFrame by n days starting in the begining of the day,df['dateonly'] = df['time'].apply(lambda x: x.date())
pandas: best way to select all columns starting with X,"df.loc[(df == 1).any(axis=1), df.columns.map(lambda x: x.startswith('foo'))]"
Reindex sublevel of pandas dataframe multiindex,df['Measurements'] = df.reset_index().groupby('Trial').cumcount()
How convert a jpeg image into json file in Google machine learning,{'image_bytes': {'b64': 'dGVzdAo='}}
Python: How can I include the delimiter(s) in a string split?,"['(two', 'plus', 'three)', 'plus', 'four']"
How to use python pandas to get intersection of sets from a csv file,csv_pd.query('setA==1 & setB==0 & setC==0').groupby('D').count()
SQLAlchemy query where a column contains a substring,Model.query.filter(Model.columnName.contains('sub_string'))
How to get the current port number in Flask?,app.run(port=port)
Sum one number to every element in a list (or array) in Python,"map(lambda x: x + 1, L)"
Is it possible to print a string at a certain screen position inside IDLE?,sys.stdout.flush()
how to combine two data frames in python pandas,"df_col_merged = pd.concat([df_a, df_b], axis=1)"
How to teach beginners reversing a string in Python?,s[::-1]
"How do you determine if an IP address is private, in Python?",ip.iptype()
Insert item into case-insensitive sorted list in Python,"['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E']"
Numpy: Sorting a multidimensional array by a multidimensional array,a[list(np.ogrid[[slice(x) for x in a.shape]][:-1]) + [i]]
3d plotting with python,plt.show()
How to rotate a QPushButton?,self.layout.addWidget(self.button)
"Using Python, is there a way to automatically detect a box of pixels in an image?",img.save(sys.argv[2])
When should I commit with SQLAlchemy using a for loop?,db.session.commit()
open file with a unicode filename?,open('someUnicodeFilename\u03bb')
Interleaving Lists in Python,"list(chain.from_iterable(zip(list_a, list_b)))"
Python & Pandas: How to query if a list-type column contains something?,df[df.genre.str.join(' ').str.contains('comedy')]
python dict comprehension with two ranges,"{i: j for i, j in zip(list(range(1, 5)), list(range(7, 11)))}"
Python: invalid literal for int() with base 10: '808.666666666667',int(float('808.666666666667'))
Python: prevent values in Pandas Series rounding to integer,"series = pd.Series(list(range(20)), dtype=float)"
Scatterplot Contours In Matplotlib,plt.show()
How to add http headers in suds 0.3.6?,client.set_options(headers={'key2': 'value'})
How to attach a Scrollbar to a Text widget?,"scrollb.grid(row=0, column=1, sticky='nsew')"
Colored LaTeX labels in plots,plt.xlabel('$x=\\frac{ \\color{red}{red text} }{ \\color{blue}{blue text} }$')
"Getting return values from a MySQL stored procedure in Python, using MySQLdb",results = cursor.fetchall()
Proper way in Python to raise errors while setting variables,raise ValueError('password must be longer than 6 characters')
Finding missing values in a numpy array,m[m.mask]
Finding index of maximum value in array with NumPy,x[np.where(x == 5)]
Printing a list using python,"print('[', ', '.join(repr(i) for i in list), ']')"
"In Python, how can I turn this format into a unix timestamp?",int(time.mktime(dt.timetuple()))
How to make Matplotlib scatterplots transparent as a group?,plt.show()
"How to filter the DataFrame rows of pandas by ""within""/""in""?",b = df[(df['a'] > 1) & (df['a'] < 5)]
Pandas DataFrame - Find row where values for column is maximal,df.ix[df['A'].idxmax()]
Representing a multi-select field for weekdays in a Django model,weekdays = models.PositiveIntegerField(choices=WEEKDAYS)
How to get an isoformat datetime string including the default timezone?,datetime.datetime.now(pytz.timezone('US/Central')).isoformat()
How can I replace all the NaN values with Zero's in a column of a pandas dataframe,df['column'] = df['column'].fillna(value)
filtering pandas dataframes on dates,df.ix['2014-01-01':'2014-02-01']
How can I get a list of all classes within current module in Python?,"clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)"
Get top biggest values from each column of the pandas.DataFrame,"pd.DataFrame(_, columns=data.columns, index=data.index[:3])"
How to to filter dict to select only keys greater than a value?,"{k: v for k, v in list(mydict.items()) if k >= 6}"
Capitalizing non-ASCII words in Python,print('\xc3\xa9'.decode('cp1252').capitalize().encode('cp1252'))
How convert a jpeg image into json file in Google machine learning,{'instances': [{'image_bytes': {'b64': 'dGVzdAo='}}]}
Reading hex to double-precision float python,"struct.unpack('d', '4081637ef7d0424a'.decode('hex'))"
How to index a pandas dataframe using locations wherever the data changes,"df.drop_duplicates(keep='last', subset=['valueA', 'valueB'])"
Passing on named variable arguments in python,"methodB('argvalue', **kwargs)"
How to redirect stderr in Python?,"sys.stderr = open('C:\\err.txt', 'w')"
Python/Matplotlib - Is there a way to make a discontinuous axis?,ax.tick_params(labeltop='off')
matplotlib - extracting data from contour lines,plt.show()
How can I make an animation with contourf()?,plt.show()
"Python Regular Expressions, find Email Domain in Address","re.search('@.*', test_string).group()"
Access index of last element in data frame,df['date'][df.index[-1]]
How to mask numpy structured array on multiple columns?,A[(A['segment'] == 42) & (A['material'] == 5)]
How to get the width of a string in pixels?,"width, height = dc.GetTextExtent('Text to measure')"
"search for ""does-not-contain"" on a dataframe in pandas",~df['col'].str.contains(word)
Extracting words between delimiters [] in python,"re.findall('\\[([^\\]]*)\\]', str)"
Flask: Using multiple packages in one app,app.run()
Python list comprehension - simple,[(x * 2 if x % 2 == 0 else x) for x in a_list]
python append to array in json object,jsobj['a']['b']['e'].append(dict(f=var3))
Python most common element in a list,"print(most_common(['goose', 'duck', 'duck', 'goose']))"
Is there a multi-dimensional version of arange/linspace in numpy?,"X, Y = np.mgrid[-5:5:21j, -5:5:21j]"
Embed a web browser in a Python program,browser.close()
Find lowest value in a list of dictionaries in python,return min(d['id'] for d in l if 'id' in d)
Divide two lists in python,"[(x * 1.0 / y) for x, y in zip(a, b)]"
Pythonic way to insert every 2 elements in a string,"""""""-"""""".join(a + b for a, b in zip(t, t))"
Rendering text with multiple lines in pygame,pygame.display.update()
ttk: how to make a frame look like a labelframe?,root.mainloop()
How to overplot a line on a scatter plot in python?,"plt.plot(x, m * x + b, '-')"
Accessing form fields as properties in a django view,print(myForm.cleaned_data.get('description'))
Changing the options of a OptionMenu when clicking a Button,root.mainloop()