text
stringlengths 4
1.08k
|
|---|
pandas: sorting columns by their mean value,"df.reindex_axis(df.mean().sort_values().index, axis=1)"
|
need help using xpath in elementtree,e = element.findall('Items/Item/ItemAttributes/ListPrice/Amount')
|
"get rows of dataframe `df` where column `col1` has values `['men', 'rocks', 'mountains']`","df[df.Col1.isin(['men', 'rocks', 'mountains'])]"
|
"python 2.7 - find and replace from text file, using dictionary, to new text file","""""""abc abc abcd ab"""""".replace('abc', 'def')"
|
"get a list of words from a string `hello world, my name is...james the 2nd!` removing punctuation","re.compile('\\w+').findall('Hello world, my name is...James the 2nd!')"
|
python: define multiple variables of same type?,"levels = [{}, {}, {}]"
|
how to set a default string for raw_input?,i = input('Please enter name[Jack]:') or 'Jack'
|
print specific lines of multiple files in python,f.close()
|
removing duplicate characters from a string,""""""""""""".join(set(foo))"
|
add column to dataframe with default value,df['Name'] = 'abc'
|
how to find all possible sequences of elements in a list?,"list(permutations([2, 3, 4]))"
|
comparing order of 2 python lists,"list2 == sorted(list2, key=lambda c: list1.index(c))"
|
sorting json in python by a specific value,sorted_list_of_values = [item[1] for item in sorted_list_of_keyvalues]
|
python for increment inner loop,"list(range(0, 6, 2))"
|
convert a list of objects `list_name` to json string `json_string`,json_string = json.dumps([ob.__dict__ for ob in list_name])
|
match regex pattern 'a*?bc*?' on string 'aabcc' with dotall enabled,"re.findall('a*?bc*?', 'aabcc', re.DOTALL)"
|
json to model a class using django,"[{'model': 'myapp.user', 'pk': '89900', 'fields': {'name': 'Clelio de Paula'}}]"
|
set environment variable 'debussy' equal to 1,os.environ['DEBUSSY'] = '1'
|
for loop with custom steps in python,"list(range(0, 10, 3))"
|
sort a list of strings 'words' such that items starting with 's' come first.,"sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)"
|
"how to set ""step"" on axis x in my figure in matplotlib python 2.6.6?","plt.xticks([1, 2, 3, 4, 5])"
|
how to read a .xlsx file using the pandas library in ipython?,"dfs = pd.read_excel(file_name, sheetname=None)"
|
how do you perform basic joins of two rdd tables in spark using python?,"rdd2 = sc.parallelize([('foo', 4), ('bar', 5), ('bar', 6)])"
|
format floating point number `totalamount` to be rounded off to two decimal places and have a comma thousands' seperator,"print('Total cost is: ${:,.2f}'.format(TotalAmount))"
|
import a module 'a.b.c' with importlib.import_module in python 2,importlib.import_module('a.b.c')
|
"insert variables `(var1, var2, var3)` into sql statement 'insert into table values (?, ?, ?)'","cursor.execute('INSERT INTO table VALUES (?, ?, ?)', (var1, var2, var3))"
|
listing files from a directory using glob python,glob.glob('hello*.txt')
|
python regex pattern max length in re.compile?,stopword_pattern.match('1999')
|
python regex match date,match.group(1)
|
how to set null for integerfield instead of setting 0?,"age = models.IntegerField(blank=True, null=True)"
|
reverse a utf-8 string 'a',b = a.decode('utf8')[::-1].encode('utf8')
|
using chromedriver with selenium/python/ubuntu,driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver')
|
python 2.7 - write and read a list from file,out_file.write('\n'.join(data))
|
how can i split and parse a string in python?,mystring.split('_')[4]
|
initializing 2d lists in python: how to make deep copies of each row?,[([0.0] * 10) for _ in range(10)]
|
set the font 'purisa' of size 12 for a canvas' text item `k`,"canvas.create_text(x, y, font=('Purisa', 12), text=k)"
|
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]]"
|
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]"
|
how to properly quit a program in python,sys.exit(0)
|
python: how to use a list comprehension here?,[item['baz'] for foo in foos for item in foo['bar']]
|
parse raw http headers,print(request.headers['host'])
|
how do i run multiple python test cases in a loop?,unittest.main()
|
how can i get a list of all classes within current module in python?,"clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)"
|
django queryset filter for backwards related fields,Project.objects.filter(person_set__name='John')
|
how would i go about playing an alarm sound in python?,winsound.PlaySound('alert.wav')
|
how can i convert a binary to a float number,"struct.unpack('d', b8)[0]"
|
how to disable a widget in kivy?,MyApp().run()
|
how do i add a % symbol to my python script,"print('The average is: ' + format(average, ',.3f') + '%')"
|
"generate all permutations of a list `[1, 2, 3]`","itertools.permutations([1, 2, 3])"
|
how can i select 'last business day of the month' in pandas?,"pd.date_range('1/1/2014', periods=12, freq='BM')"
|
"how to make a python script ""pipeable"" in bash?",sys.stdout.write(line)
|
"split unicode string ""raz dva tri"" into words",'\u0440\u0430\u0437 \u0434\u0432\u0430 \u0442\u0440\u0438'.split()
|
python pandas- merging two data frames based on an index order,df2['cumcount'] = df2.groupby('val1').cumcount()
|
convert list of strings to dictionary,"{' Failures': '0', 'Tests run': '1', ' Errors': '0'}"
|
how do you round up a number in python?,print(math.ceil(4.2))
|
split strings with multiple delimiters?,"""""""a;bcd,ef g"""""".replace(';', ' ').replace(',', ' ').split()"
|
subtracting the current and previous item in a list,"[(y - x) for x, y in zip(L, L[1:])]"
|
"convert the string '0,1,2' to a list of integers","[int(x) for x in '0,1,2'.split(',')]"
|
how do i convert a unicode to a string at the python level?,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9').decode('utf8')"
|
case sensitive string replacement in python,"""""""Abc"""""".translate(maketrans('abcABC', 'defDEF'))"
|
how to download file from ftp?,ftp.quit()
|
writing unicode text to a text file?,print(f.read().decode('utf8'))
|
how to get indices of n maximum values in a numpy array?,ind[np.argsort(a[ind])]
|
reading data from text file with missing values,"genfromtxt('missing1.dat', delimiter=',', filling_values=99)"
|
split string on a number of different characters,"re.split('[ .]', 'a b.c')"
|
add two lists in python,"[('%s+%s' % x) for x in zip(a, b)]"
|
python: logging typeerror: not all arguments converted during string formatting,"logging.info(__('date={}', date))"
|
mitm proxy over ssl hangs on wrap_socket with client,connection.send('HTTP/1.0 200 OK\r\n\r\n')
|
add column `d` to index of dataframe `df`,"df.set_index(['d'], append=True)"
|
multiple element indexing in multi-dimensional array,"array([0.49482768, 0.53013301, 0.4485054, 0.49516017, 0.47034123])"
|
pandas: change data type of columns,"pd.to_numeric(s, errors='ignore')"
|
sort a list of dictionaries `list_of_dct` by values in an order `order`,"sorted(list_of_dct, key=lambda x: order.index(list(x.values())[0]))"
|
matplotlib in python - drawing shapes and animating them,plt.show()
|
how do i remove \n from my python dictionary?,"key, value = line.rstrip('\n').split(',')"
|
print javascript exceptions in a qwebview to the console,sys.exit(app.exec_())
|
how to tweak the nltk sentence tokenizer,"text = text.replace('?""', '? ""').replace('!""', '! ""').replace('.""', '. ""')"
|
python how to get every first element in 2 dimensional list,[x[0] for x in a]
|
how to append a dictionary to a pandas dataframe?,"df.append(new_df, ignore_index=True)"
|
parsing a date in python without using a default,"datetime.datetime(ddd.year, ddd.month, ddd.day)"
|
how to store os.system() output in a variable or a list in python,"direct_output = subprocess.check_output('ls', shell=True)"
|
congruency table in pandas (pearson correlation between each row for every row pair),"df.corr().mask(np.equal.outer(df.index.values, df.columns.values))"
|
how to draw directed graphs using networkx in python?,"nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)"
|
python regex -- extraneous matchings,"re.findall('-|\\+=|==|=|\\+|[^-+=\\s]+', 'hello-+==== =+ there')"
|
mapping over values in a python dictionary,"my_dictionary = {k: f(v) for k, v in list(my_dictionary.items())}"
|
split a python string with nested separated symbol,"[k for j in re.findall(""(\\d)|'([^']*)'"", i) for k in j if k]"
|
how to remove square brackets from list in python?,"print(', '.join(map(str, LIST)))"
|
get modification time of file `path`,os.path.getmtime(path)
|
setting default value for integer field in django models,models.PositiveSmallIntegerField(default=0)
|
iterate over a dictionary `d` in sorted order,it = iter(sorted(d.items()))
|
convert string representation `s2` of binary string rep of integer to floating point number,"struct.unpack('d', struct.pack('Q', int(s2, 0)))[0]"
|
how to convert integer into date object python?,s = date.strftime('%Y%m%d')
|
get data of columns with null values in dataframe `df`,df[pd.isnull(df).any(axis=1)]
|
linear regression with pymc3 and belief,"pymc3.traceplot(trace, vars=['alpha', 'beta', 'sigma'])"
|
python convert list to dictionary,"zip(['a', 'c', 'e'], ['b', 'd'])"
|
how can i check a python unicode string to see that it *actually* is proper unicode?,foo.decode('utf8').encode('utf8')
|
"call a python script ""test2.py""","exec(compile(open('test2.py').read(), 'test2.py', 'exec'))"
|
remove duplicate chars using regex?,"re.sub('([a-z])\\1+', '\\1', 'ffffffbbbbbbbqqq')"
|
python pandas - re-ordering columns in a dataframe based on column name,"df.reindex_axis(sorted(df.columns), axis=1)"
|
create a new 2d array with 2 random rows from array `a`,"A[(np.random.choice(A.shape[0], 2, replace=False)), :]"
|
filter common sub-dictionary keys in a dictionary,set.intersection(*(set(x) for x in d.values()))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.