text
stringlengths 4
1.08k
|
|---|
Python Pandas drop columns based on max value of column,df[df.columns[df.max() > 0]]
|
How to split string into words that do not contain whitespaces in python?,"""""""This is a string"""""".split()"
|
Python: How to round 123 to 100 instead of 100.0?,"int(round(123, -2))"
|
Symlinks on windows?,"kdll.CreateSymbolicLinkA('d:\\test.txt', 'd:\\test_link.txt', 0)"
|
Pythonic way to create a 2d array?,[([0] * width) for y in range(height)]
|
splitting numpy array into 2 arrays,"np.hstack((A[:, :1], A[:, 3:]))"
|
Evaluating a mathematical expression in a string,"eval('(1).__class__.__bases__[0].__subclasses__()', {'__builtins__': None})"
|
How do I pull a recurring key from a JSON?,print(item['name'])
|
How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?,ax.legend()
|
How to add an image in Tkinter (Python 2.7),root.mainloop()
|
How to write Unix end of line characters in Windows using Python,"f = open('file.txt', 'wb')"
|
Python- insert a character into a string,""""""""""""".join(parts[1:])"
|
How to update a plot in matplotlib?,fig.canvas.draw()
|
pandas split string into columns,"df['stats'].str[1:-1].str.split(',').apply(pd.Series).astype(float)"
|
How to write a multidimensional array to a text file?,"np.savetxt('test.txt', x)"
|
how to sort by length of string followed by alphabetical order?,"the_list.sort(key=lambda item: (-len(item), item))"
|
How can I convert an RGB image into grayscale in Python?,"img = cv2.imread('messi5.jpg', 0)"
|
Python and urllib2: how to make a GET request with parameters,"urllib.parse.urlencode({'foo': 'bar', 'bla': 'blah'})"
|
Terminating QThread gracefully on QDialog reject(),time.sleep(0.5)
|
"In Python, how do I index a list with another list?",T = [L[i] for i in Idx]
|
OverflowError: long int too large to convert to float in python,float(math.factorial(171))
|
Python: How to get attribute of attribute of an object with getattr?,"from functools import reduce
|
reduce(lambda obj, attr: getattr(obj, attr, None), ('id', 'num'), myobject)"
|
How to unquote a urlencoded unicode string in python?,urllib.parse.unquote('%0a')
|
Checking if any elements in one list are in another,len(set(list1).intersection(list2)) > 0
|
Convert column of date objects in Pandas DataFrame to strings,df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y')
|
pandas dataseries - How to address difference in days,df.index.to_series().diff()
|
how to sort 2d array by row in python?,"sorted(matrix, key=itemgetter(1))"
|
Pandas : Use groupby on each element of list,df['categories'].apply(pd.Series).stack().value_counts()
|
Starting two methods at the same time in Python,threading.Thread(target=play2).start()
|
How can I lookup an attribute in any scope by name?,"getattr(__builtins__, 'range')"
|
Sorting datetime objects while ignoring the year?,"birthdays.sort(key=lambda d: (d.month, d.day))"
|
Python: Check the occurrences in a list against a value,len(set(lst)) == len(lst)
|
How to reorder indexed rows based on a list in Pandas data frame,"df.reindex(['Z', 'C', 'A'])"
|
How to check if two keys in dict hold the same value,len(list(dictionary.values())) == len(set(dictionary.values()))
|
How to get pandas.read_csv() to infer datetime and timedelta types from CSV file columns?,df['timedelta'] = pd.to_timedelta(df['timedelta'])
|
Superscript in Python plots,plt.show()
|
python list comprehension double for,[x.lower() for x in words]
|
How to count number of rows in a group in pandas group by object?,df.groupby(key_columns).size()
|
how to create a dictionary using two lists in python?,"dict(zip(x, y))"
|
Write xml file using lxml library in Python,"str = etree.tostring(root, pretty_print=True)"
|
How to calculate moving average in Python 3?,"print(sum(map(int, x[num - n:num])))"
|
How to send cookies in a post request with the Python Requests library?,"r = requests.post('http://wikipedia.org', cookies=cookie)"
|
Read and overwrite a file in Python,f.close()
|
python how to search an item in a nested list,[x for x in li if 'ar' in x[2]]
|
How do I plot multiple X or Y axes in matplotlib?,plt.show()
|
Sort list with multiple criteria in python,"sorted(file_list, key=lambda x: map(int, x.split('.')[:-1]))"
|
finding streaks in pandas dataframe,df.groupby('loser').apply(f)
|
Fast way to remove a few items from a list/queue,somelist = [x for x in somelist if not determine(x)]
|
Index confusion in numpy arrays,"A[np.ix_([0, 2], [0, 1], [1, 2])]"
|
Call a method of an object with arguments in Python,"getattr(o, 'A')(1)"
|
Convert an IP string to a number and vice versa,"socket.inet_ntoa(struct.pack('!L', 2130706433))"
|
"Get (column, row) index from NumPy array that meets a boolean condition",np.column_stack(np.where(b))
|
List comprehension with an accumulator,list(accumulate(list(range(10))))
|
How to pass multiple values for a single URL parameter?,request.GET.getlist('urls')
|
How to convert a string to its Base-10 representation?,"int(s.encode('hex'), 16)"
|
Pandas date_parser function for year:doy:sod format,"df['Epoch'] = pd.to_datetime(df['Epoch'].str[:6], format='%y:%j') + df"
|
how do you filter pandas dataframes by multiple columns,"df = df[df[['col_1', 'col_2']].apply(lambda x: f(*x), axis=1)]"
|
Arrow on a line plot with matplotlib,plt.show()
|
How to filter model results for multiple values for a many to many field in django,"Group.objects.filter(member__in=[1, 2])"
|
Iterate through words of a file in Python,words = open('myfile').read().split()
|
"How to set ""step"" on axis X in my figure in matplotlib python 2.6.6?","plt.xticks([1, 2, 3, 4, 5])"
|
How do get the ID field in App Engine Datastore?,entity.key.id()
|
How to set the labels size on a pie chart in python,plt.show()
|
Sort a list of dictionary provided an order,"sorted(list_of_dct, key=lambda x: order.index(list(x.values())[0]))"
|
Remove non-ASCII characters from a string using python / django,"""""""1 < 4 & 4 > 1"""""""
|
Using multiple cursors in a nested loop in sqlite3 from python-2.7,curOuter.execute('SELECT id FROM myConnections')
|
How to check version of python package if no __version__ variable is set,"pip.main(['show', 'pyodbc'])"
|
Pandas remove column by index,"df = df.ix[:, 0:2]"
|
What is the reason behind the advice that the substrings in regex should be ordered based on length?,regex.findall(string)
|
List comprehension with if statement,[y for y in a if y not in b]
|
Most efficient way in Python to iterate over a large file (10GB+),"collections.Counter(map(uuid, open('log.txt')))"
|
Format string - spaces between every three digit,"format(12345678.46, ',').replace(',', ' ').replace('.', ',')"
|
Convert float Series into an integer Series in pandas,"df['time'] = pd.to_datetime(df['time'], unit='s')"
|
Convert pandas group by object to multi-indexed Dataframe,"df.set_index(['Name', 'Destination'])"
|
How can I remove duplicate words in a string with Python?,"print(' '.join(sorted(set(words), key=words.index)))"
|
"How do I get the UTC time of ""midnight"" for a given timezone?",datetime.now(pytz.timezone('Australia/Melbourne'))
|
Multiplication of 1d arrays in numpy,"np.dot(a[:, (None)], b[(None), :])"
|
How do I insert a list at the front of another list?,a = a[:n] + k + a[n:]
|
Python list of tuples to list of int,y = [i[0] for i in x]
|
Convert a string to integer with decimal in Python,int(Decimal(s))
|
How to print utf-8 to console with Python 3.4 (Windows 8)?,sys.stdout.buffer.write('\xe2\x99\xa0'.encode('cp437'))
|
Is there a way to make matplotlib scatter plot marker or color according to a discrete variable in a different column?,"plt.scatter(x, y, color=color)"
|
How to make custom legend in matplotlib,plt.show()
|
Is it possible to define global variables in a function in Python,globals()['something'] = 'bob'
|
How to count the Nan values in the column in Panda Data frame,df.isnull().sum()
|
How to remove multiple columns that end with same text in Pandas?,"df2 = df.ix[:, (~df.columns.str.endswith('prefix'))]"
|
How to write a regular expression to match a string literal where the escape is a doubling of the quote character?,"""""""'(''|[^'])*'"""""""
|
Get Element value with minidom with Python,name[0].firstChild.nodeValue
|
Split a list of tuples into sub-lists of the same tuple field,"zip(*[(1, 4), (2, 5), (3, 6)])"
|
"Why can you loop through an implicit tuple in a for loop, but not a comprehension in Python?",list(i for i in range(3))
|
Generating all unique pair permutations,"list(permutations(list(range(9)), 2))"
|
Python 2.7: making a dictionary object from a specially-formatted list object,"{f[i + 1]: [f[i], f[i + 2]] for i in range(0, len(f), 3)}"
|
for loop in Python,list(range(10))
|
Python: slicing a multi-dimensional array,"slice = [arr[i][0:2] for i in range(0, 2)]"
|
Sum values from DataFrame into Parent Index - Python/Pandas,"df_new.reset_index().set_index(['parent', 'index']).sort_index()"
|
Inserting a string into a list without getting split into characters,"list.insert(0, 'foo')"
|
How to use Beautiful Soup to find a tag with changing id?,"soup.select('div[id^=""value_xxx_c_1_f_8_a_""]')"
|
Manipulating binary data in Python,print(repr(data))
|
Importing everything ( * ) dynamically from a module,globals().update(importlib.import_module('some.package').__dict__)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.