text
stringlengths
4
1.08k
How do I generate a pcap file in Python?,os.system('rm tmp.txt')
How to replace the nth element of multi dimension lists in Python?,"[[1, 2, 3], [4, 5], ['X'], [7, 8, 9, 10]]"
Similarity of lists in Python - comparing customers according to their features,"[['100', '2', '3', '4'], ['110', '2', '5', '6'], ['120', '6', '3', '4']]"
Regex: How to match sequence of key-value pairs at end of string,"['key1: val1-words ', 'key2: val2-words ', 'key3: val3-words']"
What's the most memory efficient way to generate the combinations of a set in python?,"print(list(itertools.combinations({1, 2, 3, 4}, 3)))"
Python insert numpy array into sqlite3 database,cur.execute('create table test (arr array)')
How can I store binary values with trailing nulls in a numpy array?,"np.array([('abc\x00\x00',), ('de\x00\x00\x00',)], dtype='O')"
Convert UTF-8 with BOM to UTF-8 with no BOM in Python,u = s.decode('utf-8-sig')
Google App Engine (Python) - Uploading a file (image),imagedata.image = self.request.get('image')
scrapy: convert html string to HtmlResponse object,"response.xpath('//div[@id=""test""]/text()').extract()[0].strip()"
How to use regexp function in sqlite with sqlalchemy?,"cursor.execute('CREATE TABLE t1 (id INTEGER PRIMARY KEY, c1 TEXT)')"
Is there a way to refer to the entire matched expression in re.sub without the use of a group?,"print(re.sub('[_%^$]', '\\\\\\g<0>', line))"
Redirect stdout to a file in Python?,os.system('echo this also is not redirected')
How to get IP address of hostname inside jinja template,{{grains.fqdn_ip}}
sort dict by value python,"sorted(data, key=data.get)"
"json.loads() giving exception that it expects a value, looks like value is there","json.loads('{""distance"":\\u002d1}')"
How to set the current working directory in Python?,os.chdir('c:\\Users\\uname\\desktop\\python')
Large number of subplots with matplotlib,"fig, ax = plt.subplots(10, 10)"
Multidimensional Eucledian Distance in Python,"scipy.spatial.distance.euclidean(A, B)"
"Python - Combine two dictionaries, concatenate string values?","dict((k, d.get(k, '') + d1.get(k, '')) for k in keys)"
How to get process's grandparent id,os.popen('ps -p %d -oppid=' % os.getppid()).read().strip()
Python: How to use a list comprehension here?,[item['baz'] for foo in foos for item in foo['bar']]
How to find the cumulative sum of numbers in a list?,"subseqs = (seq[:i] for i in range(1, len(seq) + 1))"
How to determine pid of process started via os.system,proc.terminate()
How to update a plot in matplotlib?,plt.show()
Generate a heatmap in MatPlotLib using a scatter data set,plt.show()
(Django) how to get month name?,today.strftime('%B')
Pandas: joining items with same index,pd.DataFrame(df.groupby(level=0)['column_name'].apply(list).to_dict())
Plot a (polar) color wheel based on a colormap using Python/Matplotlib,plt.show()
When the key is a tuple in dictionary in Python,"d = {(a.lower(), b): v for (a, b), v in list(d.items())}"
Sorting JSON in python by a specific value,"sorted_list_of_keyvalues = sorted(list(ips_data.items()), key=item[1]['data_two'])"
How to get the length of words in a sentence?,s.split()
else if in list comprehension in Python3,"['A', 'b', 'C', 'D', 'E', 'F']"
How to save and load MLLib model in Apache Spark,"lrm.save(sc, 'lrm_model.model')"
Numpy: how to find the unique local minimum of sub matrixes in matrix A?,"[np.unravel_index(np.argmin(a), (2, 2)) for a in A2]"
How do I insert a list at the front of another list?,"a.insert(0, k)"
Python: Uniqueness for list of lists,"list(map(list, set(map(lambda i: tuple(i), testdata))))"
How to query as GROUP BY in django?,Members.objects.values('designation').annotate(dcount=Count('designation'))
Deleting multiple slices from a numpy array,"array([0, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 19])"
Grouping daily data by month in python/pandas and then normalizing,"g.dropna().reset_index().reindex(columns=['visits', 'string', 'date'])"
How can I render 3D histograms in python?,plt.show()
python matplotlib multiple bars,plt.show()
Plotting a 2D heatmap with Matplotlib,plt.show()
Get max key in dictionary,"max(list(MyCount.keys()), key=int)"
Creating a dictionary from a CSV file,"{'123': {'Foo': '456', 'Bar': '789'}, 'abc': {'Foo': 'def', 'Bar': 'ghi'}}"
how to extract frequency associated with fft values in python,"numpy.fft.fft([1, 2, 1, 0, 1, 2, 1, 0])"
Change a string of integers separated by spaces to a list of int,"x = map(int, x.split())"
Python : How to plot 3d graphs using Python?,plt.show()
Divide the values of two dictionaries in python,{k: (float(d2[k]) / d1[k]) for k in d2}
Python: How to remove all duplicate items from a list,woduplicates = list(set(lseperatedOrblist))
Python Pandas: How to move one row to the first row of a Dataframe?,"df.reindex([2, 0, 1] + list(range(3, len(df))))"
python: deleting numbers in a file,"fin = open('C:\\folder1\\test1.txt', 'r')"
"Python - How do I write a more efficient, Pythonic reduce?",a.contains(b)
How do I do a not equal in Django queryset filtering?,results = Model.objects.filter(x=5).exclude(a=true)
Getting the correct timezone offset in Python using local timezone,dt = pytz.utc.localize(dt)
How do you extract a column from a multi-dimensional array?,"[1, 2, 3]"
Format string by binary list,"['-', 't', '-', 'c', '-', 'over', '----']"
Output first 100 characters in a string,print(my_string[0:100])
Pythonic way to convert list of dicts into list of namedtuples,"items = [some(m['a'].split(), m['d'], m['n']) for m in dl]"
Python: Lambda function in List Comprehensions,[lambda x: (x * x for x in range(10))]
Extracting data from a text file with Python,print('\n'.join(to_search[NAME]))
Ranking of numpy array with possible duplicates,"array([0, 1, 4, 5, 6, 1, 7, 8, 8, 1])"
Flask: How to handle application/octet-stream,app.run()
Splitting a list in python,"['4', ')', '/', '3', '.', 'x', '^', '2']"
numpy: how to select rows based on a bunch of criteria,"a[np.in1d(a[:, (1)], b)]"
looking for a more pythonic way to access the database,cursor.execute('delete from ...')
Python - how to convert int to string represent a 32bit Hex number,"""""""0x{0:08X}"""""".format(3652458)"
Python - read text file with weird utf-16 format,print(line.decode('utf-16-le').split())
python string format() with dict with integer keys,'hello there %(5)s' % {'5': 'you'}
Most efficient way to forward-fill NaN values in numpy array,"arr[mask] = arr[np.nonzero(mask)[0], idx[mask]]"
Counting unique index values in Pandas groupby,ex.groupby(level='A').agg(lambda x: x.index.get_level_values(1).nunique())
Unable to parse TAB in JSON files,{'My_string': 'Foo bar.\t Bar foo.'}
simple/efficient way to expand a pandas dataframe,"pd.merge(y, x, on='k')[['a', 'b', 'y']]"
Creating a list from a Scipy matrix,"x = scipy.matrix([1, 2, 3]).transpose()"
Tkinter - How to create a combo box with autocompletion ,root.mainloop()
How to get alpha value of a PNG image with PIL?,alpha = img.split()[-1]
how to get all the values from a numpy array excluding a certain index?,a[np.arange(len(a)) != 3]
How to add columns to sqlite3 python?,"c.execute(""alter table linksauthor add column '%s' 'float'"" % author)"
Python Pandas: How to move one row to the first row of a Dataframe?,df.sort(inplace=True)
How do you call a python file that requires a command line argument from within another python file?,"call(['path/to/python', 'test2.py', 'neededArgumetGoHere'])"
How to reliably open a file in the same directory as a Python script,"f = open(os.path.join(__location__, 'bundled-resource.jpg'))"
How to custom sort an alphanumeric list?,"sorted(l, key=lambda x: x.replace('0', 'Z'))"
Pandas: how to change all the values of a column?,df['Date'] = df['Date'].apply(convert_to_year)
Python returning unique words from a list (case insensitive),"['We', 'are', 'one', 'the', 'world', 'UNIVERSE']"
Converting datetime.date to UTC timestamp in Python,"timestamp = (dt - datetime(1970, 1, 1)).total_seconds()"
Sorting a list of dictionaries based on the order of values of another list,listTwo.sort(key=lambda x: order_dict[x['eyecolor']])
How do I add a title to Seaborn Heatmap?,plt.show()
Local import statements in Python,"foo = __import__('foo', globals(), locals(), [], -1)"
Pandas: aggregate based on filter on another column,"df.groupby(['Month', 'Fruit']).sum().unstack(level=0)"
How to convert unicode text to normal text,elems[0].getText().encode('utf-8')
python get time stamp on file in mm/dd/yyyy format,"time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))"
First non-null value per row from a list of Pandas columns,df.stack()
How to print a tree in Python?,print_tree(shame)
Rearrange tuple of tuples in Python,tuple(zip(*t))
Converting timezone-aware datetime to local time in Python,datetime.datetime.fromtimestamp(calendar.timegm(d.timetuple()))
Convert timestamp since epoch to datetime.datetime,"time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(1346114717972 / 1000.0))"
Renaming multiple files in python,"re.sub('.{20}(.mkv)', '\\1', 'unique12345678901234567890.mkv')"
How do you send a HEAD HTTP request in Python 2?,print(response.geturl())
add line based on slope and intercept in matplotlib?,plt.show()
Find the last substring after a character,"""""""foo:bar:baz:spam:eggs"""""".rsplit(':', 3)"