text
stringlengths 4
1.08k
|
|---|
How to check if type of a variable is string?,"isinstance(s, str)"
|
What is the difference between a string and a byte string?,"""""""I am a string"""""".decode('ASCII')"
|
How to plot a density map in python?,plt.show()
|
How can I use a 2D array of boolean rows to filter another 2D array?,"data[(np.where(masks)[1]), :]"
|
What is the best way to get the first item from an iterable matching a condition?,next((x for x in range(10) if x > 5))
|
Can I put a tuple into an array in python?,"a = [('b', i, 'ff') for i in range(1, 5)]"
|
How to change text of a label in the kivy language with python,YourApp().run()
|
numpy array multiplication with arrays of arbitrary dimensions,"np.allclose(C0, C3)"
|
How to extract the year from a Python datetime object?,a = datetime.datetime.now().year
|
Sub matrix of a list of lists (without numpy),[row[2:5] for row in LoL[1:4]]
|
How to execute an .sql file in pymssql,cursor.close()
|
Subtract a column from one pandas dataframe from another,"rates.sub(treas.iloc[:, (0)], axis=0).dropna()"
|
Get the dictionary values for every key in a list,values = [d[k] for k in a]
|
Scrapy:How to print request referrer,"response.request.headers.get('Referer', None)"
|
Convert JSON to CSV,csv_file.close()
|
Django Model: How to use mixin class to override django model for function likes save,"super(SyncableMixin, self).save(*args, **kwargs)"
|
Applying a function to values in dict,"d2 = {k: f(v) for k, v in list(d1.items())}"
|
sorting values of python dict using sorted builtin function,"sorted(list(mydict.values()), reverse=True)"
|
How to JSON serialize __dict__ of a Django model?,"return HttpResponse(json.dumps(data), content_type='application/json')"
|
How to resample a df with datetime index to exactly n equally sized periods?,"df.resample('2D', how='sum')"
|
Using python to write specific lines from one file to another file,f.write('foo')
|
How to download file from ftp?,ftp.retrlines('LIST')
|
matplotlib: Set markers for individual points on a line,plt.show()
|
Pandas fillna() based on specific column attribute,"df.loc[df['Type'] == 'Dog', ['Killed']]"
|
Python: Get the first character of a the first string in a list?,mylist[0][0]
|
Python split string with multiple-character delimiter,"""""""Hello there. My name is Fr.ed. I am 25.5 years old."""""".split('. ')"
|
Efficient calculation on a pandas dataframe,"C = pd.merge(C, A, on=['Canal', 'Gerencia'])"
|
in python how do I convert a single digit number into a double digits string?,"""""""{0:0=2d}"""""".format(a)"
|
Lack of ROLLBACK within TestCase causes unique contraint violation in multi-db django app,multi_db = True
|
sorting a graph by its edge weight. python,"lst.sort(key=lambda x: (-x[2], x[0]))"
|
Drop all duplicate rows in Python Pandas,"df.drop_duplicates(subset=['A', 'C'], keep=False)"
|
Feeding a Python array into a Perl script,"[1, 2, 3]"
|
Playing video in Gtk in a window with a menubar,Gtk.main()
|
Create kml from csv in Python,f.close()
|
"Missing data, insert rows in Pandas and fill with NAN",df.set_index('A').reindex(new_index).reset_index()
|
How can I disable logging while running unit tests in Python Django?,logging.disable(logging.NOTSET)
|
Python: confusions with urljoin,"urljoin('http://some/more', 'thing')"
|
Python: confusions with urljoin,"urljoin('http://some/more/', 'thing')"
|
Python: confusions with urljoin,"urljoin('http://some/more/', '/thing')"
|
python: MYSQLdb. how to get columns name without executing select * in a big table?,cursor.execute('SELECT * FROM table_name LIMIT 1')
|
How to create a spinning command line cursor using python?,sys.stdout.write('\x08')
|
How to print like printf in python3?,"print('a={:d}, b={:d}'.format(f(x, n), g(x, n)))"
|
format strings and named arguments in Python,"""""""{} {}"""""".format(10, 20)"
|
How to maximize a plt.show() window using Python,plt.show()
|
How to get MD5 sum of a string?,print(hashlib.md5('whatever your string is').hexdigest())
|
How do I right-align numeric data in Python?,"""""""a string {0:>5}"""""".format(foo)"
|
How to drop a list of rows from Pandas dataframe?,"df.drop(df.index[[1, 3]])"
|
Python find list lengths in a sublist,[len(x) for x in a[0]]
|
Comparing lists of dictionaries,"all(d1[k] == d2[k] for k in ('testclass', 'testname'))"
|
How to use pandas to group pivot table results by week?,"df.resample('w', how='sum', axis=1)"
|
Setting aspect ratio of 3D plot,"ax.auto_scale_xyz([0, 500], [0, 500], [0, 0.15])"
|
Python pickle/unpickle a list to/from a file,pickle.load('afile')
|
Replacing values greater than a limit in a numpy array,"np.array([[0, 1, 2, 3], [4, 5, 4, 3], [6, 5, 4, 3]])"
|
How to generate all permutations of a list in Python,"print(list(itertools.permutations([1, 2, 3, 4], 2)))"
|
matplotlib scatter plot colour as function of third variable,plt.show()
|
Creating dictionary from space separated key=value string in Python,"{k: v.strip('""') for k, v in re.findall('(\\S+)=("".*?""|\\S+)', s)}"
|
How to shorten this if and elif code in Python,('NORTH ' if b > 0 else 'SOUTH ') + ('EAST' if a > 0 else 'WEST')
|
How can one replace an element with text in lxml?,"print(etree.tostring(f, pretty_print=True))"
|
Unpythonic way of printing variables in Python?,"print('{foo}, {bar}, {baz}'.format(**locals()))"
|
How can a Python list be sliced such that a column is moved to being a separate element column?,"[item for sublist in [[i[1:], [i[0]]] for i in l] for item in sublist]"
|
How to construct regex for this text,"re.findall('(?<=\\s)\\d.*?(?=\\s\\d\\s\\d[.](?=$|\\s[A-Z]))', s)"
|
how to do bitwise exclusive or of two strings in python?,"l = [(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]"
|
Most Pythonic way to provide global configuration variables in config.py?,config['mysql']['tables']['users']
|
How to scp in python?,client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
Custom sorting in pandas dataframe,df.set_index(s.index).sort()
|
Best way to print list output in python,print('---'.join(vals))
|
tornado write a Jsonp object,"{'1': 2, 'foo': 'bar', 'false': true}"
|
how to shade points in scatter based on colormap in matplotlib?,plt.show()
|
how to use hough circles in cv2 with python?,"circles = cv2.HoughCircles(gray, cv.CV_HOUGH_GRADIENT)"
|
How to check if an element from List A is not present in List B in Python?,"[1, 2, 3]"
|
Simple way to append a pandas series with same index,"pd.Series(np.concatenate([a, b]))"
|
Pandas: Selection with MultiIndex,df[pd.Series(df.index.get_level_values('A')).isin(vals[vals['values']].index)]
|
How to use POST method in Tornado?,"data = self.get_argument('data', 'No data received')"
|
Transpose a matrix in Python,"[[1, 2, 3], [4, 5, 6], [7, 8, 9]]"
|
Convert Pandas dataframe to csv string,df.to_csv()
|
Some built-in to pad a list in python,a += [''] * (N - len(a))
|
How to check if an element from List A is not present in List B in Python?,C = [i for i in A if i not in B]
|
Python: Creating a 2D histogram from a numpy matrix,"plt.imshow(Z, interpolation='none')"
|
Selenium (with python) how to modify an element css style,"driver.execute_script(""document.getElementById('lga').style.display = 'none';"")"
|
How to sum a 2d array in Python?,"sum(map(sum, a))"
|
How to delete everything after a certain character in a string?,"s = s.split('.zip', 1)[0] + '.zip'"
|
Python: how to count overlapping occurrences of a substring,"len([s.start() for s in re.finditer('(?=aa)', 'aaa')])"
|
Making a string out of a string and an integer in Python,name = 'b' + str(num)
|
Group/Count list of dictionaries based on value,"Counter({'BlahBlah': 1, 'Blah': 1})"
|
How to find range overlap in python?,"list(range(max(x[0], y[0]), min(x[-1], y[-1]) + 1))"
|
How to deal with SettingWithCopyWarning in Pandas?,df[df['A'] > 2]['B'] = new_val
|
Print a dict sorted by values,"sorted(((v, k) for k, v in d.items()), reverse=True)"
|
Where's the error in this for loop to generate a list of ordered non-repeated combinations?,"[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]"
|
What is the proper way to insert an object with a foreign key in SQLAlchemy?,transaction.commit()
|
How do I convert unicode code to string in Python?,print(text.decode('unicode-escape'))
|
live output from subprocess command,"proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)"
|
How can I get an array of alternating values in python?,"np.resize([1, -1], 11)"
|
How to make 3D plots in Python?,plt.show()
|
How do I plot multiple X or Y axes in matplotlib?,plt.ylabel('Response')
|
Python pandas plot time-series with gap,df.plot(x=df.index.astype(str))
|
pairwise traversal of a list or tuple,"[(x - y) for x, y in zip(a[1:], a)]"
|
Convert a column of timestamps into periods in pandas,df[1] = df[0].dt.to_period('M')
|
how to save captured image using pygame to disk,"pygame.image.save(img, 'image.jpg')"
|
Using resample to align multiple timeseries in pandas,"print(df.resample('Q-APR', loffset='-1m').T)"
|
An elegant way to get hashtags out of a string in Python?,[i[1:] for i in line.split() if i.startswith('#')]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.