text stringlengths 4 1.08k |
|---|
Substitute multiple whitespace with single whitespace in Python,""""""" """""".join(mystring.split())" |
Remove NULL columns in a dataframe Pandas?,"df = df.dropna(axis=1, how='all')" |
how to use logging inside Gevent?,"logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(msg)s')" |
Extract all keys from a list of dictionaries,[i for s in [list(d.keys()) for d in LoD] for i in s] |
Pandas : Assign result of groupby to dataframe to a new column,df.groupby('adult')['weight'].transform('idxmax') |
Padding a list in python with particular value,self.myList.extend([0] * (4 - len(self.myList))) |
Python Check if all of the following items is in a list,"set(['a', 'b']).issubset(['a', 'b', 'c'])" |
Create 2d Array in Python Using For Loop Results,"[[i, i * 10] for i in range(5)]" |
Extracting date from a string in Python,"dparser.parse('monkey 20/01/1980 love banana', fuzzy=True)" |
Extracting date from a string in Python,"dparser.parse('monkey 2010-07-32 love banana', fuzzy=True)" |
Confusing with the usage of regex in Python,"re.findall('[a-z]*', 'f233op')" |
Get index of the top n values of a list in python,"sorted(list(range(len(a))), key=lambda i: a[i])[-2:]" |
Python: How to generate a 12-digit random number?,"random.randint(100000000000, 999999999999)" |
How do I divide the members of a list by the corresponding members of another list in Python?,"[(c / t) for c, t in zip(conversions, trials)]" |
Count number of occurrences of a given substring in a string,"""""""abcdabcva"""""".count('ab')" |
"Regular expression syntax for ""match nothing""?",re.compile('.\\A|.\\A*|.\\A+') |
How to implement curl -u in Python?,"r = requests.get('https://api.github.com', auth=('user', 'pass'))" |
Plotting histograms from grouped data in a pandas DataFrame,"df.reset_index().pivot('index', 'Letter', 'N').hist()" |
How do I read a text file into a string variable in Python,"str = open('very_Important.txt', 'r').read()" |
Norm along row in pandas,np.sqrt(np.square(df).sum(axis=1)) |
python map array of dictionaries to dictionary?,"dict(map(operator.itemgetter('city', 'country'), li))" |
How do I slice a string every 3 indices?,"['str', 'ing', 'Str', 'ing', 'Str', 'ing', 'Str', 'ing']" |
clicking on a link via selenium in python,link.click() |
Comparing values in two lists in Python,[(x[i] == y[i]) for i in range(len(x))] |
Most pythonic way to convert a list of tuples,[list(t) for t in zip(*list_of_tuples)] |
python regex get first part of an email address,s.split('@')[0] |
How to tell if string starts with a number?,string[0].isdigit() |
How to check if character exists in DataFrame cell,df['a'].str.contains('-') |
Converting utc time string to datetime object,"datetime.strptime('2012-03-01T10:00:00Z', '%Y-%m-%dT%H:%M:%SZ')" |
How to fold/accumulate a numpy matrix product (dot)?,"np.einsum('ij,jk,kl,lm', S0, Sx, Sy, Sz)" |
Python regex findall alternation behavior,"re.findall('\\d|\\d,\\d\\)', '6,7)')" |
Python regex alternative for join,"re.sub('(.)(?=.)', '\\1-', s)" |
Find same data in two DataFrames of different shapes,"c = pd.concat([df, df2], axis=1, keys=['df1', 'df2'])" |
Convert list of strings to dictionary,"{' Failures': '0', 'Tests run': '1', ' Errors': '0'}" |
How can I break up this long line in Python?,"'This is the first line of my text, ' + 'which will be joined to a second.'" |
How to remove all the punctuation in a string? (Python),"out = ''.join(c for c in asking if c not in ('!', '.', ':'))" |
Python : How to fill an array line by line?,"[[0, 0, 0], [1, 1, 1], [0, 0, 0]]" |
How to read integers from a file that are 24bit and little endian using Python?,"struct.unpack('<I', bytes + '\x00')" |
Python - Compress Ascii String,comptest('test') |
Python - Compress Ascii String,comptest('This is a compression test of a short sentence.') |
"Recursive ""all paths"" through a list of lists - Python","['ab', 'c', 'de', 'fg', 'h']" |
how to remove positive infinity from numpy array...if it is already converted to a number?,"np.array([0.0, pinf, ninf]) < 0" |
Printing tabular data in Python,print('%20s' % somevar) |
How do I change directories using Paramiko?,myssh.exec_command('cd ..; pwd') |
Is there a Python dict without values?,{(x ** 2) for x in range(100)} |
Remove cancelling rows from Pandas Dataframe,"df2 = df.groupby(['customer', 'invoice_nr', 'date']).sum()" |
Python and SQLite: insert into table,connection.commit() |
How to grab one random item from a database in Django/postgreSQL?,model.objects.all().order_by('?')[0] |
Selenium (with python) how to modify an element css style,"driver.execute_script(""$('#copy_link').css('visibility', 'visible');"")" |
Numpy: cartesian product of x and y array points into single array of 2D points,"numpy.dstack(numpy.meshgrid(x, y)).reshape(-1, 2)" |
How to convert python list of points to numpy image array?,numpy.array(your_list) |
Convert UTF-8 with BOM to UTF-8 with no BOM in Python,return s.decode('latin-1') |
Get the first element of each tuple in a list in Python,[x[0] for x in rows] |
How do I vectorize this loop in numpy?,"np.ma.array(np.tile(arr, 2).reshape(2, 3), mask=~cond).argmax(axis=1)" |
Splitting the sentences in python,"re.findall('\\w+', ""Don't read O'Rourke's books!"")" |
How to make curvilinear plots in matplotlib,"plt.figure(figsize=(8, 8))" |
Is it possible to effectively initialize bytearray with non-zero value?,"array([True, True, True, True, True, True, True, True, True, True], dtype=bool)" |
Python Pandas Identify Duplicated rows with Additional Column,"df.groupby(['PplNum', 'RoomNum']).cumcount() + 1" |
Python creating a dictionary of lists,"dict((i, list(range(int(i), int(i) + 2))) for i in ['1', '2'])" |
How to change the order of DataFrame columns?,"df = df[['mean', '0', '1', '2', '3']]" |
"Python, remove all non-alphabet chars from string",""""""""""""".join([i for i in s if i.isalpha()])" |
how to change the size of the sci notation above the y axis in matplotlib?,"plt.rc('font', **{'size': '30'})" |
Write to UTF-8 file in Python,file.close() |
python-numpy: Apply a function to each row of a ndarray,"np.apply_along_axis(mahalanobis_sqdist, 1, d1, mean1, Sig1)" |
Python numpy keep a list of indices of a sorted 2D array,i = a.argsort(axis=None)[::-1] |
Convert Django Model object to dict with all of the fields intact,"{'id': 1, 'reference1': 1, 'value': 1}" |
How do I build a numpy array from a generator?,my_array = numpy.array(list(gimme())) |
Dropping a single (sub-) column from a MultiIndex,"df.drop(('col1', 'a'), axis=1)" |
Python sum of ASCII values of all characters in a string,sum(ord(c) for c in string) |
Js Date object to python datetime,"datetime.strptime('Tue, 22 Nov 2011 06:00:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')" |
How can I turn 000000000001 into 1?,int('08') |
Is it possible to serve a static html page at the root of a django project?,"url('^$', TemplateView.as_view(template_name='your_template.html'))" |
How to sort multidimensional array by column?,"sorted(a, key=lambda x: x[1])" |
How to repeat individual characters in strings in Python,""""""""""""".join(map(lambda x: x * 7, 'map'))" |
How can I disable logging while running unit tests in Python Django?,logging.disable(logging.CRITICAL) |
Averages of slices on a 1d nparray: how to make it more NumPy-thonic?,np.cumsum(a[::-1])[::-1] - np.cumsum(a) |
how to find the target file's full(absolute path) of the symbolic link or soft link in python,os.path.realpath(path) |
How do I get multiple values from checkboxes in Django,request.POST.getlist('recommendations') |
How to get all children of queryset in django?,Category.objects.filter(animal__name__startswith='A') |
How do I combine two lists into a dictionary in Python?,"dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))" |
Equivalent to matlab's imagesc in matplotlib?,"ax.imshow(data, extent=[0, 1, 0, 1])" |
How to use logging with python's fileConfig and configure the logfile filename,"logging.fileConfig(loginipath, defaults={'logfilename': '/var/log/mylog.log'})" |
"Python list of dicts, get max value index","max(enumerate(ld), key=lambda item: item[1]['size'])" |
sum of squares in a list in one line?,sum(i * i for i in l) |
How do I zip keys with individual values in my lists in python?,"[dict(zip(k, x)) for x in v]" |
multi-column factorize in pandas,df.drop_duplicates() |
"If I have this string in Python, how do I decode it?",urllib.parse.unquote(string) |
How to use numpy.random.choice in a list of tuples?,"lista_elegir[np.random.choice(len(lista_elegir), 1, p=probabilit)]" |
Splitting dictionary/list inside a Pandas Column into Separate Columns,"pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)" |
What is the max length of a python string?,print(str(len(s)) + ' bytes') |
How do I slice a numpy array to get both the first and last two rows,"x[[0, 1, -2, -1]]" |
How to display Image in pygame?,"screen.blit(img, (0, 0))" |
Print a variable selected by a random number,random_choice = random.choice(choices) |
How to get UTC time in Python?,"return (now - datetime.datetime(1970, 1, 1)).total_seconds()" |
Converting a dict into a list,"['We', 'Love', 'Your', 'Dict']" |
"How can I ""unpivot"" specific columns from a pandas DataFrame?","pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')" |
Close pyplot figure using the keyboard on Mac OS X,plt.show() |
Setting Different Bar color in matplotlib Python,plt.show() |
Format number using LaTeX notation in Python,print('\\num{{{0:.2g}}}'.format(1000000000.0)) |
Python: A4 size for a plot,"rc('figure', figsize=(11.69, 8.27))" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.