text
stringlengths
4
1.08k
How can I check a Python unicode string to see that it *actually* is proper Unicode?,foo.decode('utf8').encode('utf8')
Matplotlib: filled contour plot with transparent colors,"ax.contour(x, y, z, levels, cmap=cmap, norm=norm, antialiased=True)"
numpy: efficiently reading a large array,"a = numpy.fromfile('filename', dtype=numpy.float32)"
Find a specific tag with BeautifulSoup,"soup.findAll('div', style='width=300px;')"
Removing the first folder in a path,os.path.join(*x.split(os.path.sep)[2:])
How to make a timer program in Python,time.sleep(1)
Divide two lists in python,"[(x / y) for x, y in zip(a, b)]"
Python - Remove dictionary from list if key is equal to value,a = [x for x in a if x['link'] not in b]
How do you make the linewidth of a single line change as a function of x in matplotlib?,plt.show()
How can I get the output of a matplotlib plot as an SVG?,plt.savefig('test.svg')
How do I get user IP address in django?,get_client_ip(request)
How to replace (or strip) an extension from a filename in Python?,print(os.path.splitext('/home/user/somefile.txt')[0] + '.jpg')
Interoperating with Django/Celery From Java,CELERY_ROUTES = {'mypackage.myclass.runworker': {'queue': 'myqueue'}}
R dcast equivalent in python pandas,"pd.crosstab(index=df['values'], columns=[df['convert_me'], df['age_col']])"
How to subset a data frame using Pandas based on a group criteria?,df.loc[df.groupby('User')['X'].transform(sum) == 0]
Sorting the content of a dictionary by the value and by the key,"sorted(list(d.items()), key=lambda x: (x[1], x[0]))"
count how many of an object type there are in a list Python,"sum(isinstance(x, int) for x in a)"
How to retrieve only arabic texts from a string using regular expression?,"print(re.findall('[u0600-u06FF]+', my_string))"
How to retrieve only arabic texts from a string using regular expression?,"print(re.findall('[0-u]+', my_string))"
Django Get Latest Entry from Database,Status.objects.order_by('id')[0]
Django - How to sort queryset by number of character in a field,MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length')
Index the first and the last n elements of a list,l[:3] + l[-3:]
How do I insert a space after a certain amount of characters in a string using python?,"""""""this isar ando msen tenc e"""""""
"Python, zip multiple lists where one list requires two items each","list(zip(a, b, zip(c[0::2], c[1::2]), d))"
How to reset index in a pandas data frame?,df = df.reset_index(drop=True)
increase the linewidth of the legend lines in matplotlib,plt.show()
django models selecting single field,"Employees.objects.values_list('eng_name', flat=True)"
Python: comprehension to compose two dictionaries,"result = {k: d2.get(v) for k, v in list(d1.items())}"
Python - Move elements in a list of dictionaries to the end of the list,"sorted(lst, key=lambda x: x['language'] != 'en')"
x11 forwarding with paramiko,ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
python: MYSQLdb. how to get columns name without executing select * in a big table?,cursor.execute('SELECT * FROM table_name WHERE 1=0')
Python - Remove any element from a list of strings that is a substring of another element,"set(['looked', 'resting', 'spit'])"
Python - how to sort a list of numerical values in ascending order,"sorted(['10', '3', '2'])"
How do I tell matplotlib that I am done with a plot?,plt.cla()
Copy keys to a new dictionary (Python),set(d.keys())
How to obtain values of request variables using Python and Flask,first_name = request.args.get('firstname')
arbitrary number of arguments in a python function,return args[-1] + mySum(args[:-1])
How do I convert an array to string using the jinja template engine?,{{tags | join(' ')}}
Flipping the boolean values in a list Python,"[False, False, True]"
Automatically setting y-axis limits for bar graph using matplotlib,plt.show()
Find Average of Every Three Columns in Pandas dataframe,"res = df.resample('Q', axis=1).mean()"
Python - Start a Function at Given Time,"threading.Timer(delay, self.update).start()"
How to construct a dictionary from two dictionaries in python?,"{'y2': 2, 'y1': 1, 'x2': 2, 'x3': 3, 'y3': 3, 'x1': 1}"
Return a list of weekdays,weekdays('Wednesday')
Pandas: Create another column while splitting each row from the first column,"df['new_column'] = df['old_column'].apply(lambda x: '#' + x.replace(' ', ''))"
Regex: How to match words without consecutive vowels?,"[w for w in open('file.txt') if not re.search('[aeiou]{2}', w)]"
Add a tuple to a specific cell of a pandas dataframe,tempDF['newTuple'] = 's'
Using Python String Formatting with Lists,""""""", """""".join(['%.2f'] * len(x))"
Python Pandas: Convert Rows as Column headers,"medals.reindex_axis(['Gold', 'Silver', 'Bronze'], axis=1)"
Grouping dates in Django,return qs.values('date').annotate(Sum('amount')).order_by('date')
Python Pandas - How to flatten a hierarchical index in columns,df.columns = df.columns.get_level_values(0)
How can I zip file with a flattened directory structure using Zipfile in Python?,"archive.write(pdffile, os.path.basename(pdffile))"
How to set the unit length of axis in matplotlib?,plt.show()
Pandas changing cell values based on another cell,"df.fillna(method='ffill', inplace=True)"
Pandas DataFrame Groupby two columns and get counts,"df.groupby(['col5', 'col2']).size()"
Getting the first elements per row in an array in Python?,t = tuple(x[0] for x in s)
tkinter: how to use after method,root.mainloop()
how to slice a dataframe having date field as index?,df = df.set_index(['TRX_DATE'])
copying one file's contents to another in python,"shutil.copy('file.txt', 'file2.txt')"
How to create a density plot in matplotlib?,plt.show()
Changing marker's size in matplotlib,"scatter(x, y, s=500, color='green', marker='h')"
Python: How do I format a date in Jinja2?,{{car.date_of_manufacture | datetime}}
How do I use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*\\Z', 'A\n')"
Python: How to order a list based on another list,"sorted(list1, key=lambda x: wordorder.get(x.split('-')[1], len(wordorder)))"
How to split a byte string into separate bytes in python,"['\x00\x00', '\x00\x00', '\x00\x00']"
Pycurl keeps printing in terminal,"p.setopt(pycurl.WRITEFUNCTION, lambda x: None)"
Fastest way to remove all multiple occurrence items from a list?,list_of_tuples = [tuple(k) for k in list_of_lists]
How to reverse tuples in Python?,x[::-1]
Sorting a defaultdict by value in python,"sorted(list(u.items()), key=lambda v: v[1])"
URL encoding in python,urllib.parse.quote(s.encode('utf-8'))
Set value for particular cell in pandas DataFrame,df['x']['C'] = 10
How to check whether elements appears in the list only once in python?,len(set(a)) == len(a)
Set execute bit for a file using python,"os.chmod('my_script.sh', 484)"
How to tell if string starts with a number?,"strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))"
How to write a generator that returns ALL-BUT-LAST items in the iterable in Python?,"list(allbutlast([1, 2, 3]))"
Python 3: Multiply a vector by a matrix without NumPy,"np.dot([1, 0, 0, 1, 0, 0], [[0, 1], [1, 1], [1, 0], [1, 0], [1, 1], [0, 1]])"
how do I halt execution in a python script?,sys.exit()
type conversion in python from int to float,data_df['grade'] = data_df['grade'].astype(float).astype(int)
How can I insert data into a MySQL database?,cursor.execute('DROP TABLE IF EXISTS anooog1')
Python datetime to string without microsecond component,datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
How to create a Manhattan plot with matplotlib in python?,ax.set_xlabel('Chromosome')
How to convert a string to a function in python?,raise ValueError('invalid input')
how to convert 2d list to 2d numpy array?,a = np.array(a)
How do I find the most common words in multiple separate texts?,"['data1', 'data3', 'data5', 'data2']"
How to get a list of matchable characters from a regex class,"print(re.findall(pattern, x))"
Pandas: Subtract row mean from each element in row,"df.sub(df.mean(axis=1), axis=0)"
join list of lists in python,[j for i in x for j in i]
How to create ternary contour plot in Python?,plt.show()
Django Rest Framework - How to test ViewSet?,"self.assertEqual(response.status_code, 200)"
Pandas Plotting with Multi-Index,"summed_group.unstack(level=0).plot(kind='bar', subplots=True)"
rename index of a pandas dataframe,"df.ix['c', '3']"
Pythonic way to access arbitrary element from dictionary,return next(iter(dictionary.values()))
Reshaping Pandas dataframe by months,"df['values'].groupby([df.index.year, df.index.strftime('%b')]).sum().unstack()"
Read file with timeout in Python,"os.read(f.fileno(), 50)"
How to find the count of a word in a string?,input_string.count('Hello')
How to split 1D array into 2D array in NumPy by splitting the array at the last element?,"np.split(a, [-1])"
How to remove gaps between subplots in matplotlib?,"plt.subplots_adjust(wspace=0, hspace=0)"
How does python do string magic?,""""""""""""".join(['x', 'x', 'x'])"
Anchor or lock text to a marker in Matplotlib,"ax.annotate(str(y), xy=(x, y), xytext=(-5.0, -5.0), textcoords='offset points')"
String split with indices in Python,"c = [(m.start(), m.end() - 1) for m in re.finditer('\\S+', a)]"