text
stringlengths 4
1.08k
|
|---|
"is it possible to add <key, value> pair at the end of the dictionary in python",dict(mylist)
|
print a progress-bar processing in python,sys.stdout.flush()
|
pandas dataframe groupby two columns and get counts,"df.groupby(['col5', 'col2']).size().reset_index().groupby('col2')[[0]].max()"
|
"running a python debug session from a program, not from the console",p.communicate('continue')
|
how to print more than one value in a list comprehension?,"output = [[word, len(word), word.upper()] for word in sent]"
|
"get the zip output as list from the lists `[1, 2, 3]`, `[4, 5, 6]`, `[7, 8, 9]`","[list(a) for a in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])]"
|
get the value at index 1 for each tuple in the list of tuples `l`,[x[1] for x in L]
|
how do i remove rows from a dataframe?,"print(df.ix[i, 'attr'])"
|
select rows from a dataframe based on values in a column in pandas,df.loc[~df['column_name'].isin(some_values)]
|
how to get field type string from db model in django,model._meta.get_field('g').get_internal_type()
|
split a list into nested lists on a value,"[[1, 4], [6], [3], [4]]"
|
dynamically escape % sign and brackets { } in a string,"s = s.replace('{', '{{').replace('}', '}}')"
|
rfc 1123 date representation in python?,"datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')"
|
how to plot arbitrary markers on a pandas data series?,ts.plot(marker='.')
|
django: how to filter model field values with out space?,City.objects.filter(name__nospaces='newyork')
|
concatenating values in `list1` to a string,str1 = ''.join(list1)
|
python - convert datetime to varchar/string,"d = datetime.strptime(date_str, '%Y-%m-%d')"
|
efficiently select rows that match one of several values in pandas dataframe,"df[df.Name.isin(['Alice', 'Bob'])]"
|
converting python dictionary to list,list(dict.items())
|
"how to set 'auto' for upper limit, but keep a fixed lower limit with matplotlib.pyplot",plt.gca().set_xlim(left=0)
|
create 3d array using python,"numpy.zeros((i, j, k))"
|
replace string ' and ' in string `stuff` with character '/',"stuff.replace(' and ', '/')"
|
splitting strings in python,"re.findall('\\[[^\\]]*\\]|""[^""]*""|\\S+', s)"
|
regex python adding characters after a certain word,"re.sub('(get)', '\\1@', text)"
|
sort json `ips_data` by a key 'data_two',"sorted_list_of_keyvalues = sorted(list(ips_data.items()), key=item[1]['data_two'])"
|
"get mean of columns `2, 5, 6, 7, 8` for all rows in dataframe `df`","df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=1)"
|
nltk - counting frequency of bigram,bigram_measures = nltk.collocations.BigramAssocMeasures()
|
strip html from strings,"re.sub('<[^<]+?>', '', text)"
|
watch for a variable change in python,pdb.set_trace()
|
print a variable selected by a random number,random_choice = random.choice(choices)
|
getting a list of all subdirectories in the current directory,[x[0] for x in os.walk(directory)]
|
parsing a complex logical expression in pyparsing in a binary tree fashion,"['A', 'and', 'B', 'and', 'C']"
|
how to replace unicode characters in string with something else python?,"str.decode('utf-8').replace('\u2022', '*')"
|
rounding entries in a pandas dafaframe,"df.round({'Alabama_exp': 2, 'Credit_exp': 3})"
|
"how do i get the utc time of ""midnight"" for a given timezone?",datetime.now(pytz.timezone('Australia/Melbourne'))
|
pandas date_parser function for year:doy:sod format,"df['Epoch'] = pd.to_datetime(df['Epoch'].str[:6], format='%y:%j') + df"
|
how to remove all integer values from a list in python,"no_integers = [x for x in mylist if not isinstance(x, int)]"
|
how to label a line in python?,"plt.plot([1, 2, 3], 'r-', label='Sample Label Red')"
|
how can i split a file in python?,output.close()
|
how to configure logging in python,handler.setLevel(logging.DEBUG)
|
convert django model object to dict with all of the fields intact,"{'id': 1, 'reference1': 1, 'value': 1}"
|
how to display a pdf that has been downloaded in python,os.system('my_pdf.pdf')
|
python - how can i do a string find on a unicode character that is a variable?,s.decode('utf-8').find('\u0101')
|
"how to read a ""c source, iso-8859 text""","codecs.open('myfile', 'r', 'iso-8859-1').read()"
|
python: convert defaultdict to dict,"isinstance(a, dict)"
|
data munging in pandas,"df.groupby('ID')['<colname>'].agg(['std', 'mean'])"
|
pandas pivot table of sales,"df.pivot_table(index='saleid', columns='upc', aggfunc='size', fill_value=0)"
|
"regex, find first - python","re.findall('<wx\\.(?:.*?)> >', i)"
|
grouping daily data by month in python/pandas and then normalizing,"g.dropna().reset_index().reindex(columns=['visits', 'string', 'date'])"
|
create numpy array of `5` numbers starting from `1` with interval of `3`,"print(np.linspace(1, 3, num=5))"
|
how to set the unit length of axis in matplotlib?,plt.show()
|
easy way of finding decimal places,len(foo.split('.')[1])
|
python: how to get rid of spaces in str(dict)?,"'{' + ','.join('{0!r}:{1!r}'.format(*x) for x in list(dct.items())) + '}'"
|
split string on whitespace in python,"re.split('\\s+', s)"
|
how to execute a python script file with an argument from inside another python script file,"os.system('getCameras.py ""path_to_the_scene"" ')"
|
split an array dependent on the array values in python,"array([[1, 6], [2, 6], [3, 8], [4, 10], [5, 6], [5, 7]])"
|
python export csv data into file,"output.write('{0}:{1}\n'.format(nfeature[0] + 1, nfeature[1]))"
|
what does the 'b' character do in front of a string literal?,"""""""\\uFEFF"""""".encode('UTF-8')"
|
how to quit a pygtk application after last window is closed/destroyed,"window.connect('destroy', gtk.main_quit)"
|
pandas: how to run a pivot with a multi-index?,"df.set_index(['year', 'month', 'item']).unstack(level=-1)"
|
break string into list elements based on keywords,"['Na', '2', 'S', 'O', '4', 'Mn', 'O', '4']"
|
sort a string in lexicographic order python,"sorted(s, key=str.upper)"
|
replace value in any column in pandas dataframe,"pd.to_numeric(df.stack(), 'coerce').unstack()"
|
concatenating string and integer in python,"""""""{}{}"""""".format(s, i)"
|
remove item `c` in list `a`,a.remove(c)
|
draw a terrain with python?,plt.show()
|
extract floating number from string 'current level: 13.4 db.',"re.findall('\\d+\\.\\d+', 'Current Level: 13.4 db.')"
|
python: how to convert a string to utf-8,"stringnamehere.decode('utf-8', 'ignore')"
|
convert tab-delimited txt file into a csv file using python,"open('demo.txt', 'r').read()"
|
how to calculate centroid in python,"nx.mean(data[:, -3:], axis=0)"
|
how can i change type of django calender with persian calender?,widgets = {'delivery_date': forms.DateInput(attrs={'id': 'datepicker'})}
|
how to copy a dict and modify it in one line of code,result = copy.deepcopy(source_dict)
|
add dictionary `{'class': {'section': 5}}` to key 'test' of dictionary `dic`,dic['Test'].update({'class': {'section': 5}})
|
decode json string `u` to a dictionary,json.load(u)
|
how to assign value to a tensorflow variable?,sess.run(assign_op)
|
unpack column 'stats' in dataframe `df` into a series of columns,df['stats'].apply(pd.Series)
|
removing entries from a dictionary based on values,"{k: v for k, v in list(hand.items()) if v}"
|
convert a string of bytes into an int (python),"int.from_bytes('y\xcc\xa6\xbb', byteorder='big')"
|
using an ssh keyfile with fabric,run('uname -a')
|
how do i add two lists' elements into one list?,"list3 = [(a + b) for a, b in zip(list1, list2)]"
|
matplotlib remove patches from figure,circle1.set_visible(False)
|
python: load words from file into a set,words = set(open('filename.txt').read().split())
|
selecting specific rows and columns from numpy array,"a[[[0], [1], [3]], [0, 2]]"
|
backslash in a character set of a python regexp (how to specify 'not a backslash' character set)?,"regexps.append({'left': '[^\\\\]%.*', 'right': ''})"
|
replace first occurence of string,"'longlongTESTstringTEST'.replace('TEST', '?', 1)"
|
creating link to an url of flask app in jinja2 template,"{{url_for('post_blueprint.get_post', **post)}}"
|
how do i can format exception stacktraces in python logging?,logging.exception('ZeroDivisionError: {0}'.format(e))
|
get a string after a specific substring,"print(my_string.split(', ', 1)[1])"
|
how to create a timer using tkinter?,root.mainloop()
|
remove none value from a list without removing the 0 value,[x for x in L if x is not None]
|
sum one row of a numpy array,"z = arr[:, (5)].sum()"
|
sort list with multiple criteria in python,"['0.0.0.0.py', '1.0.0.0.py', '1.1.0.0.py']"
|
combine python dictionary permutations into list of dictionaries,"[dict(zip(d, v)) for v in product(*list(d.values()))]"
|
finding non-numeric rows in dataframe in pandas?,df[~df.applymap(np.isreal).all(1)]
|
removing backslashes from string,"print(""///I don't know why ///I don't have the right answer///"".strip('/'))"
|
how to read the entire file into a list in python?,text_file.close()
|
custom keys for google app engine models (python),kwargs['key_name'] = kwargs['name']
|
how to shift a string to right in python?,""""""" """""".join(l[-1:] + l[:-1])"
|
"execute sql query 'insert into table values(%s,%s,%s,%s,%s,%s,%s,%s,%s)' with all parameters in list `tup`","cur.executemany('INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)', tup)"
|
"python: convert ""5,4,2,4,1,0"" into [[5, 4], [2, 4], [1, 0]]","zip(*([iter(num_str.split(','))] * 4))"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.