text
stringlengths 4
1.08k
|
|---|
How to sum the values of list to the power of their indices,"sum(j ** i for i, j in enumerate(l, 1))"
|
convert binary string to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='>f4')"
|
"Import module in another directory from a ""parallel"" sub-directory",sys.path.append('/path/to/main_folder')
|
Multi-Index Sorting in Pandas,"g = df.groupby(['Manufacturer', 'Product Launch Date', 'Product Name']).sum()"
|
Pandas groupby: Count the number of occurences within a time range for each group,df['cumsum'] = df['WIN1'].cumsum()
|
Add scrolling to a platformer in pygame,pygame.display.update()
|
How to deal with SettingWithCopyWarning in Pandas?,"df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 1, 2, 2]})"
|
How to pass a dictionary as value to a function in python,"reducefn({'physics': 1}, {'volume': 1, 'chemistry': 1}, {'chemistry': 1})"
|
Convert a list to a dictionary in Python,"b = dict(zip(a[0::2], a[1::2]))"
|
"Python list comprehension, with unique items","['n', 'e', 'v', 'r', ' ', 'g', 'o', 'a', 'i', 'y', 'u', 'p']"
|
More elegant way to implement regexp-like quantifiers,"['x', ' ', 'y', 'y', ' ', 'z']"
|
how to format date in ISO using python?,"datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()"
|
Find Average of Every Three Columns in Pandas dataframe,"pd.concat([df, res], axis=1)"
|
Pandas groupby: How to get a union of strings,df.groupby('A').apply(f)
|
Removing white space around a saved image in matplotlib,"plt.savefig('test.png', bbox_inches='tight')"
|
Plotting categorical data with pandas and matplotlib,df.groupby('colour').size().plot(kind='bar')
|
testing whether a Numpy array contains a given row,"any(np.equal(a, [1, 2]).all(1))"
|
How do I convert datetime to date (in Python)?,datetime.datetime.now().date()
|
"Elegant way to create a dictionary of pairs, from a list of tuples?",dict(x[1:] for x in reversed(myListOfTuples))
|
How to match beginning of string or character in Python,"re.findall('[^a]', 'abcd')"
|
Is there any elegant way to build a multi-level dictionary in python?,"multi_level_dict(['a', 'b'], ['A', 'B'], ['1', '2'])"
|
How to select columns from groupby object in pandas?,"df.groupby(['a', 'name']).median().index.get_level_values('name')"
|
Can Python test the membership of multiple values in a list?,"all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])"
|
Python regex to match multiple times,"pattern = re.compile('(?:review: )?(http://url.com/(\\d+))\\s?', re.IGNORECASE)"
|
Python: Finding a (string) key in a dictionary that contains a substring,"[(k, v) for k, v in D.items() if 'Light' in k]"
|
Sending a file over TCP sockets in Python,s.send('Hello server!')
|
Python Pandas : group by in group by and average?,"df.groupby(['cluster', 'org']).mean()"
|
What is the best way to remove a dictionary item by value in python?,"{key: val for key, val in list(myDict.items()) if val != 42}"
|
Finding key from value in Python dictionary:,"[k for k, v in d.items() if v == desired_value]"
|
Summing 2nd list items in a list of lists of lists,[[sum([x[1] for x in i])] for i in data]
|
Add Multiple Columns to Pandas Dataframe from Function,"df[['hour', 'weekday', 'weeknum']] = df.apply(lambdafunc, axis=1)"
|
retrieving list items from request.POST in django/python,request.POST.getlist('pass_id')
|
Average values in two Numpy arrays,"np.mean(np.array([old_set, new_set]), axis=0)"
|
Calling a function of a module from a string with the function's name in Python,globals()['myfunction']()
|
Using a RegEx to match IP addresses in Python,"pat = re.compile('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')"
|
best way to extract subset of key-value pairs from python dictionary object,"{k: bigdict[k] for k in ('l', 'm', 'n')}"
|
pandas create new column based on values from other columns,"df['race_label'] = df.apply(lambda row: label_race(row), axis=1)"
|
Get current URL in Python,self.request.get('name-of-querystring-variable')
|
How to change legend size with matplotlib.pyplot,"pyplot.legend(loc=2, fontsize='x-small')"
|
How can i create the empty json object in python,"json.loads(request.POST.get('mydata', '{}'))"
|
my matplotlib title gets cropped,plt.subplots_adjust(top=0.5)
|
Sort list of strings by integer suffix in python,"sorted(the_list, key=lambda k: int(k.split('_')[1]))"
|
How to dynamically access class properties in Python?,"setattr(my_class_instance, 'attr_name', attr_value)"
|
How to use the mv command in Python with subprocess,"subprocess.call(['mv', '/home/somedir/subdir/*', 'somedir/'])"
|
syntax for creating a dictionary into another dictionary in python,"d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}"
|
sort a list of tuples alphabetically and by value,"sorted(list_of_medals, key=lambda x: (-x[1], x[0]))"
|
Converting Perl Regular Expressions to Python Regular Expressions,re.compile('Author\\(s\\) :((.+\\n)+)')
|
How to convert dictionary into string,""""""""""""".join('{}{}'.format(key, val) for key, val in sorted(adict.items()))"
|
How to input an integer tuple from user?,"tuple(map(int, input().split(',')))"
|
Python Add Elements to Lists within List if Missing,"[[2, 3, 0], [1, 2, 3], [1, 0, 0]]"
|
How to convert this list into dictionary in Python?,"dict_list = {'a': 1, 'b': 2, 'c': 3, 'd': 4}"
|
matplotlib: Set markers for individual points on a line,"plt.plot(list(range(10)), linestyle='--', marker='o', color='b')"
|
Redis: How to parse a list result,"myredis.lpush('foo', *[1, 2, 3, 4])"
|
How do I draw a grid onto a plot in Python?,plt.show()
|
Find Average of Every Three Columns in Pandas dataframe,"df.groupby(np.arange(len(df.columns)) // 3, axis=1).mean()"
|
How to merge two columns together in Pandas,"pd.melt(df, id_vars='Date')[['Date', 'value']]"
|
How to change User-Agent on Google App Engine UrlFetch service?,"urlfetch.fetch(url, headers={'User-Agent': 'MyApplication_User-Agent'})"
|
How to split a string into integers in Python?,"""string"".split()"
|
How to print a dictionary's key?,"print((key, value))"
|
Python: reduce (list of strings) -> string,print('.'.join([item[0] for item in data]))
|
QDialog not opening from Main window (pyQt),self.pushButton.clicked.connect(self.showDial)
|
Convert a list to a dictionary in Python,"dict(x[i:i + 2] for i in range(0, len(x), 2))"
|
How to account for accent characters for regex in Python?,"hashtags = re.findall('#(\\w+)', str1, re.UNICODE)"
|
Get index values of Pandas DataFrame as list?,df.index.values.tolist()
|
Filter a tuple with another tuple in Python,"['subject', 'filer, subject', 'filer', 'activity, subject']"
|
What's the best way to aggregate the boolean values of a Python dictionary?,all(dict.values())
|
Convert list of strings to int,[[int(x) for x in sublist] for sublist in lst]
|
python's webbrowser launches IE instead of default on windows 7,webbrowser.open('file://' + os.path.realpath(filename))
|
Python: Split NumPy array based on values in the array,"np.diff(arr[:, (1)])"
|
Escaping quotes in string,"replace('""', '\\""')"
|
Save JSON outputed from a URL to a file,"urllib.request.urlretrieve('http://search.twitter.com/search.json?q=hi', 'hi.json')"
|
Call a function with argument list in python,func(*args)
|
Pythonic way to populate numpy array,"X = numpy.loadtxt('somefile.csv', delimiter=',')"
|
Howto determine file owner on windows using python without pywin32,"subprocess.call('dir /q', shell=True)"
|
regex: string with optional parts,"re.search('^(.*?)(Arguments:.*?)?(Returns:.*)?$', s, re.DOTALL)"
|
Is there a matplotlib equivalent of MATLAB's datacursormode?,plt.show()
|
Pixelate Image With Pillow,img = img.convert('RGB')
|
Extracting specific columns in numpy array,"data[:, ([1, 9])]"
|
ValueError: invalid literal for int() with base 10: '',int('55063.000000')
|
sqlalchemy add child in one-to-many relationship,"parent = relationship('Parent', backref=backref('children', lazy='noload'))"
|
"How do I generate a random string (of length X, a-z only) in Python?",""""""""""""".join(random.choice(string.lowercase) for x in range(X))"
|
convert list of tuples to multiple lists in Python,"map(list, zip(*[(1, 2), (3, 4), (5, 6)]))"
|
How to modify a variable inside a lambda function?,"lambda a, b: a + b"
|
How to rearrange Pandas column sequence?,"df = df[['x', 'y', 'a', 'b']]"
|
Python - How to sort a list of lists by the fourth element in each list?,unsorted_list.sort(key=lambda x: x[3])
|
How does this function to remove duplicate characters from a string in python work?,"OrderedDict([('a', None), ('b', None), ('c', None), ('d', None), ('e', None)])"
|
Looping over a MultiIndex in pandas,df.index.get_level_values(0).unique()
|
sunflower scatter plot using matplotlib,plt.show()
|
converting integer to list in python,"map(int, str(num))"
|
Delete column from pandas DataFrame,"df.drop(df.columns[[0, 1, 3]], axis=1)"
|
Slicing a multidimensional list,[[[x[0]] for x in y] for y in listD]
|
set multi index of an existing data frame in pandas,"df.set_index(['Company', 'date'], inplace=True)"
|
Using inheritance in python,"super(Executive, self).__init__(*args)"
|
Python check if all elements of a list are the same type,"all(isinstance(x, int) for x in lst)"
|
Getting an element from tuple of tuples in python,[x[1] for x in COUNTRIES if x[0] == 'AS'][0]
|
How to swap a group of column headings with their values in Pandas,"pd.DataFrame(df.columns[np.argsort(df.values)], df.index, np.unique(df.values))"
|
"Pandas sum by groupby, but exclude certain columns","df.groupby(['Country', 'Item_Code'])[['Y1961', 'Y1962', 'Y1963']].sum()"
|
Merge Columns within a DataFrame that have the Same Name,"df.groupby(df.columns, axis=1).sum()"
|
django: how to filter model field values with out space?,City.objects.filter(name__nospaces='newyork')
|
python pandas: apply a function with arguments to a series. Update,"a['x'].apply(lambda x, y: x + y, args=(100,))"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.