text stringlengths 4 1.08k |
|---|
Python: Finding a (string) key in a dictionary that contains a substring,"[(k, v) for k, v in D.items() if 'Light' in k]" |
How do I use a MD5 hash (or other binary data) as a key name?,k = hashlib.md5('thecakeisalie').hexdigest() |
How to get only the last part of a path in Python?,os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/')) |
Sorting datetime objects while ignoring the year?,"birthdays.sort(key=lambda d: (d.month, d.day))" |
How do I extract table data in pairs using BeautifulSoup?,[[td.findNext(text=True) for td in tr.findAll('td')] for tr in rows] |
"python: rstrip one exact string, respecting order","""""""Boat.txt.txt"""""".replace('.txt', '')" |
Python Pandas: How to get the row names from index of a dataframe?,list(df.index) |
Python Pandas: How to get the row names from index of a dataframe?,df.index |
List of all unique characters in a string?,""""""""""""".join(list(OrderedDict.fromkeys('aaabcabccd').keys()))" |
List of all unique characters in a string?,list(set('aaabcabccd')) |
List of all unique characters in a string?,""""""""""""".join(set('aaabcabccd'))" |
Find rows with non zero values in a subset of columns in pandas dataframe,"df.loc[(df.loc[:, (df.dtypes != object)] != 0).any(1)]" |
upload file with Python Mechanize,"br.form.add_file(open(filename), 'text/plain', filename)" |
Multiple 'in' operators in Python?,"all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])" |
How to hide output of subprocess in Python 2.7,"subprocess.check_output(['espeak', text], stderr=subprocess.STDOUT)" |
How to replace NaNs by preceding values in pandas DataFrame?,"df.fillna(method='ffill', inplace=True)" |
How to create range of numbers in Python like in MATLAB,"print(np.linspace(1, 3, num=4, endpoint=False))" |
How to create range of numbers in Python like in MATLAB,"print(np.linspace(1, 3, num=5))" |
Symlinks on windows?,"kdll.CreateSymbolicLinkW('D:\\testdirLink', 'D:\\testdir', 1)" |
Python: slicing a multi-dimensional array,"slice = [arr[i][0:2] for i in range(0, 2)]" |
Upload files to Google cloud storage from appengine app,"upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='my_bucket')" |
Change directory to the directory of a Python script,os.chdir(os.path.dirname(__file__)) |
Call a function with argument list in python,func(*args) |
"Pandas DataFrame, how do i split a column into two","df['AB'].str.split(' ', 1, expand=True)" |
"Pandas DataFrame, how do i split a column into two","df['A'], df['B'] = df['AB'].str.split(' ', 1).str" |
Sorting Python list based on the length of the string,"print(sorted(xs, key=len))" |
Sorting Python list based on the length of the string,"xs.sort(lambda x, y: cmp(len(x), len(y)))" |
Sorting Python list based on the length of the string,xs.sort(key=lambda s: len(s)) |
how to plot arbitrary markers on a pandas data series?,ts.plot(marker='.') |
get all combination of n binary value,"lst = list(itertools.product([0, 1], repeat=n))" |
get all combination of n binary value,"lst = map(list, itertools.product([0, 1], repeat=n))" |
get all combination of n binary value,"bin = [0, 1] |
[(x, y, z) for x in bin for y in bin for z in bin]" |
get all combination of n binary value,"lst = list(itertools.product([0, 1], repeat=3))" |
Append string to the start of each value in a said column of a pandas dataframe (elegantly),df['col'] = 'str' + df['col'].astype(str) |
How to get a variable name as a string in Python?,"dict((name, eval(name)) for name in ['some', 'list', 'of', 'vars'])" |
How to add a colorbar for a hist2d plot,"plt.colorbar(im, ax=ax)" |
How to get every element in a list of list of lists?,[a for c in Cards for b in c for a in b] |
Sorting dictionary keys in python,"sorted(d, key=d.get)" |
How to count the number of occurences of `None` in a list?,print(len([x for x in lst if x is not None])) |
Accessing dictionary by key in Django template,{{json.key1}} |
Get unique values from a list in python,mynewlist = list(myset) |
Get unique values from a list in python,"set(['a', 'b', 'c', 'd'])" |
Python: A4 size for a plot,"figure(figsize=(11.69, 8.27))" |
How to get everything after last slash in a URL?,"url.rsplit('/', 1)" |
How to get everything after last slash in a URL?,"url.rsplit('/', 1)[-1]" |
how to read a file in other directory in python,"x_file = open(os.path.join(direct, '5_1.txt'), 'r')" |
How to create a list with the characters of a string?,list('5+6') |
Flattening a list of NumPy arrays?,np.concatenate(input_list).ravel().tolist() |
Converting a dict into a list,print([y for x in list(dict.items()) for y in x]) |
Converting a dict into a list,[y for x in list(dict.items()) for y in x] |
How to pull a random record using Django's ORM?,MyModel.objects.order_by('?').first() |
change current working directory in python,os.chdir('chapter3') |
change current working directory in python,os.chdir('C:\\Users\\username\\Desktop\\headfirstpython\\chapter3') |
change current working directory in python,os.chdir('.\\chapter3') |
How to create single Python dict from a list of dicts by summing values with common keys?,"dict((key, sum(d[key] for d in dictList)) for key in dictList[0])" |
How to sort pandas data frame using values from several columns?,"df.sort(['c1', 'c2'], ascending=[True, True])" |
Converting string series to float list,floats = [float(x) for x in s.split()] |
Converting string series to float list,"floats = map(float, s.split())" |
"How to set ""step"" on axis X in my figure in matplotlib python 2.6.6?","plt.xticks([1, 2, 3, 4, 5])" |
read from stdin,"for line in fileinput.input(): |
pass" |
read from stdin,"for line in sys.stdin: |
pass" |
How to check if a value exists in a dictionary (python),'one' in list(d.values()) |
How to check if a value exists in a dictionary (python),'one' in iter(d.values()) |
Calling a parent class constructor from a child class in python,"super(Instructor, self).__init__(name, year)" |
how to create a dictionary using two lists in python?,"dict(zip(x, y))" |
Sorting a list of dicts by dict values,"sorted(a, key=lambda i: list(i.values())[0], reverse=True)" |
Sorting a list of dicts by dict values,"sorted(a, key=dict.values, reverse=True)" |
pandas: how to do multiple groupby-apply operations,"df.groupby(level=0).agg(['sum', 'count', 'std'])" |
How to add multiple values to a dictionary key in python?,"a.setdefault('somekey', []).append('bob')" |
Python - sum values in dictionary,sum(item['gold'] for item in example_list) |
Python - sum values in dictionary,sum([item['gold'] for item in example_list]) |
Python - sum values in dictionary,sum(item['gold'] for item in myLIst) |
writing string to a file on a new line everytime?,f.write('text to write\n') |
writing string to a file on a new line everytime?,file.write('My String\n') |
Finding consecutive segments in a pandas data frame,df.reset_index().groupby('A')['index'].apply(np.array) |
Python - how to refer to relative paths of resources when working with code repository,"fn = os.path.join(os.path.dirname(__file__), 'my_file')" |
How to retrieve an element from a set without removing it?,e = next(iter(s)) |
How to execute a command prompt command from python,os.system('dir c:\\') |
How to auto-scroll a gtk.scrolledwindow?,"self.treeview.connect('size-allocate', self.treeview_changed)" |
Python: Find in list,"3 in [1, 2, 3]" |
Convert date format python,"datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d')" |
python : how to convert string literal to raw string literal?,"s = s.replace('\\', '\\\\')" |
Get output of python script from within python script,print(proc.communicate()[0]) |
Getting pandas dataframe from list of nested dictionaries,"pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T" |
Delete Column in Pandas based on Condition,"df.loc[:, ((df != 0).any(axis=0))]" |
How to sort multidimensional array by column?,"sorted(a, key=lambda x: x[1])" |
string to list conversion in python,"[x.strip() for x in s.split(',')]" |
Get list item by attribute in Python,items = [item for item in container if item.attribute == value] |
Python: Write a list of tuples to a file,"open('filename', 'w').write('\n'.join('%s %s' % x for x in mylist))" |
Python regex to match multiple times,"pattern = re.compile('(?:review: )?(http://url.com/(\\d+))\\s?', re.IGNORECASE)" |
How do I read a text file into a string variable in Python,"str = open('very_Important.txt', 'r').read()" |
Grouping dataframes in pandas?,"df.groupby(['A', 'B'])['C'].unique()" |
read a file line by line into a list,"with open(fname) as f: |
content = f.readlines()" |
read a file line by line into a list,"with open('filename') as f: |
lines = f.readlines()" |
read a file line by line into a list,lines = [line.rstrip('\n') for line in open('filename')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.