text
stringlengths 4
1.08k
|
|---|
Python: Zip dict with keys,"[{'char': 'a', 'num': 1}, {'char': 'd', 'num': 18}]"
|
Find Monday's date with Python,today - datetime.timedelta(days=today.weekday())
|
"Regular expression syntax for ""match nothing""?",re.compile('$^')
|
Replace non-ascii chars from a unicode string in Python,"unicodedata.normalize('NFKD', 'm\xfasica').encode('ascii', 'ignore')"
|
reverse a string in Python,"l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
|
How to combine single and multiindex Pandas DataFrames,"pd.concat([df2, df1], axis=1)"
|
Python/Django: Creating a simpler list from values_list(),"Entry.objects.values_list('id', flat=True).order_by('id')"
|
Sort a string in lexicographic order python,"sorted(s, key=str.upper)"
|
How to retrive GET vars in python bottle app,request.query['city']
|
Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row,"np.argmin(a[:, (1)])"
|
Best way to remove elements from a list,[item for item in my_list if some_condition()]
|
How to generate all permutations of a list in Python,"print(list(itertools.product([1, 2, 3], [4, 5, 6])))"
|
Remove object from a list of objects in python,my_list.pop(2)
|
memory usage of a probabilistic parser,"('S', 'NP', 'VP') is ('S', 'NP', 'VP')"
|
"Python: Is there a way to plot a ""partial"" surface plot with Matplotlib?",plt.show()
|
Adding two items at a time in a list comprehension,"print([y for x in zip(['^'] * len(mystring), mystring.lower()) for y in x])"
|
Parse string to int when string contains a number + extra characters,int(''.join(c for c in s if c.isdigit()))
|
creating list of random numbers in python,print('%.5f' % randomList[index])
|
Currency formatting in Python,"""""""{:20,.2f}"""""".format(1.8446744073709552e+19)"
|
Sorting a dictionary (with date keys) in Python,"ordered = OrderedDict(sorted(list(mydict.items()), key=lambda t: t[0]))"
|
How to make a window jump to the front?,"root.attributes('-topmost', True)"
|
How to get UTC time in Python?,datetime.utcnow()
|
Python Pandas: drop rows of a timeserie based on time range,"pd.concat([df[:start_remove], df[end_remove:]])"
|
Using BeautifulSoup To Extract Specific TD Table Elements Text?,"[tag.text for tag in filter(pred, soup.find('tbody').find_all('a'))]"
|
pandas joining multiple dataframes on columns,"df1.merge(df2, on='name').merge(df3, on='name')"
|
Is there a function in python to split a word into a list?,"['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']"
|
How can I list the contents of a directory in Python?,os.listdir('/home/username/www/')
|
Sorting a text file alphabetically (Python),lines.sort()
|
I want to plot perpendicular vectors in Python,plt.axes().set_aspect('equal')
|
Python: logging module - globally,logger.debug('submodule message')
|
How can I get Python to use upper case letters to print hex values?,print('0x%X' % value)
|
finding non-numeric rows in dataframe in pandas?,"df.applymap(lambda x: isinstance(x, (int, float)))"
|
How to send a xml-rpc request in python?,server.serve_forever()
|
How to create a ssh tunnel using python and paramiko?,ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
How to retrieve an element from a set without removing it?,e = next(iter(s))
|
Transparent background in a Tkinter window,root.geometry('+250+250')
|
Heap Sort: how to sort?,sort()
|
Splitting on last delimiter in Python string?,"s.rsplit(',', 1)"
|
Find ordered vector in numpy array,"(e == np.array([1, 2])).all(-1).shape"
|
How do you set up a Flask application with SQLAlchemy for testing?,app.run(debug=True)
|
Parse and format the date from the GitHub API in Python,date.strftime('%c')
|
Python: Can a function return an array and a variable?,result = my_function()
|
php's strtr for python,"print(strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'}))"
|
Python: Check if one dictionary is a subset of another larger dictionary,all(item in list(superset.items()) for item in list(subset.items()))
|
How to Close a program using python?,os.system('TASKKILL /F /IM firefox.exe')
|
Python - Choose a dictionary in list which key is closer to a global value,"min(dicts, key=lambda x: (abs(1.77672955975 - x['ratio']), -x['pixels']))"
|
Setting a fixed size for points in legend,plt.show()
|
Python parse comma-separated number into int,"int('1,000,000'.replace(',', ''))"
|
Python: print a variable in hex,print(' '.join(hex(ord(n)) for n in my_hex))
|
How do I tell matplotlib that I am done with a plot?,plt.clf()
|
Check for a valid domain name in a string?,"""""""^(?=.{4,255}$)([a-zA-Z0-9][a-zA-Z0-9-]{,61}[a-zA-Z0-9]\\.)+[a-zA-Z0-9]{2,5}$"""""""
|
How to remove multiple indexes from a list at the same time?,del my_list[index]
|
Create a list of tuples with adjacent list elements if a condition is true,"[(myList[i - 1], myList[i]) for i in range(len(myList)) if myList[i] == 9]"
|
Sum of product of combinations in a list,"sum([(i * j) for i, j in list(itertools.combinations(l, 2))])"
|
How do I use matplotlib autopct?,plt.figure()
|
Multi-line logging in Python,logging.getLogger().setLevel(logging.DEBUG)
|
How to clamp an integer to some range? (in Python),"new_index = max(0, min(new_index, len(mylist) - 1))"
|
How __hash__ is implemented in Python 3.2?,sys.hash_info
|
Python Print String To Text File,text_file.close()
|
python - How to format variable number of arguments into a string?,"'Hello %s' % ', '.join(my_args)"
|
Plotting data from CSV files using matplotlib,plt.show()
|
How to iterate over Unicode characters in Python 3?,print('U+{:04X}'.format(i))
|
How do you convert command line args in python to a dictionary?,"{'arg1': ['1', '4'], 'arg2': 'foobar'}"
|
Numpy: How to check if array contains certain numbers?,"numpy.in1d(b, a).all()"
|
How to create range of numbers in Python like in MATLAB,"print(np.linspace(1, 3, num=4, endpoint=False))"
|
Creating a numpy array of 3D coordinates from three 1D arrays,"np.vstack(np.meshgrid(x_p, y_p, z_p)).reshape(3, -1).T"
|
NumPy: Comparing Elements in Two Arrays,"array([True, False, False, True, True, False], dtype=bool)"
|
How to use 'User' as foreign key in Django 1.5,"user = models.ForeignKey(User, unique=True)"
|
"Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)","[key for key, value in list(my_dict.items()) if set(value).intersection(lst)]"
|
Dictionary to lowercase in Python,"{k.lower(): v.lower() for k, v in list({'My Key': 'My Value'}.items())}"
|
python: convert numerical data in pandas dataframe to floats in the presence of strings,"pd.read_csv(myfile.file, na_values=['na'])"
|
How do I display current time using Python + Django?,now = datetime.datetime.now().strftime('%H:%M:%S')
|
How to merge the elements in a list sequentially in python,"[''.join(seq) for seq in zip(lst, lst[1:])]"
|
"Efficiently re-indexing one level with ""forward-fill"" in a multi-index dataframe",df1['value'].unstack(0)
|
Remove repeating characters from words,"re.sub('(.)\\1+', '\\1\\1', 'haaaaapppppyyy')"
|
Python - simple reading lines from a pipe,sys.stdout.flush()
|
Can I get a lint error on implicit string joining in python?,x = 'abcde'
|
Fixing color in scatter plots in matplotlib,plt.show()
|
How do I use a dictionary to update fields in Django models?,Book.objects.filter(id=id).update()
|
How to import modules in Google App Engine?,"sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))"
|
Compare elements of a list of lists and return a list,zip(*a)
|
Splitting a List inside a Pandas DataFrame,"pd.melt(split, id_vars=['a', 'b'], value_name='TimeStamp')"
|
Read into a bytearray at an offset?,bytearray('\x00\x00\x00\x07\x08\x00\x00\x00\x00\x00')
|
arrange labels for plots on multiple panels to be in one line in matplotlib,"ax.yaxis.set_label_coords(0.5, 0.5)"
|
How to pass arguments as tuple to odeint?,"odeint(func, y0, t, args=(123, 456))"
|
Specific sort a list of numbers separated by dots,"print(sorted(L, key=lambda x: int(x.split('.')[2])))"
|
How to get a random value in python dictionary,"country, capital = random.choice(list(d.items()))"
|
Creating Unit tests for methods with global variables,unittest.main()
|
How do I find the largest integer less than x?,int(math.ceil(x)) - 1
|
How to convert a string to a function in python?,"eval('add')(x, y)"
|
"Updating a list of python dictionaries with a key, value pair from another list","[dict(d, count=n) for d, n in zip(l1, l2)]"
|
The Pythonic way to grow a list of lists,uniques = collections.defaultdict(set)
|
Python: how to normalize a confusion matrix?,C / C.astype(np.float).sum(axis=1)
|
Python-opencv: Read image data from stdin,cv2.waitKey()
|
pandas split string into columns,"df['stats'].str[1:-1].str.split(',', expand=True).astype(float)"
|
avoiding regex in pandas str.replace,"df['a'] = df['a'].str.replace('in.', ' in. ')"
|
How to remove rows with null values from kth column onward in python,"df2.dropna(subset=['three', 'four', 'five'], how='all')"
|
How to pack spheres in python?,r = [(1) for i in range(n)]
|
Calculation between groups in a Pandas multiindex dataframe,df['ratio'] = df.groupby(level=0)[3].transform(lambda x: x[0] / x[1])
|
How to properly quit a program in python,sys.exit(0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.