text
stringlengths
4
1.08k
django rest framework - using detail_route and detail_list,"return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)"
"How to set a variable to be ""Today's"" date in Python/Pandas",pandas.to_datetime('today')
How do I get the number of lists with a particular element?,"Counter({'a': 3, 'c': 3, 'b': 2, 'd': 1})"
Numpy isnan() fails on an array of floats (from pandas dataframe apply),"np.isnan(np.array([np.nan, 0], dtype=object))"
Pandas Write table to MySQL,"df.to_sql('demand_forecast_t', engine, if_exists='replace', index=False)"
Python : How to create a dynamic list of class values,"MyList = [inst1, inst2]"
Working with nested lists in Python,result = (list_[0][0] + list_[1][0]) * (list_[0][1] + list_[1][1])
How to extract the n-th elements from a list of tuples in python?,zip(*elements)[1]
Single Line Nested For Loops,"[50.1, 50.2, 50.3, 50.4, 60.1, 60.2, 60.3, 60.4, 70.1, 70.2, 70.3, 70.4]"
Regular expression in python 2.7 to identify any non numeric symbol in a column in dataframe,print(df.applymap(lambda x: str(x).isdigit()))
Django models - how to filter out duplicate values by PK after the fact?,q = Model.objects.filter(Q(field1=f1) | Q(field2=f2)).distinct()
"Python, remove all occurrences of string in list","set(['cheese', 'tomato'])"
Matplotlib: Specify format of floats for tick lables,ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
Python Multidimensional Arrays - most efficient way to count number of non-zero entries,sum(sum(1 for i in row if i) for row in rows)
Python regular expression to replace everything but specific words,"print(re.sub('(.+?)(going|you|$)', subit, s))"
Map two lists into a dictionary in Python,"zip(keys, values)"
How do I get the raw representation of a string in Python?,return repr(s)
Pandas - conditionally select column based on row value,"pd.concat([foo['Country'], z], axis=1)"
Area intersection in Python,plt.show()
Using python to write text files with DOS line endings on linux,f.write('foo\nbar\nbaz\n')
Converting JSON String to Dictionary Not List,json1_data = json.loads(json1_str)[0]
How do I order fields of my Row objects in Spark (Python),"rdd = sc.parallelize([(1, 2)])"
How to make two markers share the same label in the legend using matplotlib?,ax.legend()
How to draw line inside a scatter plot,ax.set_title('ROC Space')
"python, writing Json to file","file.write(dumps({'numbers': n, 'strings': s, 'x': x, 'y': y}, file, indent=4))"
"How to compress with 7zip instead of zip, code changing","subprocess.call(['7z', 'a', filename + '.7z', '*.*'])"
Python logging: use milliseconds in time format,"logging.Formatter(fmt='%(asctime)s.%(msecs)03d', datefmt='%Y-%m-%d,%H:%M:%S')"
Average of tuples,sum([v[0] for v in list(d.values())]) / float(len(d))
Updating csv with data from a csv with different formatting,"df2.rename_axis({'Student': 'Name'}, axis=1, inplace=True)"
Problem with exiting a daemonized process,time.sleep(1)
Consuming COM events in Python,time.sleep(0.1)
pythonic way to delete elements from a numpy array,"smaller_array = np.delete(array, index)"
How to flush the input stream in python?,sys.stdout.flush()
Sum a csv column in python,total = sum(int(r[1]) for r in csv.reader(fin))
calculating cubic root in python,(1 + math.cos(i)) ** (1 / 3.0)
Python: Importing a file from a parent folder,sys.path.append('..')
Best way to plot an angle between two lines in Matplotlib,"ax.set_xlim(0, 7)"
Python: get int value from a char string,"int('AEAE', 16)"
Select Pandas rows based on list index,"df.iloc[([1, 3]), :]"
Matplotlib: How to make two histograms have the same bin width?,"plt.hist(b, bins)"
How can I get the IP address of eth0 in Python?,get_ip_address('eth0')
One-line expression to map dictionary to another,"[(m.get(k, k), v) for k, v in list(d.items())]"
Python(pandas): removing duplicates based on two columns keeping row with max value in another column,"df.groupby(['A', 'B']).max()['C']"
How to convert a string to its Base-10 representation?,"int(''.join([hex(ord(x))[2:] for x in 'YZ']), 16)"
How can I retrieve the current seed of NumPy's random number generator?,"print(np.random.randint(0, 100, 10))"
Inserting values into specific locations in a list in Python,"[(mylist[i:] + [newelement] + mylist[:i]) for i in range(len(mylist), -1, -1)]"
What is the most pythonic way to pop a random element from a list?,x.pop(random.randrange(len(x)))
x11 forwarding with paramiko,"ssh_client.connect('server', username='username', password='password')"
Normalize columns of pandas data frame,df = df / df.loc[df.abs().idxmax()].astype(np.float64)
Tweaking axis labels and names orientation for 3D plots in matplotlib,plt.show()
how to write to the file with array values in python?,q.write(''.join(w))
Python Pandas - Date Column to Column index,"df.reset_index(level=0, inplace=True)"
Creating a Confidence Ellipses in a sccatterplot using matplotlib,plt.show()
Python how to sort this list?,"sorted(lst, reverse=True, key=operator.itemgetter(0))"
Numpy: get index of smallest value based on conditions,"np.argwhere(a[:, (1)] == -1)[np.argmin(a[a[:, (1)] == -1, 0])]"
converting python list of strings to their type,print([tryeval(x) for x in L])
Using a conditional in the python interpreter -c command,python - mplatform
How to concatenate element-wise two lists in Python?,"[(m + str(n)) for m, n in zip(b, a)]"
Find all the occurrences of a character in a string,"[x.start() for x in re.finditer('\\|', str)]"
"Python code simplification? One line, add all in list",sum(int(n) for n in str(2 ** 1000))
Python finding substring between certain characters using regex and replace(),"match = re.search('(?<=Value=?)([^&>]+)', strJunk)"
How can I insert a new tag into a BeautifulSoup object?,"self.new_soup.body.insert(3, new_tag)"
Python implementation of Jenkins Hash?,"hash, hash2 = hashlittle2(hashstr, 3735928559, 3735928559)"
Accessing columns with MultiIndex after using pandas groupby,"g1.columns = ['agd_mean', 'agd_std', 'hgd_mean', 'hgd_std']"
Creating a list by iterating over a dictionary,"['{}_{}'.format(k, v) for k, l in list(d.items()) for v in l]"
How to split python list into chunks of equal size?,"[l[i:i + 3] for i in range(0, len(l), 3)]"
check if directory `directory ` exists and create it if necessary,"if (not os.path.exists(directory)):
os.makedirs(directory)"
subscript text 'h20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'.,"plt.plot(x, y, label='H\u2082O')"
count the occurrences of items in list `l`,"[[x, l.count(x)] for x in set(l)]"
get the largest key whose not associated with value of 0 in dictionary `x`,"(k for k, v in x.items() if v != 0)"
convert a raw string `raw_byte_string` into a normal string,raw_byte_string.decode('unicode_escape')
zip two 2-d arrays `a` and `b`,"np.array(zip(a.ravel(), b.ravel()), dtype='i4,i4').reshape(a.shape)"
replace all occurrences of a string `\n` by string `<br>` in a pandas data frame `df`,"df.replace({'\n': '<br>'}, regex=True)"
extract a url from a string `mystring`,"print(re.search('(?P<url>https?://[^\\s]+)', myString).group('url'))"
shuffle columns of an numpy array 'r',np.random.shuffle(np.transpose(r))
sorting data in dataframe pandas,"df.sort_values(['System_num', 'Dis'])"
get all matches with regex pattern `\\d+[xx]` in list of string `teststr`,"[i for i in teststr if re.search('\\d+[xX]', i)]"
call a shell script `notepad` using subprocess,subprocess.call(['notepad'])
encode a string `data to be encoded` to `ascii` encoding,encoded = 'data to be encoded'.encode('ascii')
sort a list of dictionary `mylist` by the key `title`,mylist.sort(key=lambda x: x['title'])
get the position of item `element` in list `testlist`,print(testlist.index(element))
check if object `obj` is a string,"isinstance(obj, str)"
getting the length of `my_string`,len(my_string)
numpy concatenate two arrays `a` and `b` along the second axis,"print(concatenate((a, b), axis=1))"
determine the type of variable `v`,type(v)
delete all instances of a character 'i' in a string 'it is icy',"re.sub('i', '', 'it is icy')"
converting list of strings `intstringlist` to list of integer `nums`,nums = [int(x) for x in intstringlist]
"find all files in directory ""/mydir"" with extension "".txt""","for file in os.listdir('/mydir'):
if file.endswith('.txt'):
pass"
"loop through the ip address range ""192.168.x.x""","generator = iter_iprange('192.168.1.1', '192.168.255.255', step=1)"
sort a list of dictionary `l` based on key `time` in descending order,"l = sorted(l, key=lambda a: a['time'], reverse=True)"
decode json string `request.body` to python dict,json.loads(request.body)
"split string `text` by "",""","text.split(',')"
sort list `list_of_strings` based on second index of each string `s`,"sorted(list_of_strings, key=lambda s: s.split(',')[1])"
sort a list of dictionaries `list_to_be_sorted` by the value of the dictionary key `name`,"newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])"
"write dataframe `df`, excluding index, to a csv file","df.to_csv(filename, index=False)"
convert a urllib unquoted string `unescaped` to a json data `json_data`,json_data = json.loads(unescaped)
"write line ""hi there"" to file `f`","print('hi there', file=f)"