text
stringlengths 4
1.08k
|
|---|
How do I print a Celsius symbol with matplotlib?,ax.set_xlabel('Temperature (\u2103)')
|
How to print variables without spaces between values,"print('Value is ""' + str(value) + '""')"
|
How to reduce queries in django model has_relation method?,Person.objects.exclude(pets=None)
|
Python - How to call bash commands with pipe?,"subprocess.call('tar c my_dir | md5sum', shell=True)"
|
syntax for creating a dictionary into another dictionary in python,"d['dict3'] = {'spam': 5, 'ham': 6}"
|
python dict to numpy structured array,"numpy.array([(key, val) for key, val in result.items()], dtype)"
|
writing a log file from python program,logging.debug('next line')
|
how to multiply multiple columns by a column in Pandas,"df[['A', 'B']].multiply(df['C'], axis='index')"
|
what's a good way to combinate through a set?,list(powerset('abcd'))
|
"Pandas read_csv expects wrong number of columns, with ragged csv file","pd.read_csv('D:/Temp/tt.csv', names=list('abcdef'))"
|
Updating a matplotlib bar graph?,plt.show()
|
How to get week number in Python?,"datetime.date(2010, 6, 16).isocalendar()[1]"
|
Python pandas: check if any value is NaN in DataFrame,df.isnull().values.any()
|
Python cant find module in the same folder,sys.path.append('/path/to/2014_07_13_test')
|
Break string into list elements based on keywords,"['Na', '2', 'S', 'O', '4', 'Mn', 'O', '4']"
|
How to filter a dictionary in Python?,"{i: 'updated' for i, j in list(d.items()) if j != 'None'}"
|
How to repeat Pandas data frame?,pd.concat([x] * 5)
|
Python list comprehension for loops,[(x + y) for x in '12345' for y in 'ab']
|
Sorting a list of dicts by dict values,"sorted(a, key=lambda i: list(i.values())[0], reverse=True)"
|
Get function name as a string in python,print(func.__name__)
|
How do I create a file in python without overwriting an existing file,"fd = os.open('x', os.O_WRONLY | os.O_CREAT | os.O_EXCL)"
|
what is a quick way to delete all elements from a list that do not satisfy a constraint?,[x for x in lst if fn(x) != 0]
|
"in Python, How to join a list of tuples into one list?",list(itertools.chain(*a))
|
Python Requests encoding POST data,headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
|
How do I use a dictionary to update fields in Django models?,Book.objects.create(**d)
|
How to pass a dictionary as value to a function in python,"{'physics': 1}, {'volume': 1, 'chemistry': 1}, {'chemistry': 1}"
|
How do you remove the column name row from a pandas DataFrame?,"df.to_csv('filename.tsv', sep='\t', index=False)"
|
Python - sum values in dictionary,sum([item['gold'] for item in example_list])
|
Change a string of integers separated by spaces to a list of int,x = [int(i) for i in x.split()]
|
How to merge two DataFrames into single matching the column values,"pd.concat([distancesDF, datesDF.dates], axis=1)"
|
How to use lxml to find an element by text?,"e = root.xpath('.//a[text()=""TEXT A""]')"
|
"How to set a variable to be ""Today's"" date in Python/Pandas",dt.datetime.today().strftime('%m/%d/%Y')
|
matplotlib: Set markers for individual points on a line,"plt.plot(list(range(10)), '--bo')"
|
How to retrieve table names in a mysql database with Python and MySQLdb?,cursor.execute('SHOW TABLES')
|
how can I use the python imaging library to create a bitmap,img.show()
|
tricky string matching,"['a', 'foobar', 'FooBar', 'baz', 'golf', 'CART', 'Foo']"
|
Pandas: how to increment a column's cell value based on a list of ids,"my_df.loc[my_df['id'].isin(ids), 'other_column'] += 1"
|
How to calculate percentage of sparsity for a numpy array/matrix?,np.isnan(a).sum() / np.prod(a.shape)
|
Best way to plot an angle between two lines in Matplotlib,"ax.set_ylim(0, 5)"
|
PLS-DA algorithm in python,mypred = myplsda.predict(Xdata)
|
How to plot blurred points in Matplotlib,plt.show()
|
Getting pandas dataframe from list of nested dictionaries,"pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T"
|
Python - Get Yesterday's date as a string in YYYY-MM-DD format,(datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
|
Use groupby in Pandas to count things in one column in comparison to another,"df.pivot_table(index='Event', columns='Status', aggfunc=len, fill_value=0)"
|
Regex match even number of letters,re.compile('(.)\\1')
|
Python Decimals format,"""""""{0:.3g}"""""".format(num)"
|
Convert list of strings to int,"[map(int, sublist) for sublist in lst]"
|
Random strings in Python,return ''.join(random.choice(string.lowercase) for i in range(length))
|
format strings and named arguments in Python,"""""""{0} {1}"""""".format(10, 20)"
|
How to remove the space between subplots in matplotlib.pyplot?,plt.show()
|
How to erase the file contents of text file in Python?,"open('filename', 'w').close()"
|
join list of lists in python,print(list(itertools.chain.from_iterable(a)))
|
How do I find the first letter of each word?,output = ''.join(item[0].upper() for item in input.split())
|
python sorting two lists,"[list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))]"
|
Best way to split a DataFrame given an edge,df.groupby((df.a == 'B').shift(1).fillna(0).cumsum())
|
Python - read text file with weird utf-16 format,"file = io.open('data.txt', 'r', encoding='utf-16-le')"
|
Sort a list in python based on another sorted list,"sorted(unsorted_list, key=presorted_list.index)"
|
applying functions to groups in pandas dataframe,df.groupby('type').apply(lambda x: np.mean(np.log2(x['v'])))
|
Python - Sum 4D Array,M.sum(axis=0).sum(axis=0)
|
Regex match even number of letters,re.compile('^([^A]*)AA([^A]|AA)*$')
|
Joining a list that has Integer values with Python,"print(', '.join(str(x) for x in list_of_ints))"
|
Get index of the top n values of a list in python,"sorted(list(range(len(a))), key=lambda i: a[i], reverse=True)[:2]"
|
Convert unicode string to byte string,'\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'.encode('latin-1')
|
"Create new list by taking first item from first list, and last item from second list","[value for pair in zip(a, b[::-1]) for value in pair]"
|
How to get everything after last slash in a URL?,"url.rsplit('/', 1)"
|
Replace first occurence of string,"'longlongTESTstringTEST'.replace('TEST', '?', 1)"
|
flask : how to architect the project with multiple apps?,app.run()
|
filtering grouped df in pandas,grouped.filter(lambda x: len(x) > 1)
|
Python: Lambda function in List Comprehensions,[(lambda x: x * x)(x) for x in range(10)]
|
"How to print a list with integers without the brackets, commas and no quotes?","print(''.join(map(str, data)))"
|
"How to make a Python string out of non-ascii ""bytes""",""""""""""""".join(chr(i) for i in myintegers)"
|
How to serve static files in Flask,app.run()
|
How to change the font size on a matplotlib plot,matplotlib.rcParams.update({'font.size': 22})
|
How to check if a template exists in Django?,"django.template.loader.select_template(['custom_template', 'default_template'])"
|
Remove string between 2 characters from text string,"re.sub('\\[.*?\\]', '', 'abcd[e]yth[ac]ytwec')"
|
Creating a 2d matrix in python,x = [[None for _ in range(5)] for _ in range(6)]
|
Python: find index of first digit in string?,"[(i, c) for i, c in enumerate('xdtwkeltjwlkejt7wthwk89lk') if c.isdigit()]"
|
Python: sorting dictionary of dictionaries,"sorted(list(dic.items()), key=lambda x: x[1]['Fisher'], reverse=True)"
|
Sorting a defaultdict by value in python,"sorted(list(d.items()), key=lambda k_v: k_v[1])"
|
How to read a .xlsx file using the pandas Library in iPython?,"dfs = pd.read_excel(file_name, sheetname=None)"
|
What's the easiest way to convert a list of hex byte strings to a list of hex integers?,"[int(x, 16) for x in L]"
|
Accessing elements of python dictionary,dict['Apple']['American']
|
Pythonic way to append list of strings to an array,""""""""""""".join(entry_list)"
|
How can I check if a date is the same day as datetime.today()?,yourdatetime.date() == datetime.today().date()
|
How to group DataFrame by a period of time?,df.groupby(df.index.map(lambda t: t.minute))
|
matplotlib scatter plot with different markers and colors,plt.show()
|
How to make PyQt window state to maximised in pyqt,self.showMaximized()
|
Pandas - conditionally select column based on row value,"pd.concat([foo['Country'], z], keys=['Country', 'z'], axis=1)"
|
how to get tuples from lists using list comprehension in python,"[(i, j) for i, j in zip(lst, lst2)]"
|
How do I authenticate a urllib2 script in order to access HTTPS web services from a Django site?,"req.add_header('Referer', login_url)"
|
A list as a key for PySpark's reduceByKey,"rdd.map(lambda k_v: (frozenset(k_v[0]), k_v[1])).groupByKey().collect()"
|
Python: filter list of list with another list,result = [x for x in list_a if x[0] in list_b]
|
Using INSERT with a PostgreSQL Database using Python,conn.commit()
|
Find the row indexes of several values in a numpy array,np.where(out.ravel())[0]
|
How to subset a dataset in pandas dataframe?,df.groupby('ID').head(4)
|
How to remove decimal points in pandas,df.round()
|
How do I delete a row in a numpy array which contains a zero?,"a[np.all(a != 0, axis=1)]"
|
Python: how to get rid of spaces in str(dict)?,"str({'a': 1, 'b': 'as df'}).replace(': ', ':').replace(', ', ',')"
|
ValueError: setting an array element with a sequence,"numpy.array([[1, 2], [2, [3, 4]]])"
|
Python Regex Get String Between Two Substrings,"re.findall(""api\\('(.*?)'"", ""api('randomkey123xyz987', 'key', 'text')"")"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.