text
stringlengths
4
1.08k
list of dictionaries from numpy array without for loop,"np.rec.fromarrays((x, y, z), names=['x', 'y', 'z'])"
apply function with args in pandas,df['Month'] = df['Date'].apply(lambda x: x.strftime('%b'))
add headers in a flask app with unicode_literals,"response.headers['WWW-Authenticate'] = 'Basic realm=""test""'"
how can i use a pseudoterminal in python to emulate a serial port?,time.sleep(3)
accessing json elements,print(wjdata['data']['current_condition'][0]['temp_C'])
"python, regex split and special character",l = re.compile('\\s').split(s)
how to do pearson correlation of selected columns of a pandas data frame,data[data.columns[1:]].corr()['special_col'][:-1]
get a list of values from a list of dictionaries in python,[d['key'] for d in l if 'key' in d]
how can i change a specific row label in a pandas dataframe?,df = df.rename(index={last: 'a'})
how do i find the first letter of each word?,output = ''.join(item[0].upper() for item in input.split())
pythonic iteration over sliding window pairs in list?,"zip(l, l[1:])"
iterating over a dictionary to create a list,"{'Jhonny': 'green', 'Steve': 'blue'}"
how to get a file close event in python,app.exec_()
python multidimensional arrays - most efficient way to count number of non-zero entries,sum(sum(1 for i in row if i) for row in rows)
numpy: comparing elements in two arrays,"array([True, False, False, True, True, False], dtype=bool)"
remove all items from a dictionary `d` where the values are less than `1`,"d = dict((k, v) for k, v in d.items() if v > 0)"
add items to a dictionary of lists,"print(dict(zip(keys, [list(i) for i in zip(*data)])))"
how to iterate over unicode characters in python 3?,print('U+{:04X}'.format(i))
get utc timestamp in python with datetime,dt = dt.replace(tzinfo=timezone('Europe/Amsterdam'))
finding the last occurrence of an item in a list python,last = len(s) - s[::-1].index(x) - 1
get python class object from string,"print(getattr(somemodule, class_name))"
python: check the occurrences in a list against a value,len(set(lst)) == len(lst)
is it possible to define global variables in a function in python,globals()['something'] = 'bob'
"in dictionary, converting the value from string to integer","{k: int(v) for k, v in d.items()}"
split string `text` into chunks of 16 characters each,"re.findall('.{,16}\\b', text)"
sorting files in a list,"[['s1.txt', 'ai1.txt'], ['s2.txt'], ['ai3.txt']]"
download to a directory '/path/to/dir/filename.ext' from source 'http://example.com/file.ext',"urllib.request.urlretrieve('http://example.com/file.ext', '/path/to/dir/filename.ext')"
python how to pad numpy array with zeros,result = np.zeros(b.shape)
execute shell command 'grep -r passed *.log | sort -u | wc -l' with a | pipe in it,"subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)"
inserting a string into a list without getting split into characters,list.append('foo')
python accessing values in a list of dictionaries,{d['Name']: d['Age'] for d in thisismylist}
check to ensure a string does not contain multiple values,"""""""test.png"""""".endswith(('jpg', 'png', 'gif'))"
"distance between numpy arrays, columnwise",(dist ** 2).sum(axis=1) ** 0.5
how can i group equivalent items together in a python list?,"[list(g) for k, g in itertools.groupby(sorted(iterable))]"
recursively delete all contents in directory `path`,"shutil.rmtree(path, ignore_errors=False, onerror=None)"
python: how do i display a timer in a terminal,sys.stdout.write('\rComplete! \n')
arrows in matplotlib using mplot3d,ax.set_axis_off()
change legend size to 'x-small' in upper-left location,"pyplot.legend(loc=2, fontsize='x-small')"
how can i print over the current line in a command line application?,sys.stdout.flush()
how do i grab the last portion of a log string and interpret it as json?,"line = x.split(None, 4)"
how to encode a categorical variable in sklearn?,pd.get_dummies(df['key'])
python pandas convert dataframe to dictionary with multiple values,"{k: list(v) for k, v in df.groupby('Address')['ID']}"
list comprehensions in python : efficient selection in a list,[f(x) for x in list]
how to make markers on lines smaller in matplotlib?,"plt.errorbar(x, y, yerr=err, fmt='-o', markersize=2, color='k', label='size 2')"
how do i blit a png with some transparency onto a surface in pygame?,pygame.display.flip()
python - sum values in dictionary,sum([item['gold'] for item in example_list])
read the first line of a string `my_string`,my_string.splitlines()[0]
how can i do multiple substitutions using regex in python?,"re.sub('([abc])', '\\1\\1', text.read())"
"how to change numpy array from (128,128,3) to (3,128,128)?","a.transpose(2, 1, 0)"
split a string in python,a.split('\n')[:-1]
python: intertwining two lists,"c = [item for pair in zip(a, b) for item in pair]"
python: how to convert a query string to json string?,json.dumps(urlparse.parse_qs('a=1&b=2'))
sort pandas dataframe by date,df.ix[pd.to_datetime(df.Date).order().index]
python - speed up for converting a categorical variable to it's numerical index,df['col'] = df['col'].astype('category')
split string `s` by '@' and get the first element,s.split('@')[0]
how to pack spheres in python?,r = [(1) for i in range(n)]
sort dictionary `d` by value in ascending order,"sorted(list(d.items()), key=(lambda x: x[1]))"
build dictionary in python loop - list and dictionary comprehensions,{_key: _value(_key) for _key in _container}
how to multiply all integers inside list,l = [(x * 2) for x in l]
pythonic way to get the largest item in a list,"max(a_list, key=operator.itemgetter(1))"
django - how to sort queryset by number of character in a field,MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length')
multiple tuple to two-pair tuple in python?,"[(tuple[a], tuple[a + 1]) for a in range(0, len(tuple), 2)]"
how to use a dot in python format strings?,"""""""Hello {user[name]}"""""".format(**{'user': {'name': 'Markus'}})"
how to determine whether a pandas column contains a particular value,"df.isin({'A': [1, 3], 'B': [4, 7, 12]})"
using python to return a list of squared integers,squared = [(x ** 2) for x in lst]
create 3d array using python,[[[(0) for _ in range(n)] for _ in range(n)] for _ in range(n)]
calling php from python,"subprocess.call(['php', 'path/to/script.php'])"
unpack each value in list `x` to its placeholder '%' in string '%.2f',""""""", """""".join(['%.2f'] * len(x))"
extract all keys from a list of dictionaries,{k for d in LoD for k in list(d.keys())}
iterating over a dictionary to create a list,"['blue', 'blue', None, 'red', 'red', 'green', None]"
how can you split a list every x elements and add those x amount of elements to an new list?,"composite_list.append(['200', '200', '200', '400', 'bluellow'])"
new column based on conditional selection from the values of 2 other columns in a pandas dataframe,"df['A'].where(df['A'] > df['B'], df['B'])"
how do i specify a range of unicode characters in a regular-expression in python?,"""""""[\\u00d8-\\u00f6]"""""""
python accessing nested json data,print(data['places']['latitude'])
how to reshape a networkx graph in python?,plt.show()
python list of tuples to list of int,"y = map(operator.itemgetter(0), x)"
python: beautifulsoup - get an attribute value based on the name attribute,"soup.find('meta', {'name': 'City'})['content']"
how do you edit cells in a sparse matrix using scipy?,"A.indptr = np.array([0, 0, 0, 1, 1, 1, 2], dtype=np.int32)"
how to terminate process from python using pid?,"Popen(['python', 'StripCore.py'])"
scikit-learn: how to run kmeans on a one-dimensional array?,"km.fit(x.reshape(-1, 1))"
delete an item with key `key` from `mydict`,del mydict[key]
unable to access files from public s3 bucket with boto,conn = boto.connect_s3(anon=True)
how to decode this representation of a unicode string in python?,print(bytes.decode(encoding))
convert an rfc 3339 time to a standard python timestamp,"dt.datetime.strptime('1985-04-12T23:20:50.52', '%Y-%m-%dT%H:%M:%S.%f')"
how do convert a pandas/dataframe to xml?,df.to_xml('foo.xml')
what's the most memory efficient way to generate the combinations of a set in python?,"print(list(itertools.combinations({1, 2, 3, 4}, 3)))"
how do i write to the console in google app engine?,logging.debug('hi')
print list in table format in python,print(' '.join(row))
finding count of duplicate values and ordering in a pandas dataframe,"agg[agg['size'] > 100].sort_values(by='ave_age', ascending=True).head(5)"
how to create a sequential combined list in python?,"[''.join(['a', 'b', 'c', 'd'])[i:j + 1] for i in range(4) for j in range(i, 4)]"
converting a dictionary into a list,list(flatten(elements))
"use a list of values `[3,6]` to select rows from a pandas dataframe `df`'s column 'a'","df[df['A'].isin([3, 6])]"
"why can you loop through an implicit tuple in a for loop, but not a comprehension in python?","[i for i in ('a', 'b', 'c')]"
"in python, if i have a unix timestamp, how do i insert that into a mysql datetime field?",datetime.fromtimestamp(1268816500)
how do you split a list into evenly sized chunks?,"[l[i:i + n] for i in range(0, len(l), n)]"
how to make a class json serializable,"{'age': 35, 'dog': {'name': 'Apollo'}, 'name': 'Onur'}"
how to change the date/time in python for all modules?,datetime.datetime.now()
how do i limit the border size on a matplotlib graph?,ax.set_title('Title')
"check if 3 is inside list `[1, 2, 3]`","3 in [1, 2, 3]"
"insert a character ',' into a string in front of '+' character in second part of the string",""""""",+"""""".join(c.rsplit('+', 1))"