text
stringlengths
4
1.08k
What are some good ways to set a path in a Multi-OS supported Python script,"os.path.join(os.path.abspath(os.path.dirname(__file__)), 'logs')"
How do I get the indexes of unique row for a specified column in a two dimensional array,"[[0, 5], [2, 7], [1, 3, 9], [4, 10], [6], [8]]"
How to remove gaps between subplots in matplotlib?,"fig.subplots_adjust(wspace=0, hspace=0)"
How to create mosaic plot from Pandas dataframe with Statsmodels library?,"mosaic(myDataframe, ['size', 'length'])"
BeautifulSoup in Python - getting the n-th tag of a type,secondtable = soup.findAll('table')[1]
Computing diffs within groups of a dataframe,"df.filter(['ticker', 'date', 'value'])"
Iterating over a dictionary to create a list,"['blue', 'blue', None, 'red', 'red', 'green', None]"
matplotlib colorbar formatting,"plt.rcParams['text.latex.preamble'].append('\\mathchardef\\mhyphen=""2D')"
Optional dot in regex,"re.sub('\\bMr\\.|\\bMr\\b', 'Mister', s)"
How do convert a pandas/dataframe to XML?,xml.etree.ElementTree.parse('xml_file.xml')
How do you reverse the significant bits of an integer in python?,"return int(bin(x)[2:].zfill(32)[::-1], 2)"
Key Order in Python Dictionaries,print(sorted(d.keys()))
How do I offset lines in matplotlib by X points,plt.show()
How to create an immutable list in Python?,new_list = copy.deepcopy(old_list)
Paging depending on grouping of items in Django,messages = Message.objects.filter(head=True).order_by('time')[0:15]
Getting user input,filename = input('Enter a file name: ')
Making a list of evenly spaced numbers in a certain range in python,"np.linspace(0, 5, 10, endpoint=False)"
Python sorting - A list of objects,somelist.sort(key=lambda x: x.resultType)
Convert json to pandas DataFrame,"pd.concat([pd.Series(json.loads(line)) for line in open('train.json')], axis=1)"
How to retrieve Facebook friend's information with Python-Social-auth and Django,"SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_friends', 'friends_location']"
how to output every line in a file python,f.close()
cant connect to TOR with python,"httplib.HTTPConnection('myip.dnsomatic.com').request('GET', '/')"
Is there a Numpy function to return the first index of something in an array?,array[itemindex[0][0]][itemindex[1][0]]
How do I get the name from a named tuple in python?,type(ham).__name__
Multiple linear regression with python,import pandas as pd
Python Using Adblock with Selenium and Firefox Webdriver,ffprofile = webdriver.FirefoxProfile('/Users/username/Downloads/profilemodel')
How to convert a string to a function in python?,"eval('add(3,4)', {'__builtins__': None}, dispatcher)"
Select Rows from Numpy Rec Array,array[array['phase'] == 'P']
Multiplying a tuple by a scalar,tuple([(10 * x) for x in img.size])
How to use Python to calculate time,"print(now + datetime.timedelta(hours=1, minutes=23, seconds=10))"
Python/Matplotlib - Is there a way to make a discontinuous axis?,"plt.plot(x, y, '.')"
How to plot bar graphs with same X coordinates side by side,plt.show()
Sort list of dictionaries by multiple keys with different ordering,"stats.sort(key=lambda x: (x['K'], x['B']), reverse=True)"
Dynamically change widget background color in Tkinter,root.mainloop()
How do I suppress scientific notation in Python?,'%f' % (x / y)
Matplotlib/pyplot: How to enforce axis range?,fig.savefig('the name of your figure')
How to make a window fullscreen in a secondary display with tkinter?,root.mainloop()
Join last element in list,""""""" & """""".join(['_'.join(inp[i:j]) for i, j in zip([0, 2], [2, None])])"
How to add title to subplots in Matplotlib?,plt.show()
Pandas : Assign result of groupby to dataframe to a new column,df['size'].loc[df.groupby('adult')['weight'].transform('idxmax')]
python requests not working with google app engine,"r = http.request('GET', 'https://www.23andme.com/')"
Using 'if in' with a dictionary,any(value in dictionary[key] for key in dictionary)
Create a list of tuples with adjacent list elements if a condition is true,"[(x, y) for x, y in zip(myList, myList[1:]) if y == 9]"
Finding The Biggest Key In A Python Dictionary,"sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)[:2]"
How do I get the path of a the Python script I am running in?,print(os.path.abspath(__file__))
google app engine oauth2 provider,"app = webapp2.WSGIApplication([('/.*', MainHandler)], debug=True)"
connect to url in python,urllib.request.install_opener(opener)
URL encoding in python,urllib.parse.quote('%')
Drawing cards from a deck in SciPy with scipy.stats.hypergeom,"scipy.stats.hypergeom.pmf(k, M, n, N)"
PyQt dialog - How to make it quit after pressing a button?,btn.clicked.connect(self.close)
How to set the font size of a Canvas' text item?,"canvas.create_text(x, y, font=('Purisa', rndfont), text=k)"
Removing Trailing Zeros in Python,float('123.4506780')
"In a matplotlib plot, can I highlight specific x-value ranges?",plt.show()
streaming m3u8 file with opencv,cv2.destroyAllWindows()
Combining multiple 1D arrays returned from a function into a 2D array python,"np.array([a, a, a])"
Extracting first n columns of a numpy matrix,"a[:, :2]"
MITM proxy over SSL hangs on wrap_socket with client,connection.send('HTTP/1.0 200 OK')
understanding list comprehension for flattening list of lists in python,[item for sublist in list_of_lists for item in sublist]
Get size of a file before downloading in Python,os.stat('/the/local/file.zip').st_size
How to find all occurrences of a pattern and their indices in Python,"[x.span() for x in re.finditer('foo', 'foo foo foo foo')]"
Pandas (python): How to add column to dataframe for index?,df['index_col'] = df.index
Is it possible to have a vertical-oriented button in tkinter?,main.mainloop()
How do I edit and delete data in Django?,return HttpResponse('deleted')
python: plot a bar using matplotlib using a dictionary,plt.show()
Pandas - Get first row value of a given column,df_test['Btime'].iloc[0]
Pandas: Counting unique values in a dataframe,pd.value_counts(d.values.ravel())
Remove dtype at the end of numpy array,"data = numpy.loadtxt(fileName, dtype='float')"
Multiply high order matrices with numpy,"np.tensordot(ind, dist, axes=[1, 1])[0].T"
How to make pylab.savefig() save image for 'maximized' window instead of default size,"matplotlib.rc('font', size=6)"
Is there a function to make scatterplot matrices in matplotlib?,plt.show()
Create a tuple from a string and a list of strings,my_tuple = tuple([my_string] + my_list)
How can I perform a ping or traceroute using native python?,"webb.traceroute('your-web-page-url', 'file-name.txt')"
Sort dict in jinja2 loop,"sorted(list(league.items()), key=lambda x: x[1]['totalpts'], reverse=True)"
How do I get a website's IP address using Python 3.x?,socket.gethostbyname('cool-rr.com')
"Extracting words from a string, removing punctuation and returning a list with separated words in Python","re.findall('[%s]+' % string.ascii_letters, 'Hello world, my name is...James!')"
Most efficient way to access binary files on ADLS from worker node in PySpark?,"[4957, 4957, 1945]"
How do I make the width of the title box span the entire plot?,plt.show()
Python regex for unicode capitalized words,"re.findall('(\\b[A-Z\xc3\x9c\xc3\x96\xc3\x84][a-z.-]+\\b)', words, re.UNICODE)"
How to get the value of a variable given its name in a string?,globals()['a']
Is there a more pythonic way to populate a this list?,"[2, 4, 6, 8]"
How to use delimiter for csv in python,"csv.writer(f, delimiter=' ', quotechar=',', quoting=csv.QUOTE_MINIMAL)"
How to unnest a nested list?,"from functools import reduce
reduce(lambda x, y: x + y, A, [])"
Python split string on regex,p = re.compile('(Friday\\s\\d+|Saturday)')
How can I plot NaN values as a special color with imshow in matplotlib?,"ax.imshow(masked_array, interpolation='nearest', cmap=cmap)"
How to fit result of matplotlib.pyplot.contourf into circle?,plt.show()
run multiple tornado processess,"application = tornado.web.Application([('/', hello)], debug=False)"
Python long integer input,n = int(input())
Split a multidimensional numpy array using a condition,"good_data = np.array([x for x in data[(0), :] if x == 1.0])"
Slice pandas DataFrame where column's value exists in another array,df[df.a.isin(keys)]
"Python: Tuples/dictionaries as keys, select, sort",fruits.sort(key=lambda x: x.name.lower())
Invalid syntax error using format with a string in Python 3 and Matplotlib,"""""""$Solución \\; {}\\; :\\; {}\\\\$"""""".format(i, value)"
How to combine the data from many data frames into a single data frame with an array as the data values,"p.apply(np.sum, axis='major')"
Convert a list of characters into a string,"['a', 'b', 'c'].join('')"
Sorting a tuple that contains tuples,"sorted(my_tuple, key=lambda tup: tup[1])"
Consequences of abusing nltk's word_tokenize(sent),"nltk.tokenize.word_tokenize('Hello, world. How are you?')"
Populating a SQLite3 database from a .txt file with Python,c.execute('SELECT * FROM politicians').fetchall()
How to download file from ftp?,ftp.quit()
Matplotlib fill beetwen multiple lines,plt.show()
Sorting Python list based on the length of the string,xs.sort(key=len)