text stringlengths 4 1.08k |
|---|
can i get json to load into an ordereddict in python?,"data = json.load(open('config.json'), object_pairs_hook=OrderedDict)" |
remove duplicated items from list of lists `testdata`,"list(map(list, set(map(lambda i: tuple(i), testdata))))" |
how do i get the whole content between two xml tags in python?,"tostring(element).split('>', 1)[1].rsplit('</', 1)[0]" |
create a permutation with same autocorrelation,"np.corrcoef(x[0:len(x) - 1], x[1:])[0][1]" |
beautifulsoup find all tags with attribute 'name' equal to 'description',soup.findAll(attrs={'name': 'description'}) |
parsing html to get text inside an element,"print(soup.find('span', {'class': 'UserName'}).text)" |
is there a matplotlib equivalent of matlab's datacursormode?,"plt.subplot(2, 1, 2)" |
terminate the program,sys.exit() |
"adding a 1-d array `[1, 2, 3, 4, 5, 6, 7, 8, 9]` to a 3-d array `np.zeros((6, 9, 20))`","np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])[(None), :, (None)]" |
python / remove special character from string,"re.sub('[^a-zA-Z0-9-_*.]', '', my_string)" |
matplotlib.animation: how to remove white margin,"fig.set_size_inches(w, h, forward=True)" |
how do i abort the execution of a python script?,sys.exit('aa! errors!') |
how to extract the n-th elements from a list of tuples in python?,[x[1] for x in elements] |
pandas: transforming the dataframegroupby object to desired format,df = df.reset_index() |
make a 0.1 seconds time delay,sleep(0.1) |
how to use a file in a hadoop streaming job using python?,"f = open('user_ids', 'r')" |
create list of single item repeated n times in python,"[['x'], ['x'], ['x'], ['x']]" |
simple way to append a pandas series `a` and `b` with same index,"pd.concat([a, b], ignore_index=True)" |
"how to decode url to path in python, django","urllib.parse.quote('/static/media/uploads/gallery/Marrakech, Morocco_be3Ij2N.jpg')" |
check if string contains a certain amount of words of another string,x = [x for x in b.split() if x in a.split()] |
how to assign equal scaling on the x-axis in matplotlib?,ax.set_xticklabels(nonRepetitive_x) |
appending column totals to a pandas dataframe,df['Total'] = df.sum(axis=1) |
python3: conditional extraction of keys from a dictionary with comprehension,"[key for key, val in list(dct.items()) if val == True]" |
how to get environment from a subprocess in python,proc.communicate() |
python3: conditional extraction of keys from a dictionary with comprehension,"[key for key, val in list(dct.items()) if val]" |
how do i transform a multi-level list into a list of strings in python?,[''.join(x) for x in a] |
update all values associated with key `i` to string 'updated' if value `j` is not equal to 'none' in dictionary `d`,"{i: 'updated' for i, j in list(d.items()) if j != 'None'}" |
how to run a python script from idle interactive shell?,"subprocess.call(['python', 'helloworld.py'])" |
django return redirect() with parameters,"url('^link/(?P<backend>\\w+?)/$', my_function)" |
how to create inline objects with properties in python?,"obj = type('obj', (object,), {'propertyName': 'propertyValue'})" |
"remove repeating tuples from a list, depending on the values in the tuples","[(i, max(j)) for i, j in list(d.items())]" |
extract string from between quotations,"re.findall('""([^""]*)""', 'SetVariables ""a"" ""b"" ""c"" ')" |
confusing with the usage of regex in python,"re.findall('(?:[a-z])*', '123abc789')" |
utf in python regex,re.compile('\u2013') |
delete self-contained digits from string `s`,"s = re.sub('^\\d+\\s|\\s\\d+\\s|\\s\\d+$', ' ', s)" |
create multiple columns in pandas dataframe from one function,"df[['IV', 'Vega']] = df.apply(newtonRap, axis=1)" |
argparse: two positional arguments with nargs='+',"parser.add_argument('input2', nargs='+', type=int)" |
python: how to convert currency to decimal?,cents_int = int(round(float(dollars.strip('$')) * 100)) |
python: confusions with urljoin,"urljoin('http://some/more/', 'thing')" |
flask-sqlalchemy: how to conditionally insert or update a row,db.session.commit() |
apply itertools.product to elements of a list of lists `arrays`,list(itertools.product(*arrays)) |
convert dataframe `df` to integer-type sparse object,df.to_sparse(0) |
is it possible to have multiple statements in a python lambda expression?,"(lambda x, f: list(y[1] for y in f(x)))(lst, lambda x: (sorted(y) for y in x))" |
exit script,sys.exit() |
keep only date part when using pandas.to_datetime,df['just_date'] = df['dates'].dt.date |
numpy element-wise multiplication of an array and a vector,"np.allclose(a, b)" |
"how do i get a string format of the current date time, in python?","datetime.datetime.now().strftime('%I:%M%p on %B %d, %Y')" |
get count of values in numpy array `a` that are between values `25` and `100`,((25 < a) & (a < 100)).sum() |
how to remove leading and trailing spaces from strings in a python list,row = [x.strip() for x in row] |
how can i get value of the nested dictionary using immutablemultidict on flask?,"['US', 'US', 'UK']" |
get the string within brackets in python,"m = re.search('\\[(\\w+)\\]', s)" |
how do i merge a 2d array in python into one string with list comprehension?,""""""","""""".join(str(item) for innerlist in outerlist for item in innerlist)" |
modular addition in python,x = (x + y) % 48 |
reordering list of dicts arbitrarily in python,"ordered = sorted(lst, key=lambda d: [2, 3, 1, 4].index(int(d['id'])))" |
inserting a string into a list without getting split into characters,"list.insert(0, 'foo')" |
beautifulsoup find string 'python jobs' in html body `body`,soup.body.findAll(text='Python Jobs') |
python sum of ascii values of all characters in a string,sum(bytearray('abcdefgh')) |
changing the values of the diagonal of a matrix in numpy,A.ravel()[A.shape[1] * i:A.shape[1] * (i + A.shape[1]):A.shape[1] + 1] |
how to check if all values in the columns of a numpy matrix are the same?,"np.all(a == a[(0), :], axis=0)" |
how to compare value of 2 fields in django queryset?,players = Player.objects.filter(batting__gt=F('bowling')) |
python mysql connector - unread result found when using fetchone,cursor = cnx.cursor(buffered=True) |
get data of dataframe `df` where the sum of column 'x' grouped by column 'user' is equal to 0,df.loc[df.groupby('User')['X'].transform(sum) == 0] |
get total number of values in a nested dictionary `food_colors`,sum(len(x) for x in list(food_colors.values())) |
django - how to create a file and save it to a model's filefield?,"self.license_file.save(new_name, ContentFile('A string with the file content'))" |
dictionary as table in django template,"['Birthday:', 'Education', 'Job:', 'Child Sex:']" |
how do you extract a column from a multi-dimensional array?,"[1, 2, 3]" |
hashing (hiding) strings in python,hash('moo') |
how to execute an .sql file in pymssql,cursor.close() |
"in numpy, what is the fastest way to multiply the second dimension of a 3 dimensional array by a 1 dimensional array?","A * B[:, (np.newaxis)]" |
how to check if all values in the columns of a numpy matrix are the same?,"np.equal.reduce([False, 0, 1])" |
pandas dataframe with 2-rows header and export to csv,"df.to_csv('test.csv', mode='a', index=False, header=False)" |
python pandas date read_table,"pandas.io.parsers.read_csv('input.csv', parse_dates=[[0, 1, 2]], header=None)" |
"how to store data frame using pandas, python",df.to_pickle(file_name) |
format strings and named arguments in python,"""""""{1} {ham} {0} {foo} {1}"""""".format(10, 20, foo='bar', ham='spam')" |
how can i build a python datastructure by reading it from a file,"[1, 2, 3, 4]" |
"print '[1, 2, 3]'","print('[%s, %s, %s]' % (1, 2, 3))" |
play the wav file 'sound.wav',"winsound.PlaySound('sound.wav', winsound.SND_FILENAME)" |
sum of all values in a python dict `d`,sum(d.values()) |
python: split numpy array based on values in the array,"np.diff(arr[:, (1)])" |
"if i have this string in python, how do i decode it?",urllib.parse.unquote(urllib.parse.unquote(s)) |
python: sorting a dictionary of lists,"[y[1] for y in sorted([(myDict[x][2], x) for x in list(myDict.keys())])]" |
how to convert numpy.recarray to numpy.array?,"a.astype([('x', '<f8'), ('y', '<f8'), ('z', '<f8')]).view('<f8')" |
how do i get the different parts of a flask request's url?,request.url |
get the name of the os,print(os.name) |
how to create a dictionary with certain specific behaviour of values,"{'A': 4, 'B': 1, 'C': 1}" |
how to modify the elements in a list within list,"L = [[1, 2, 3], [4, 5, 6], [3, 4, 6]]" |
how to use bower package manager in django app?,{'directory': 'app/static/bower_components'} |
get a dataframe `df2` that contains all the columns of dataframe `df` that do not end in `prefix`,"df2 = df.ix[:, (~df.columns.str.endswith('prefix'))]" |
how to insert scale bar in a map in matplotlib,plt.show() |
"utf-8 in python logging, how?",logging._defaultFormatter = logging.Formatter('%(message)s') |
how to achieve two separate list of lists from a single list of lists of tuple with list comprehension?,"[[y for x, y in sublist] for sublist in l]" |
inherit from class `executive`,"super(Executive, self).__init__(*args)" |
how do i plot a step function with matplotlib in python?,plt.show() |
extract item from list of dictionaries,[d for d in a if d['name'] == 'pluto'] |
how to count the nan values in the column in panda data frame,df.isnull().sum() |
create pdf with tooltips in python,plt.savefig('tooltips.pdf') |
mapping over values in a python dictionary,"my_dictionary = dict(map(lambda k_v: (k_v[0], f(k_v[1])), iter(my_dictionary.items())))" |
"throw an assertion error with message ""unexpected value of 'distance'!"", distance","raise AssertionError(""Unexpected value of 'distance'!"", distance)" |
possible to generate data with while in list comprehension,print([i for i in range(5)]) |
group by multiple time units in pandas data frame,dfts = df.set_index('date_time') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.