text
stringlengths
4
1.08k
Creating List From File In Python,your_list = [int(i) for i in f.read().split()]
Creating a faceted matplotlib/seaborn plot using indicator variables rather than a single column,plt.savefig('multiple_facet_binary_hue')
Mathematical equation manipulation in Python,sympy.sstr(_)
Matplotlib plot with variable line width,plt.show()
Is there a Python equivalent to Ruby's string interpolation?,print('Who lives in a Pineapple under the sea? {name!s}.'.format(**locals()))
Flatten a dictionary of dictionaries (2 levels deep) of lists in Python,[x for d in thedict.values() for alist in d.values() for x in alist]
How to change the window title in pyside?,self.setWindowTitle('QtGui.QCheckBox')
PyQt - how to detect and close UI if it's already running?,sys.exit(app.exec_())
Interpolating one time series onto another in pandas,"pd.concat([data, ts]).sort_index().interpolate().reindex(ts.index)"
Insert string at the beginning of each line,sys.stdout.write('EDF {l}'.format(l=line))
Python - how to delete hidden signs from string?,print(repr(the_string))
pythonic way to filter list for elements with unique length,list({len(s): s for s in jones}.values())
Find array corresponding to minimal values along an axis in another array,"np.tile(np.arange(y), x)"
How can I just list undocumented members with sphinx/autodoc?,"autodoc_default_flags = ['members', 'undoc-members']"
Generating all combinations of a list in python,"print(list(itertools.combinations(a, i)))"
Sum values from DataFrame into Parent Index - Python/Pandas,df_sum = df.groupby('parent').sum()
Check if a value exists in pandas dataframe index,'g' in df.index
How to execute a command in the terminal from a Python script?,subprocess.call('./driver.exe bondville.dat')
Python Pandas Group by date using datetime data,df.set_index('Date_Time').groupby(pd.TimeGrouper('D')).mean().dropna()
Django Model Auto Increment Primary Key Based on Foreign Key,"super(ModelA, self).save(*args, **kwargs)"
How to bind Ctrl+/ in python tkinter?,root.mainloop()
String formatting in Python: can I use %s for all types?,"print('Integer: {0}; Float: {1}; String: {2}'.format(a, b, c))"
Python - delete blank lines of text at the end of the file,file_out[-1] = file_out[-1].strip('\n')
How to make a shallow copy of a list in Python,newprefix = list(prefix)
Django set default form values,form = JournalForm(initial={'tank': 123})
Declaring a multi dimensional dictionary in python,new_dict['a']['b']['c'] = [5]
Scale image in matplotlib without changing the axis,"ax.set_ylim(0, 1)"
is there any pool for ThreadingMixIn and ForkingMixIn for SocketServer?,python - mserver
Creating a socket restricted to localhost connections only,"socket.bind(('127.0.0.1', 80))"
Extract day of year and Julian day from a string date in python,"sum(jdcal.gcal2jd(dt.year, dt.month, dt.day))"
Python - Compress Ascii String,comptest('')
Make subprocess find git executable on Windows,"proc = subprocess.Popen('git status', stdout=subprocess.PIPE, shell=True)"
Pandas: change data type of columns,"df.apply(lambda x: pd.to_numeric(x, errors='ignore'))"
How to query MultiIndex index columns values in pandas,df.query('111 <= B <= 500')
How to query MultiIndex index columns values in pandas,df.query('0 < A < 4 and 150 < B < 400')
How to display an image using kivy,return Image(source='b1.png')
Querying from list of related in SQLalchemy and Flask,User.query.join(User.person).filter(Person.id.in_(p.id for p in people)).all()
Django queryset filter for backwards related fields,Project.objects.filter(action__person=person)
Add new column in Pandas DataFrame Python,df['Col3'] = (df['Col2'] <= 1).astype(int)
get count of values associated with key in dict python,"len([x for x in s if x.get('success', False)])"
Is there a way to find an item in a tuple without using a for loop in Python?,"[0.01691603660583496, 0.016616106033325195, 0.016437053680419922]"
Python Right Click Menu Using PyGTK,menu = gtk.Menu()
Python: finding lowest integer,x = min(float(s) for s in l)
Python: Find first non-matching character,"re.search('[^f]', 'ffffooooooooo').start()"
Remove empty string from list,mylist[:] = [i for i in mylist if i != '']
How to efficiently calculate the outer product of two series of matrices in numpy?,"C = np.einsum('kmn,kln->kml', A, B)"
Creating a Multiplayer game in python,threading.Thread.__init__(self)
Removing non numeric characters from a string,new_string = ''.join(ch for ch in your_string if ch.isdigit())
"""pythonic"" method to parse a string of comma-separated integers into a list of integers?","mylist = [int(x) for x in '3 ,2 ,6 '.split(',') if x.strip().isdigit()]"
Building up a string using a list of values,objects = ' and '.join(['{num} {obj}'.format(**item) for item in items])
How to add unicode character before a string? [Python],print(type('{}'.format(word)))
How can I fill out a Python string with spaces?,"""""""{0: <16}"""""".format('Hi')"
Python regular expression for Beautiful Soup,"['comment form new', 'comment comment-xxxx...']"
"how to remove hashtag, @user, link of a tweet using regular expression","result = re.sub('(?:@\\S*|#\\S*|http(?=.*://)\\S*)', '', subject)"
sorting a counter in python by keys,"sorted(list(c.items()), key=itemgetter(0))"
fitting data with numpy,"np.polyfit(x, y, 4)"
python randomly sort items of the same value,"sorted(a, key=lambda v: (v, random.random()))"
Write a string of 1's and 0's to a binary file?,"int('00100101', 2)"
Finding the indices of matching elements in list in Python,"return [i for i, x in enumerate(lst) if x < a or x > b]"
How to create Major and Minor gridlines with different Linestyles in Python,plt.show()
clone element with beautifulsoup,"document2.body.append(document1.find('div', id_='someid').clone())"
Python Numpy: how to count the number of true elements in a bool array,np.count_nonzero(boolarr)
Python list of tuples to list of int,y = (i[0] for i in x)
Plotting 3D Polygons in python-matplotlib,plt.show()
Multi-line logging in Python,logging.debug('Nothing special here... Keep walking')
Dot notation string manipulation,s.split('.')[-1]
django filter by datetime on a range of dates,"queryset.filter(created_at__range=(start_date, end_date))"
How do I create a new file on a remote host in fabric (python deployment tool)?,run('mv app.wsgi.template app.wsgi')
python json dumps,"""""""[{u'name': u'squats', u'wrs': [[u'99', 8]], u'id': 2}]"""""".replace(""u'"", ""'"")"
change the number of colors in matplotlib stylesheets,h.set_color('r')
How to open the user's preferred mail application on Linux?,webbrowser.open('mailto:test@example.com?subject=Hello World')
PyQt - How to set QComboBox in a table view using QItemDelegate,return QtCore.Qt.ItemIsEnabled
How to let a Python thread finish gracefully,time.sleep(10)
Make an http POST request to upload a file using python urllib/urllib2,"response = requests.post(url, files=files)"
"On Windows, how to convert a timestamps BEFORE 1970 into something manageable?","datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=-2082816000)"
Reading data into numpy array from text file,"data = numpy.loadtxt(yourFileName, skiprows=n)"
Pandas: Check if row exists with certain values,((df['A'] == 1) & (df['B'] == 2)).any()
Convert float to string without scientific notation and false precision,"format(5e-10, 'f')"
Changing the text on a label,self.labelText = 'change the value'
"How to change numpy array from (128,128,3) to (3,128,128)?","a.transpose(2, 0, 1)"
Replace non-ASCII characters with a single space,"re.sub('[^\\x00-\\x7f]', ' ', n)"
How to create a fix size list in python?,[None] * 10
How do I update an object's members using a dict?,"setattr(foo, key, value)"
Convert pandas DataFrame to a nested dict,df.to_dict()
Python regex -- extraneous matchings,"re.findall('-|\\+=|==|=|\\+|[^-+=\\s]+', 'hello-+==== =+ there')"
How do i find the scalar product of a Numpy Matrix ?,"b = np.fill_diagonal(np.zeros_like(a), value)"
How to install PySide on CentOS?,python - pip
How to unpack multiple tuples in function call,"f(tup1[0], tup1[1], tup2[0], tup2[1])"
Horizontal box plots in matplotlib/Pandas,plt.show()
Displaying multiple masks in different colours in pylab,"ax.imshow(a, interpolation='nearest')"
How to decode this representation of a unicode string in Python?,print(bytes.decode(encoding))
"python, numpy; How to insert element at the start of an array","np.insert(my_array, 0, myvalue, axis=1)"
Filtering a list of strings based on contents,[x for x in L if 'ab' in x]
Python Spliting a string,"a, b = 'string_without_spaces'.split(' ', 1)"
How to flush output of Python print?,sys.stdout.flush()
How do I remove rows from a dataframe?,"print(df.ix[i, 'attr'])"
reverse a string in Python,"l = [1, 2, 3]"
How can I get the output of a matplotlib plot as an SVG?,"plt.savefig('test.svg', format='svg')"
How to fill rainbow color under a curve in Python matplotlib,plt.show()
Change date of a DateTimeIndex,"df.index.map(lambda t: t.replace(year=2013, month=2, day=1))"