text
stringlengths
4
1.08k
"Running a python debug session from a program, not from the console",p.communicate('continue')
How to initialise a 2D array in Python?,"[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]"
Python Pandas - How to flatten a hierarchical index in columns,pd.DataFrame(df.to_records())
Creating new binary columns from single string column in pandas,pd.get_dummies(df['Speed'])
Initializing a list to a known number of elements in Python,verts = [[(0) for x in range(100)] for y in range(10)]
create dictionary from list of variables,"createDict('foo', 'bar')"
Setting up SCons to Autolint,"env.Program('test', Glob('*.cpp'))"
python dict comprehension with two ranges,"{k: v for k, v in zip(range(1, 5), count(7))}"
Escape string Python for MySQL,cursor.execute(sql)
Pandas HDFStore of MultiIndex DataFrames: how to efficiently get all indexes,"store.select('df', columns=['A'])"
Pandas: Counting unique values in a dataframe,"pd.value_counts(d[['col_title1', 'col_title2']].values.ravel())"
Passing a List to Python From Command Line,main(sys.argv[1:])
Regex to allow safe characters,"""""""^[A-Za-z0-9._~()'!*:@,;+?-]*$"""""""
Removing space in dataframe python,"formatted.columns = [x.strip().replace(' ', '_') for x in formatted.columns]"
Django datetime issues (default=datetime.now()),"date = models.DateTimeField(default=datetime.now, blank=True)"
How to make a simple cross-platform webbrowser with Python?,sys.exit(app.exec_())
How to implement a dynamic programming algorithms to TSP in Python?,A = [[(0) for i in range(n)] for j in range(2 ** n)]
TypeError: a float is required,x = float(x)
How do I suppress scientific notation in Python?,"""""""{0:f}"""""".format(x / y)"
smartest way to join two lists into a formatted string,"c = ', '.join('{}={}'.format(*t) for t in zip(a, b))"
"Sqlite3, OperationalError: unable to open database file",conn = sqlite3.connect('C:\\users\\guest\\desktop\\example.db')
Sort order of lists in multidimensional array in Python,"sorted(test, key=lambda x: isinstance(x, list) and len(x) or 1)"
pandas data frame indexing using loc,"pd.Series([pd.Timestamp('2014-01-02'), 'THU', 'THU'])"
pandas data frame indexing using loc,df['Weekday'].loc[1]
Using nx.write_gexf in Python for graphs that have dict data on nodes and edges,"G.add_edge(0, 1, likes=['milk', 'oj'])"
Notebook widget in Tkinter,root.mainloop()
Output utf-8 characters in django as json,"print(json.dumps('\u0411', ensure_ascii=False))"
How to filter files (with known type) from os.walk?,"files = [file for file in files if not file.endswith(('.dat', '.tar'))]"
Converting a full column of integer into string with thousands separated using comma in pandas,"df['Population'].str.replace('(?!^)(?=(?:\\d{3})+$)', ',')"
How are POST and GET variables handled in Python?,print(request.form['username'])
Multiple levels of keys and values in Python,creatures['birds']['eagle']['female'] += 1
Python Matplotlib - Smooth plot line for x-axis with date values,fig.show()
Difference between every pair of columns of two numpy arrays (how to do it more efficiently)?,"((a[:, (np.newaxis), :] - v) ** 2).sum(axis=-1).shape"
How to scroll text in Python/Curses subwindow?,stdscr.getch()
applying functions to groups in pandas dataframe,df.groupby('type').apply(foo)
Updating the x-axis values using matplotlib animation,plt.show()
Parsing JSON with python: blank fields,"entries['extensions'].get('telephone', '')"
Python - datetime of a specific timezone,print(datetime.datetime.now(EST()))
Selenium with pyvirtualdisplay unable to locate element,content = browser.find_element_by_id('content')
Get norm of numpy sparse matrix rows,"n = np.sqrt(np.einsum('ij,ij->i', a, a))"
"How to print a list with integers without the brackets, commas and no quotes?","print(int(''.join(str(x) for x in [7, 7, 7, 7])))"
"Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?","dict((name, eval(name)) for name in list_of_variable_names)"
SQLAlchemy: How to order query results (order_by) on a relationship's field?,session.query(Base).join(Base.owner).order_by(Player.name)
How to write text on a image in windows using python opencv2,"cv2.putText(image, 'Hello World!!!', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)"
Counting how many times a row occurs in a matrix (numpy),(array_2d == row).all(-1).sum()
Python list sorting dependant on if items are in another list,"sorted([True, False, False])"
Get random sample from list while maintaining ordering of items?,"random.sample(range(len(mylist)), sample_size)"
How do I dissolve a pattern in a numpy array?,"array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])"
changing file extension in Python,os.path.splitext('name.fasta')[0] + '.aln'
find row or column containing maximum value in numpy array,"np.argmax(np.max(x, axis=0))"
Missing data in pandas.crosstab,"pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'], dropna=False)"
Add horizontal lines to plot based on sort_values criteria,plt.show()
How to filter rows of Pandas dataframe by checking whether sub-level index value within a list?,df[df.index.levels[0].isin([int(i) for i in stk_list])]
Reverse each word in a string,""""""" """""".join(w[::-1] for w in s.split())"
Replacing the empty strings in a string,"string2.replace('', string1)"
How to use Jenkins Environment variables in python script,qualifier = os.environ['QUALIFIER']
Pandas groupby where all columns are added to a list prefixed by column name,df.groupby('id1').apply(func)
Group dictionary key values in python,mylist.sort(key=itemgetter('mc_no'))
How to calculate a column in a Row using two columns of the previous Row in Spark Data Frame?,df.show()
How do I create an OpenCV image from a PIL image?,"cv.ShowImage('pil2ipl', cv_img)"
Python - how to delete hidden signs from string?,"new_string = re.sub('[^{}]+'.format(printable), '', the_string)"
Python: for loop - print on the same line,print(' '.join([function(word) for word in split]))
"Python 2.7 - find and replace from text file, using dictionary, to new text file","output = open('output_test_file.txt', 'w')"
How to write a python script that can communicate with the input and output of a swift executable?,process.stdin.flush()
How to make a numpy array from an array of arrays?,np.vstack(counts_array)
How to select ticks at n-positions in a log plot?,ax.xaxis.set_major_locator(ticker.LogLocator(numticks=6))
Convert python datetime to epoch with strftime,"datetime.datetime(2012, 4, 1, 0, 0).timestamp()"
re.split with spaces in python,"re.findall(' +|[^ ]+', s)"
How to select rows start with some str in pandas?,"df[~df.col.str.startswith(('t', 'c'))]"
Django: How to filter Users that belong to a specific group,qs = User.objects.filter(groups__name__in=['foo'])
Efficient way to shift a list in python,"shift([1, 2, 3], 14)"
python sorting two lists,"[list(x) for x in zip(*sorted(zip(list1, list2), key=itemgetter(0)))]"
Prevent numpy from creating a multidimensional array,"np.ndarray((2, 3), dtype=object)"
How to use Unicode characters in a python string,print('\u25b2')
Update and create a multi-dimensional dictionary in Python,d['js'].append({'other': 'thing'})
Returning millisecond representation of datetime in python,date_time_secs = time.mktime(datetimeobj.timetuple())
How do I format a number with a variable number of digits in Python?,"""""""One hundred and twenty three with three leading zeros {0:06}."""""".format(123)"
Sanitizing a file path in python,os.makedirs(path_directory)
Python MySQL Parameterized Queries,"c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s' % (param1, param2))"
median of pandas dataframe,df['dist'].median()
Dijkstra's algorithm in python,"{'E': 2, 'D': 1, 'G': 2, 'F': 4, 'A': 4, 'C': 3, 'B': 0}"
tuple digits to number conversion,"float('{0}.{1}'.format(a[0], ''.join(str(n) for n in a[1:])))"
Shape of array python,"m[:, (0)].reshape(5, 1).shape"
Arrows in matplotlib using mplot3d,ax.set_axis_off()
Python Extract data from file,words = line.split()
Pythonic way to check that the lengths of lots of lists are the same,"my_list = [[1, 2, 3], ['a', 'b'], [5, 6, 7]]"
String reverse in Python,print(''.join(x[::-1] for x in pattern.split(string)))
Initialize/Create/Populate a Dict of a Dict of a Dict in Python,"{'geneid': 'bye', 'tx_id': 'NR439', 'col_name1': '4.5', 'col_name2': 6.7}"
django filter by datetime on a range of dates,queryset.filter(created_at__gte=datetime.date.today())
UnicodeDecodeError when reading a text file,"fileObject = open('countable nouns raw.txt', 'rt', encoding='utf8')"
Format a datetime into a string with milliseconds,print(datetime.utcnow().strftime('%Y%m%d%H%M%S%f'))
How do you get the process ID of a program in Unix or Linux using Python?,os.getpid()
convert a list of booleans to string,"print(''.join(chr(ord('A') + i) if b else ' ' for i, b in enumerate(bools)))"
Python unicode in Mac os X terminal,print('\xd0\xb0\xd0\xb1\xd0\xb2\xd0\xb3\xd0\xb4')
How find values in an array that meet two conditions using Python,numpy.nonzero((a > 3) & (a < 8))
Python: split list of strings to a list of lists of strings by length with a nested comprehensions,"[['a', 'b'], ['ab'], ['abc']]"
Extracting just Month and Year from Pandas Datetime column (Python),df['mnth_yr'] = df['date_column'].apply(lambda x: x.strftime('%B-%Y'))
How can I split and parse a string in Python?,print(mystring.split(' '))
Filter Pyspark dataframe column with None value,df.filter('dt_mvmt is NULL')
Python: return the index of the first element of a list which makes a passed function true,"next((i for i, v in enumerate(l) if is_odd(v)))"