text
stringlengths
4
1.08k
removing nan values from a python list,cleanlist = [(0.0 if math.isnan(x) else x) for x in oldlist]
beautifulsoup - search by text inside a tag,"soup.find_all('a', string='Elsie')"
finding missing values in a numpy array,m[m.mask]
how to save a list as numpy array in python?,"a = array([[2, 3, 4], [3, 4, 5]])"
how to accumulate an array by index in numpy?,"np.add.at(a, np.array([1, 2, 2, 1, 3]), np.array([1, 1, 1, 1, 1]))"
extracting first n columns of a numpy matrix,"A = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]"
maintain strings when converting python list into numpy structured array,"numpy.array(data, dtype=[('label', 'S2'), ('x', float), ('y', float)])"
google app engine: webtest simulating logged in user and administrator,os.environ['USER_IS_ADMIN'] = '1'
pandas groupby sort within groups,"df_agg = df.groupby(['job', 'source']).agg({'count': sum})"
change current working directory in python,os.chdir('.\\chapter3')
how to import django models in scrapy pipelines.py file,"sys.path.insert(0, '/home/zartch/PycharmProjects/Scrapy-Django-Minimal/myweb')"
find the index of sub string 's' in string `str` starting from index 11 and ending at index 14,"str.find('s', 11, 14)"
compare two lists in python `a` and `b` and return matches,set(a).intersection(b)
"check whether a path ""/etc/password.txt"" exists",print(os.path.exists('/etc/password.txt'))
extract unique dates from time series 'date' in dataframe `df`,df['Date'].map(lambda t: t.date()).unique()
"doc, rtf and txt reader in python",txt = open('file.txt').read()
get full computer name from a network drive letter in python,socket.gethostname()
getting values from json using python,"data = json.loads('{""lat"":444, ""lon"":555}')"
writing list of strings to excel csv file in python,csvwriter.writerow(row)
how can i compare a date and a datetime in python?,"datetime.datetime(d.year, d.month, d.day)"
python/matplotlib - how to put text in the corner of equal aspect figure,plt.show()
how to populate shelf with existing dictionary,myShelvedDict.update(myDict)
convert from ascii string encoded in hex to plain ascii?,print(binascii.unhexlify('7061756c'))
how to get full path of current file's directory in python?,print(os.path.dirname(__file__))
remove or adapt border of frame of legend using matplotlib,plt.legend(frameon=False)
how do i run selenium in xvfb?,browser.get('http://www.google.com')
how to make pylab.savefig() save image for 'maximized' window instead of default size,"plt.savefig('myplot.png', dpi=100)"
change the size of the sci notation to '30' above the y axis in matplotlib `plt`,"plt.rc('font', **{'size': '30'})"
pandas unique values multiple columns,"pandas.concat([df['a'], df['b']]).unique()"
"remove commas in a string, surrounded by a comma and double quotes / python","str = re.sub(',(?=[^""]*""[^""]*$)', '@', str)"
read csv file 'myfile.csv' into array,"np.genfromtxt('myfile.csv', delimiter=',', dtype=None)"
sorting a list of tuples in python,"sorted(list_of_tuples, key=lambda tup: tup[::-1])"
get the path of the current python module,print(os.getcwd())
how do i modify the last line of a file?,f.close()
how can i substract a single value from a column using pandas and python,df['hb'] - 5
deploying flask app to heroku,"app.run(debug=True, port=33507)"
execute a command in the command prompt to list directory contents of the c drive `c:\\',os.system('dir c:\\')
find the column name which has the maximum value for each row,"df['Max'] = df[['Communications', 'Business']].idxmax(axis=1)"
python - extract folder path from file path,os.path.dirname(os.path.abspath(existGDBPath))
separate each character in string `s` by '-',"re.sub('(.)(?=.)', '\\1-', s)"
how to plot a 3d patch collection in matplotlib?,plt.show()
filtering a list of strings based on contents,[k for k in lst if 'ab' in k]
how to automate the delegation of __special_methods__ in python?,self.ham = dict()
change values in a numpy array,a[a == 2] = 10
find the index of sub string 'aloha' in `x`,x.find('Aloha')
"pythonic way to validate time input (only for hr, min, sec)","values = (int(i) for i in values.split(','))"
accessing a decorator in a parent class from the child in python,"super(otherclass, self).__init__()"
"check if all elements in a tuple `(1, 6)` are in another `(1, 2, 3, 4, 5)`","all(i in (1, 2, 3, 4, 5) for i in (1, 6))"
can a python script execute a function inside a bash script?,"subprocess.Popen(['bash', '-c', '. foo.sh; go'])"
how to get one number specific times in an array python,"array([4, 5, 5, 6, 6, 6])"
how to find the cumulative sum of numbers in a list?,"subseqs = (seq[:i] for i in range(1, len(seq) + 1))"
django one-to-many models,vulnerability = models.ForeignKey(Vuln)
how to convert integer value to array of four bytes in python,"struct.unpack('4b', struct.pack('I', 100))"
how to convert from infix to postfix/prefix using ast python module?,"['w', 'time', '*', 'sin']"
how to make several plots on a single page using matplotlib?,"fig.add_subplot(1, 1, 1)"
is it possible to effectively initialize bytearray with non-zero value?,"array([True, True, True, True, True, True, True, True, True, True], dtype=bool)"
pandas unique values multiple columns,"pd.unique(df[['Col1', 'Col2']].values.ravel())"
python - sum values in dictionary,sum(item['gold'] for item in myLIst)
pyv8 in threads - how to make it work?,t.start()
print output in a single line,"print('{0} / {1}, '.format(x + 1, y), end=' ')"
how do i prevent pandas.to_datetime() function from converting 0001-01-01 to 2001-01-01,"pd.to_datetime(tempDF['date'], format='%Y-%m-%d %H:%M:%S.%f', errors='coerce')"
python date string formatting,"""""""{0.month}/{0.day}/{0.year}"""""".format(my_date)"
how to add a new encoding to python 2.6?,'\x83'.encode('cp870')
python convert list to dictionary,dict(zip(*([iter(l)] * 2)))
how to avoid line color repetition in matplotlib.pyplot?,plt.savefig('pal3.png')
"using python, is there a way to automatically detect a box of pixels in an image?",img.save(sys.argv[2])
python app import error in django with wsgi gunicorn,"sys.path.insert(1, os.path.dirname(os.path.realpath(__file__)))"
sort a list of dictionary `persons` according to the key `['passport']['birth_info']['date']`,"sorted(persons, key=lambda x: x['passport']['birth_info']['date'])"
how do i find the distance between two points?,dist = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
how to pass dictionary items as function arguments in python?,my_function(**data)
in python: iterate over each string in a list,c = sum(1 for word in words if word[0] == word[-1])
searche in html string for elements that have text 'python',soup.body.findAll(text='Python')
convert string '03:55' into datetime.time object,"datetime.datetime.strptime('03:55', '%H:%M').time()"
how can i get dict from sqlite query?,print(cur.fetchone()['a'])
how to use hough circles in cv2 with python?,"circles = cv2.HoughCircles(gray, cv.CV_HOUGH_GRADIENT)"
pandas : delete rows based on other rows,"pd.merge(df.reset_index(), df, on='sseqid')"
how to eject cd using wmi and python?,"ctypes.windll.WINMM.mciSendStringW('set cdaudio door open', None, 0, None)"
regex match even number of letters,re.compile('^([^A]*)AA([^A]|AA)*$')
split a list of tuples `data` into sub-lists of the same tuple field using itertools,"[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]"
python: how to move a file with unicode filename to a unicode folder,os.chdir('\xd7\x90')
keep a list `datalist` of lists sorted as it is created by second element,dataList.sort(key=lambda x: x[1])
selenium (with python) how to modify an element css style,"driver.execute_script(""$('#copy_link').css('visibility', 'visible');"")"
pandas how to use groupby to group columns by date in the label?,"x.groupby(pd.PeriodIndex(x.columns, freq='Q'), axis=1).mean()"
how to update a histogram when a slider is used?,plt.show()
"efficiently re-indexing one level with ""forward-fill"" in a multi-index dataframe",df1['value'].unstack(0)
how do i raise the same exception with a custom message in python?,print(' got error of type ' + str(type(e)) + ' with message ' + e.message)
python: zip dict with keys,"[{'char': 'a', 'num': 1}, {'char': 'd', 'num': 18}]"
how do i use a md5 hash (or other binary data) as a key name?,k = hashlib.md5('thecakeisalie').hexdigest()
string reverse in python,print(''.join(x[::-1] for x in pattern.split(string)))
google app engine oauth2 provider,"app = webapp2.WSGIApplication([('/.*', MainHandler)], debug=True)"
print a string as hex bytes?,""""""":"""""".join('{:02x}'.format(ord(c)) for c in s)"
subtract 5 hours from the time object `dt`,dt -= datetime.timedelta(hours=5)
pandas/python: how to concatenate two dataframes without duplicates?,"pandas.concat([df1, df2]).drop_duplicates().reset_index(drop=True)"
how to split a string on the first instance of delimiter in python,"""""""jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,"""""".split('=', 1)"
strip and split each line `line` on white spaces,line.strip().split(' ')
how to use delimiter for csv in python,"csv.writer(f, delimiter=' ', quotechar=',', quoting=csv.QUOTE_MINIMAL)"
how to drop a list of rows from pandas dataframe?,"df.drop(df.index[[1, 3]])"
how can i convert an rgb image into grayscale in python?,"img = cv2.imread('messi5.jpg', 0)"
removing letters from a list of both numbers and letters,sum(int(c) for c in strs if c.isdigit())
how to run sudo with paramiko? (python),"ssh.connect('127.0.0.1', username='jesse', password='lol')"