Unnamed: 0 int64 0 378k | id int64 49.9k 73.8M | title stringlengths 15 150 | question stringlengths 37 64.2k | answer stringlengths 37 44.1k | tags stringlengths 5 106 | score int64 -10 5.87k |
|---|---|---|---|---|---|---|
351,700 | 39,359,621 | Access all elements at given x, y position in 3-dimensional numpy array | <pre><code>mat_a = np.random.random((5, 5))
mat_b = np.random.random((5, 5))
mat_c = np.random.random((5, 5))
bigmat = np.stack((mat_a, mat_b, mat_c)) # this is a 3, 5, 5 array
for (x, y, z), value in np.ndenumerate(bigmat):
print (x, y, z)
</code></pre>
<p>In the example above, how can I loop so that I iterate o... | <p>There is a function that generates all indices for a given shape, <code>ndindex</code>. </p>
<pre><code>for y,z in np.ndindex(bigmat.shape[1:]):
print(y,z,bigmat[:,y,z])
0 0 [ 0 25 50]
0 1 [ 1 26 51]
0 2 [ 2 27 52]
0 3 [ 3 28 53]
0 4 [ 4 29 54]
1 0 [ 5 30 55]
1 1 [ 6 31 56]
...
</code></pre>
<p>For a simple ... | python|numpy | 3 |
351,701 | 38,985,011 | How to append a tuple to a numpy array without it being preformed element-wise? | <p>If I try </p>
<p><code>x = np.append(x, (2,3))</code></p>
<p>the tuple <code>(2,3)</code> does not get appended to the end of the array, rather <code>2</code> and <code>3</code> get appended individually, even if I originally declared <code>x</code> as </p>
<p><code>x = np.array([], dtype = tuple)</code> </p>
<p... | <p>I agree with @user2357112 comment:</p>
<blockquote>
<p>appending to NumPy arrays is catastrophically slower than appending to ordinary lists. It's an operation that they are not at all designed for</p>
</blockquote>
<p>Here's a little benchmark:</p>
<pre><code># measure execution time
import timeit
import numpy... | python|arrays|numpy | 9 |
351,702 | 39,312,677 | Changing values of indexes by magnitude | <p>I'm trying to make a flexible algorithm that will take values out of a 50 by 50 array (which contains pixel values from a fits image) if they are too high.
they are too high (in python). The first thing I tried to do was this:</p>
<pre><code>file = pf.open('/Users/Vofun/desktop/file.fits')
data = np.array(file[0].... | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean-array-indexing" rel="nofollow">boolean indexing</a> to change your data.</p>
<pre><code>import numpy as np
a = np.random.random_integers(40, 60, (5,5))
>>> a
array([[58, 58, 43, 56, 54],
[59, 40, 42, 52, 45]... | python|python-2.7|numpy|multidimensional-array | 1 |
351,703 | 38,997,228 | Python: Convert map in kilometres to degrees | <p>I have a pandas Dataframe with a few million rows, each with an X and Y attribute with their location in kilometres according to the WGS 1984 World Mercator projection (created using ArcGIS).</p>
<p>What is the easiest way to project these points back to degrees, without leaving the Python/pandas environment?</p> | <p>There is already a python module that can do these kind of transformations for you called <a href="https://github.com/jswhit/pyproj" rel="nofollow noreferrer">pyproj</a>. I will agree it is actually not the simplest module to find via google. Some examples of its use can be seen <a href="https://gis.stackexchange.co... | python|pandas|projection|degrees | 1 |
351,704 | 39,165,992 | converting appended images list in Pandas dataframe | <p>I have a list which I created after appending the images from a folder </p>
<pre><code>samples=[]
for filename in glob.glob(path + '/*.png'):
samples.append(misc.imread(filename))
</code></pre>
<p>And a sample of the list looks like </p>
<pre><code>[array([[ 4, 4, 4, ..., 5, 5, 4],
[ 5, 5, 5, ..... | <p>Try adding .reshape(-1) while appending an image. </p>
<pre><code>for filename in glob.glob(path + '/*.png'):
samples.append(misc.imread(filename).reshape(-1))
df = pd.DataFrame.from_records(samples)
</code></pre>
<p>If you want to 3d version please read
<a href="https://stackoverflow.com/questions/6627647/re... | python|pandas|dataframe|scipy | 0 |
351,705 | 39,284,989 | Parallelize pandas apply | <p>New to pandas, I already want to parallelize a row-wise apply operation. So far I found <a href="https://stackoverflow.com/questions/26187759/parallelize-apply-after-pandas-groupby">Parallelize apply after pandas groupby</a> However, that only seems to work for grouped data frames.</p>
<p>My use case is different: ... | <p>For the parallel approach this is the answer based on <a href="https://stackoverflow.com/questions/26187759/parallelize-apply-after-pandas-groupby">Parallelize apply after pandas groupby</a>:</p>
<pre><code>from joblib import Parallel, delayed
import multiprocessing
def get_nearest_dateParallel(df):
df['daysBe... | python|pandas|parallel-processing|apply|embarrassingly-parallel | 6 |
351,706 | 19,397,257 | numpy matrix of hour (24) and day (365) | <p>I have two vectors; one for hours in the day <code>[1,2,3,...,24]</code>, and the second for days in the
year <code>[1,2,3,4,5,6,...,365]</code></p>
<p>I would like to construct a matrix of 24*365 cells, 24 rows and 365 columns.</p>
<p>Something like:</p>
<pre><code>a = [(1,24),(2,24),(3,24),(4,24),(5,24),...,(3... | <p>It's probably worth noting that while you might be able to store general purpose objects in numpy arrays, it probably isn't a good idea - most of the algorithms are optimised to have a single value in each slot in the matrix.</p>
<p>The consequence of this is that you're probably not going to end up with a 24 x 365... | python|numpy|matrix | 1 |
351,707 | 19,660,582 | Geometric warp of image in python | <p>I would like to use python to perform a geometric transform over an image, to 'straighten' or rectify an image along a given curve. It seems that scikit-image <code>ProjectiveTransform()</code> and <code>warp()</code> are very good for this, but the documentation is sparse. I followed the documentation <a href="http... | <p>A <code>ProjectiveTransform</code> is a linear transformation, and cannot match your deformation scheme. There may be better options, but for arbitrary curves you can make it work with a <code>PiecewiseAffineTransform</code>, which will match anything you throw at it by tessellating linear transformations. If you si... | python|image-processing|numpy|scikit-image | 8 |
351,708 | 19,384,532 | Get statistics for each group (such as count, mean, etc) using pandas GroupBy? | <p>I have a data frame <code>df</code> and I use several columns from it to <code>groupby</code>:</p>
<pre><code>df['col1','col2','col3','col4'].groupby(['col1','col2']).mean()
</code></pre>
<p>In the above way I almost get the table (data frame) that I need. What is missing is an additional column that contains numb... | <h2>Quick Answer:</h2>
<p>The simplest way to get row counts per group is by calling <code>.size()</code>, which returns a <code>Series</code>:</p>
<pre><code>df.groupby(['col1','col2']).size()
</code></pre>
<p><br>
Usually you want this result as a <code>DataFrame</code> (instead of a <code>Series</code>) so you c... | python|pandas|dataframe|group-by|pandas-groupby | 1,360 |
351,709 | 19,739,503 | DFT matrix in python | <p>What's the easiest way to get the <a href="http://en.wikipedia.org/wiki/DFT_matrix">DFT matrix</a> for 2-d DFT in python? I could not find such function in <a href="http://docs.scipy.org/doc/numpy/reference/routines.fft.html">numpy.fft</a>. Thanks!</p> | <p>The easiest and most likely the fastest method would be using fft from SciPy. </p>
<pre><code>import scipy as sp
def dftmtx(N):
return sp.fft(sp.eye(N))
</code></pre>
<p>If you know even faster way (might be more complicated) I'd appreciate your input. </p>
<p>Just to make it more relevant to the main questi... | python|numpy|scipy|fft|dft | 19 |
351,710 | 19,799,197 | Overwrite char (or std::string) array positions with SWIG? | <p>I was able to write a void function in C/C++, and wrap to Python/Numpy with SWIG <code>(int* INPLACE_ARRAY1, int DIM1)</code>, that receives a <code>int* vector</code> as parameter, do some math on this vector, and overwrite the results on the same vector, and this result was available inside Python's object. Like f... | <p>Use std::vector: </p>
<pre><code>void vetor_char2D(std::vector<std::string>& vetorchar)
{
for (int i = 0; i < vetorchar.size(); i++)
vetorchar[i] = "b";
};
</code></pre>
<p>which indicates clearly that the vector can be modified, and strings within it can be modified, and the SWIG typemaps f... | python|arrays|numpy|char|swig | 0 |
351,711 | 19,402,069 | Numpy Slicing slow? | <p>Hi I am running scientific computing using numpy + numba.
I've realized that numpy array addition in-place is very slow... compared to matlab</p>
<p>here is the matlab code:</p>
<pre><code>tic;
% A,B are 2-d matrices, ind may not be distinct
for ii=1:N
A(ind(ii),:) = A(ind(ii),:) + B(ii,:);
end
toc;
</code>... | <p>Try</p>
<pre><code>A[ind] += B[:N]
</code></pre>
<p>i.e. without any loop.</p>
<p>If <code>ind</code> could have duplicate elements, you can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ufunc.at.html" rel="nofollow"><code>np.add.at</code></a>:</p>
<pre><code>np.add.at(A, ind, B[:... | python|arrays|numpy|matrix|numba | 3 |
351,712 | 19,710,366 | Elementwise logical checks using numpy arrays | <p>I have an array with dimensions (10x10) and i want to create another one (10x10). Lets say the first one is called A and the second one B. I want B to have 0 value if the value of A is zero respectively or another value(specified by me) lets say c if the value of A is not zero. </p>
<p>something like that</p>
<pre... | <p>You can use <code>np.where</code>:</p>
<pre><code>>>> A
array([[3, 2, 0, 3],
[0, 3, 3, 0],
[3, 1, 1, 0],
[2, 1, 3, 1]])
>>> np.where(A==0, 0, 5)
array([[5, 5, 0, 5],
[0, 5, 5, 0],
[5, 5, 5, 0],
[5, 5, 5, 5]])
</code></pre>
<p>This basically says where <c... | python|arrays|numpy | 3 |
351,713 | 19,457,140 | 2D kernel density e. in python - x axis crowded and shrinked | <p>I have a <code>x,y</code> distribution of points for which I obtain the KDE through <code>scipy.stats.gaussian_kde.</code></p>
<p>Both <code>kms</code> and <code>mins</code> are a list with float values representing the time needed to cover the amount of kilometres.</p>
<p>The values are distributed between:</p>
... | <p>You can change the aspect ratio of the plot from 1:1 to automatic via</p>
<p><code>ax.axis('normal')</code></p> | python|numpy|matplotlib|kernel-density|probability-density | 2 |
351,714 | 19,465,012 | " Cannot locate working compiler " in OSX while installing numpy with pip to python 3.3 | <p>Under <strong>OSX 10.8.5</strong>, I was trying to install the latest version <em>python 3.3.2</em> with IDLE and wanted to import package.
I followed the instruction and installed the pip under Library, but face problem while executing the command : <strong>pip install numpy</strong> </p>
<p>It ends up with showi... | <p>You need a C/C++ compiler in order to compile some modules of Numpy. You have to install latest version of XCode.</p> | python|macos|python-3.x|numpy|pip | 1 |
351,715 | 19,546,507 | Outputting a DataFrame instead of Series from a multiple return value groupby-apply operation | <p>Edit:</p>
<p>I need the apply function that returns several value from several complex calculations. I can return those values in a tuple, and thus the outcome of the groupby-apply action would be a Series with group name as indexes and the tuple as values. I would like it to return a DataFrame instead, So I could ... | <p>Ok, I have two solutions for this. the first one is probably better, still I would appreciate a comment from the expert. first option is to have the applied function return a tuple and then convert the Series of tuples to a DataFrame:</p>
<pre><code>s = x.groupby('ID1').apply(calc)
DataFrame(s.tolist(),index = s.in... | python|pandas | 1 |
351,716 | 19,639,596 | Efficiently writing large Pandas data frames to disk | <p>I am trying to find the best way to efficiently write large data frames (250MB+) to and from disk using Python/Pandas. I've tried all of the methods in <strong>Python for Data Analysis</strong>, but the performance has been very disappointing.</p>
<p>This is part of a larger project exploring migrating our current... | <p>Using <code>HDFStore</code> is your best bet (not covered very much in the book, and has changed quite a lot). You will find performance is MUCH better than any other serialization method.</p>
<ul>
<li><p><a href="http://pandas.pydata.org/pandas-docs/dev/io.html#hdf5-pytables" rel="nofollow noreferrer">How to write... | python|pandas | 10 |
351,717 | 12,910,187 | Pandas DataFrame slicing by day/hour/minute | <p>I have pandas Dataframe with datetime index like 'YYYY-MM-DD HH:MM:SS'.</p>
<pre><code>Index Parameter
2007-05-02 14:14:08 134.8
2007-05-02 14:14:32 134.8
2007-05-02 14:14:41 134.8
2007-05-02 14:14:53 134.8
2007-05-02 14:15:01 134.8
2007-05-02 14:15:09 134.8
......
2007-05... | <p>use <code>df.ix[x:y]</code> where <code>x</code> and <code>y</code> are datetime objects.</p>
<p>Example:</p>
<pre><code>In [117]: frame.index.summary()
Out[117]: 'DatetimeIndex: 6312960 entries, 2000-04-05 00:01:00 to 2012-04-06 00:00:00\nFreq: T'
In [118]: x=datetime(2001, 4, 5, 0, 1)
In [119]: y=datetime(200... | python|pandas|slice | 12 |
351,718 | 12,935,098 | How to plot line (polygonal chain) with numpy/scipy/matplotlib with minimal smoothing | <p>I am trying to plot a line in matplotlib.. I am searching for the right type of interpolation.. I want something like this</p>
<p><img src="https://i.stack.imgur.com/gIAd2.png" alt="taken from canvasxpress.org/line.html"></p>
<p>where every line is smoothed. I tried several combination of scipy and matplotlib, suc... | <p>For that type of graph, you want <em>monotonic</em> interpolation. The <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.PchipInterpolator.html" rel="noreferrer"><code>PchipInterpolator</code></a> class (which you can refer to by its shorter alias <code>pchip</code>) in scipy.interpolat... | python|numpy|matplotlib|scipy|spline | 12 |
351,719 | 29,171,435 | Python, split array by gradient of dataset | <p>I'm novice when it comes to programming of any sort. </p>
<p>I have a set of x and y values. </p>
<pre><code>x = [1.3, 2.1, 3.5, 4.0, 3.9, 3.1, 2.7, 1.5, 1.7, 2.0, 3.6, 4.2]
y = [1.0, 1.4, 2.0, 2.2, 2.7, 3.1, 3.3, 3.9, 4.3, 4.4, 5.0, 5.5]
</code></pre>
<p>I want to separate them every time the gradient of x chang... | <p>If I understand what you want, you can first use the sign changing algorithm from <a href="https://stackoverflow.com/questions/2652368/how-to-detect-a-sign-change-for-elements-in-a-numpy-array">How to detect a sign change for elements in a numpy array</a>
to build an array of sign change location:</p>
<pre><code>im... | python|list|numpy | 1 |
351,720 | 28,936,080 | Pandas 0.15.2 MultiIndex vs. 0.14.1 (datetime.date vs. pandas.tslib.Timestamp) | <p>When upgrading from Pandas 0.14.1 to 0.15.2, I've experienced a break in my code which I've traced it down to a MultiIndex assignment now returning a pandas.tslib.Timestamp, whereas before it was a datetime.date.</p>
<p>Has anyone else experienced something similar? Is this a desired feature, or a bug in 0.15.2? ... | <p>This was a bug in index construction, see <a href="https://github.com/pydata/pandas/issues/7888" rel="nofollow">here</a></p>
<p>Here's an example of how to use an actual <code>datetime.date</code> object</p>
<pre><code>In [8]: pd.MultiIndex.from_arrays([Index([datetime.date(2013,1,1)]),['a']])
Out[8]:
MultiIndex(... | python|pandas | 1 |
351,721 | 29,336,824 | How to obtain 2 separate plots in seaborn? | <p>I have a big function which output is a dataframe and 2 charts. Something like this:</p>
<pre><code>summary = pd.concat([mean, std], axis=1)
chart1 = sns.tsplot(sample['x'].cumsum())
chart2 = sns.tsplot(summary['mean'])
result = [summary, chart1, chart2]
return result
</code></pre>
<p>Everything works fine, except... | <p>Feed explicit matplotlib objects to <code>tsplot</code>:</p>
<pre><code>import matplotlib.pyplot as plt
import seaborn as sns
def whatever(mean, std, *args, **kwargs):
summary = pd.concat([mean, std], axis=1)
chart1, ax1 = plt.subplots()
sns.tsplot(sample['x'].cumsum(), ax=ax1)
chart2, ax2 = plt.su... | python|python-2.7|pandas|seaborn | 6 |
351,722 | 29,213,625 | NumPy: Uniformly distributed N-dimensional samples | <p>Suppose I have a list of ranges (in a form of lower bound and upper bound, inclusive) <code>ranges = [(lb1, ub1), (lb2, ub2)...]</code> and a positive number <code>k</code>. Is there some way how to sample <code>k</code> N-dimensional vectors (N is given by <code>len(ranges)</code>) from the N-dimensional interval g... | <p>If the points are independent, then there should be clusters. So, you want the points not to be independent. You want something like a <a href="http://en.wikipedia.org/wiki/Low-discrepancy_sequence" rel="nofollow noreferrer">low discrepancy sequence</a> in N dimensions. One type of low discrepancy sequence in N dime... | algorithm|python-3.x|numpy | 2 |
351,723 | 29,168,699 | cryptic scipy "could not convert integer scalar" error | <p>I am constructing a sparse vector using a <code>scipy.sparse.csr_matrix</code> like so:</p>
<pre><code>csr_matrix((values, (np.zeros(len(indices)), indices)), shape = (1, max_index))
</code></pre>
<p>This works fine for most of my data, but occasionally I get a <code>ValueError: could not convert integer scalar</c... | <p>Might it be that max_index > 2**31 ?
Try this, just to make sure:</p>
<p><code>csr_matrix((vals, (np.zeros(10), inds/2)), shape = (1, max_index/2))</code></p> | python|numpy|scipy|sparse-matrix | 1 |
351,724 | 29,020,298 | Pandas : determine mapping from unique rows to original dataframe | <p>Given the following inputs: </p>
<pre><code>In [18]: input
Out[18]:
1 2 3 4
0 1 5 9 1
1 2 6 10 2
2 1 5 9 1
3 1 5 9 1
In [26]: df = input.drop_duplicates()
Out[26]:
1 2 3 4
0 1 5 9 1
1 2 6 10 2
</code></pre>
<p>How would I go about getting an array that has the indices of ... | <p>One way would be to treat it as a <code>groupby</code> on all columns:</p>
<pre><code>>> df.groupby(list(df.columns)).groups
{(1, 5, 9, 1): [0, 2, 3], (2, 6, 10, 2): [1]}
</code></pre>
<p>Another would be to <code>sort</code> and then compare, which is less efficient in theory but could very well be faster i... | python|pandas | 1 |
351,725 | 29,148,421 | np.dot for multiple product between 2D matrices | <p>I have a code where I need to operate a lot of multiplications between matrices. The code is meant to be used for 2D matrices of arbitrary dimension n, which in principle could be very large, making the program very slow.
So far, in order to operate the multiplications, I have always used np.dot, as in the following... | <p>Because of the <a href="http://en.wikipedia.org/wiki/Trace_(linear_algebra)#Trace_of_a_product" rel="nofollow">properties of the trace</a> this computation can be rewritten as follows, which reduces the number of matrix multiplications from 7 to 4:</p>
<pre><code>def getV(csi, k, e, e2):
temp = k.dot(csi).dot(k... | python|performance|numpy|matrix|multiplication | 3 |
351,726 | 33,633,370 | How to print the value of a Tensor object in TensorFlow? | <p>I have been using the introductory example of matrix multiplication in TensorFlow.</p>
<pre><code>matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
</code></pre>
<p>When I print the product, it is displaying it as a <code>Tensor</code> object:</p>
<pre><cod... | <p>The easiest<sup>[A]</sup> way to evaluate the actual value of a <code>Tensor</code> object is to pass it to the <code>Session.run()</code> method, or call <code>Tensor.eval()</code> when you have a default session (i.e. in a <code>with tf.Session():</code> block, or see below). In general<sup>[B]</sup>, you cannot p... | python|tensorflow|tensor | 274 |
351,727 | 33,805,689 | Converting Dictionary to Dataframe with tuple as key | <p>I have a dictionary like this</p>
<pre><code>df_dict = {(7, 'hello'): {1}, (1, 'fox'): {2}}
</code></pre>
<p>I want to transform it into a dataframe where the first part of the tuple is the row header, and the second part of the tuple is the column header. I tried this: </p>
<pre><code>doc_df = pd.DataFrame(df_d... | <p>The reason you're getting the <code>TypeError</code> is that <code>df_dict.keys()</code> is an iterator which yields keys from the <code>dict</code> one by one. The elements it yields will be <code>(7, 'hello')</code> and <code>(1, 'fox')</code>, but it doesn't "know" that in advance. The iterator itself doesn't hav... | python|pandas | 4 |
351,728 | 33,837,092 | panda add several new columns based on values from other columns at the same time? | <p>How to add several new columns based on values from other columns <strong>at the same time</strong>? I only found examples to add a row one at a time.</p>
<p>I am able to add 3 new columns but this does not seem efficient since it has to go through all the rows 3 times.
Is there a way to traverse the DF once?</p>
... | <p>I wouldn't use a lambda function. Simple vectorized implementation is both faster and easier to read.</p>
<pre><code>df['C'] = df['B'] - 1000
df['D'] = df['B'] ** 2
df['E'] = df['B'] / 2
>>> df
A B C D E
0 2 628.00 -372.00 394384.0000 314.00
1 1 383.00 -617.0... | python|python-3.x|pandas | 1 |
351,729 | 33,769,860 | Pandas apply but only for rows where a condition is met | <p>I would like to use Pandas <code>df.apply</code> but only for certain rows</p>
<p>As an example, I want to do something like this, but my actual issue is a little more complicated:</p>
<pre><code>import pandas as pd
import math
z = pd.DataFrame({'a':[4.0,5.0,6.0,7.0,8.0],'b':[6.0,0,5.0,0,1.0]})
z.where(z['b'] != 0... | <p>The other answers are excellent, but I thought I'd add one other approach that can be faster in some circumstances – using broadcasting and masking to achieve the same result:</p>
<pre><code>import numpy as np
mask = (z['b'] != 0)
z_valid = z[mask]
z['c'] = 0
z.loc[mask, 'c'] = z_valid['a'] / np.log(z_valid['b'])... | python|pandas|dataframe|apply | 89 |
351,730 | 33,643,843 | Can't drop NAN with dropna in pandas | <p>I import pandas as pd and run the code below and get the following result</p>
<p>Code:</p>
<pre><code>traindataset = pd.read_csv('/Users/train.csv')
print traindataset.dtypes
print traindataset.shape
print traindataset.iloc[25,3]
traindataset.dropna(how='any')
print traindataset.iloc[25,3]
print traindataset.shape... | <p>You need to read <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.dropna.html" rel="noreferrer">the documentation</a> (emphasis added):</p>
<blockquote>
<p><strong>Return</strong> object with labels on given axis omitted</p>
</blockquote>
<p><code>dropna</code> <em>returns</em>... | python|pandas|dataframe|missing-data | 27 |
351,731 | 33,944,683 | Tensorflow "map operation" for tensor? | <p>I am adapting the <a href="https://tensorflow.googlesource.com/tensorflow/+/master/tensorflow/models/image/cifar10/cifar10.py" rel="noreferrer">cifar10 convolution example</a> to my problem. I'd like to change the data input from a design that reads images one-at-a-time from a file to a design that operates on an ... | <p>As of version 0.8 there is <code>map_fn</code>. From the <a href="https://www.tensorflow.org/api_docs/python/functional_ops/higher_order_operators#map_fn" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>map_fn(fn, elems, dtype=None, parallel_iterations=10, back_prop=True,
swap_memory=False, name=None)</... | python|functional-programming|tensorflow | 10 |
351,732 | 33,734,342 | Search for value in dataframe that contains a list | <p>I have a dataframe that looks like this :</p>
<pre><code>id points
a [c,v,b,n]
b []
c [x,a]
....
</code></pre>
<p>and a dictionary (i also have it as dataframe):</p>
<pre><code>{'a': ['j','c'],
'b': [p,r,q]
'c': [n,k,l,x,a]
....}
</code></pre>
<p>I want to search if the key of the dictionary is contain... | <p>You can call <code>apply</code> and convert your dict values into a set can convert the <code>intersection</code> to a list:</p>
<pre><code>In [15]:
d={'a': ['j','c'],
'b': ['p','r','q'],
'c': ['n','k','l','x','a']}
d
Out[15]:
{'a': ['j', 'c'], 'b': ['p', 'r', 'q'], 'c': ['n', 'k', 'l', 'x', 'a']}
In [17]:
df['... | python|dictionary|pandas|dataframe | 1 |
351,733 | 33,588,670 | Having trouble with a Seaborn Plot from a multilevel Pandas Dataframe | <p>I'm working with a csv file that I've read into pandas using the following command:</p>
<pre><code>RawData = pd.read_csv(rawData_file_path, engine='python', header=[0,1])
</code></pre>
<p>This creates a DataFrame object where rows 1 and 2 are header rows in each column. Something like this:</p>
<pre><code>-------... | <p>Seaborn functions like <code>countplot</code> assume that you have <a href="http://vita.had.co.nz/papers/tidy-data.pdf" rel="nofollow">tidy data</a>. Briefly: each variable should be a column, and each observation should be a row. You will want to find a way to format your dataframe so that it is in this basic struc... | python|pandas|seaborn | 2 |
351,734 | 33,966,150 | How to splitting a dataframe into parts by specific values of a column? | <p>I have a <code>pandas</code> dataframe matrix that looks like this:</p>
<pre><code> Store Sales year month day
0 1 5263 2015 7 31
1 1 5020 2015 7 30
2 1 4782 2015 7 29
3 2 5011 2015 8 28
4 2 6102 2015 9 27
[986159 rows x 5 columns]
</code></pre>
<p>I ... | <p>The syntax of the operation is incorrect, replace the above split with the following. You also need to wrap each predicate in parens and use '|' (or) and '&' (and). This will perform the appropriate splits.</p>
<pre><code>train_X1 = train[(train['month'] == 9) | (train['month'] == 8)]
train_X2 = train[(train[... | python|pandas|dataframe | 1 |
351,735 | 33,753,655 | TypeError: 'str' object is not callable in Ipython console, but not externally | <p>Executing: </p>
<pre><code>import numpy as np
x = np.array([ 0.815, 0.02 , -0.053])
" ".join(map(str, x))
</code></pre>
<p>in the IPython console gives me the error:</p>
<pre><code>TypeError: 'str' object is not callable
</code></pre>
<p>But, when I execute this on a external system terminal, it works fine!</p> | <p>You have made either <code>str</code> or <code>map</code> a string:</p>
<pre><code>>>> map = 'some string'
>>> x = [1, 2]
>>> " ".join(map(str, x))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> del... | python|python-2.7|numpy | 3 |
351,736 | 33,740,813 | Pandas set row values on dataframe subset | <p>I have a MWE that looks like this:</p>
<pre><code>import pandas as pd
test = pd.DataFrame({'A':['a','b'], 'B':['c','d']})
</code></pre>
<p>I want to replace the values in column B with a string, if the respective values in column A are equal to 'a'. I've tried a few things:</p>
<pre><code>In [27]: test[test['A']=... | <pre><code>In [64]:
test.B.loc[test.A == 'a'] = 'Replacement'
test
Out[64]:
A B
0 a Replacement
1 b d
</code></pre> | python|pandas|dataframe|subset | 3 |
351,737 | 33,643,146 | looping through dataframe add rows to column pandas python | <p>i have a dataset that i read in:</p>
<pre><code>import pandas as pd
data = pd.read_excel('.../data.xlsx')
</code></pre>
<p>the content looks like this:</p>
<pre><code>Out[57]:
Block Concentration Name value
1 100 GlcNAc2 321
1 100 ... | <p>Consider using <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow">groupby apply functions</a> to dataset. The first function averages the values only for 'Print Buffer' using <code>mean()</code>, leaving the others in Block zero. And then the... | python|pandas | 1 |
351,738 | 33,657,041 | How to convert date format when reading from Excel - Python | <p>I am reading from an Excel sheet. The header is date in the format of Month-Year and I want to keep it that way. But when it reades it, it changes the format to "2014-01-01 00:00:00". I wrote the following peice to fix it, but doesn't work.</p>
<pre><code>import pandas as pd
import numpy as np
import datetime
from ... | <pre><code>import datetime
df = pd.DataFrame({'data': ["11/14/2015 00:00:00", "11/14/2015 00:10:00", "11/14/2015 00:20:00"]})
df["data"].apply(lambda x: datetime.datetime.strptime(x, '%m/%d/%Y %H:%M:%S').strftime('%b-%y'))
</code></pre>
<p><strong>EDIT</strong></p>
<p>If you'd like to work with <code>df.columns</code... | python|datetime|pandas|type-conversion|datetime-format | 1 |
351,739 | 33,529,722 | Matrix with identical diagonals | <p>Please refer to the below:</p>
<p><a href="https://stackoverflow.com/questions/33523552/constructing-a-special-matrix-in-numpy-dynamically/33523779?noredirect=1#comment54833151_33523779">Constructing a special matrix in numpy dynamically</a></p>
<p>Is there a way to now actually create a matrix in a similar fashio... | <p>Personally, I think @Divakar's suggestion is best, with using <code>numpy.kron</code> in conjunction with <code>numpy.eye</code>. The key is to use the <code>np.eye(N, M=N, k)</code>, where <code>k</code> specifies the diagonal of the identity matrix. Use <code>k = 0</code> for the standard identity, but for off-d... | python|numpy|matrix | 2 |
351,740 | 33,634,525 | TensorFlow on 32-bit Linux? | <p>Is there a version of TensorFlow for 32-bit Linux? I only see the 64-bit wheel available, and didn't find anything about it on the site.</p> | <p>We have only tested the TensorFlow distribution on 64-bit Linux and Mac OS X, and distribute binary packages for those platforms only. Try following the <a href="http://tensorflow.org/get_started/os_setup.md#installing_from_sources">source installation instructions</a> to build a version for your platform.</p>
<p><... | tensorflow | 26 |
351,741 | 23,691,757 | Python: from list of tuples of arrays to list of lists | <p>I don't know how I messed up with code properties, but I ended up with a monster: a list whose elements are tuples whose elements are arrays...</p>
<pre><code>[(array([ 0.00773887, 0.00531894, 0.00533349, 0.00779727, 0.01482933,
0.01247594, 0.01274703, 0.02111097, 0.01800994, 0.01398229,
0.0098171 ,... | <p>It may not be the fastest, but this should be very robust:</p>
<pre><code>lst = np.array(lst).tolist()
</code></pre> | arrays|list|python-2.7|numpy|tuples | 6 |
351,742 | 23,472,424 | Removing entire rows that contain a zero in two Pandas series | <p>I have a function which plots the log of two columns from a <code>Pandas</code> <code>DataFrame</code>. As such zeros cause an error and need to be removed. At the moment the input to the function is two columns from a <code>DataFrame</code>. Is there a way to remove any rows containing zeros? For example an equival... | <p>As I understand your question, you need to remove rows where <strong>either</strong> (and/or) <code>x</code> or <code>y</code> are zero.</p>
<p>A simple approach is</p>
<pre><code>keepThese = (x > 0) & (y > 0)
a = x[keepThese]
b = y[keepThese]
</code></pre>
<p>and then proceed with your code.</p> | python-2.7|pandas | 2 |
351,743 | 23,638,919 | Calculate Pandas dataframe column - boolean logic and offset data | <p>Based on information in a Pandas Dataframe I would like to calculate a new column. Below is an example of what I would like to do. Starting point:</p>
<p>{'A': [1, 1, 0, 0, 1, 1, 0, 0, 0]}</p>
<p>Based on this data I would like to calculate a new column B by using the following logic: IF (A(row-2) = 1 AND A(row -1... | <p>If <code>d</code> is your DataFrame:</p>
<pre><code>>>> d['B'] = ((d.A.shift(2)==1) & (d.A.shift(1)==1)).astype(int)
>>> d
A B
0 1 0
1 1 0
2 0 1
3 0 0
4 1 0
5 1 0
6 0 1
7 0 0
8 0 0
</code></pre>
<p><code>shift</code> is the way to shift a column forward or backward, allo... | python|pandas|boolean-logic | 2 |
351,744 | 23,921,766 | Row filtering so that we only keep finite entries | <p>I found <a href="https://stackoverflow.com/a/22799245/1732769">this recipe</a> to keep finite entries in my dataframe.</p>
<p>The formula is:</p>
<pre><code>df[df == np.Inf] = np.NaN
df.dropna()
</code></pre>
<p>However, when I try it:</p>
<pre><code>In: df[df == np.Inf] = np.NaN
## -- End pasted text --
------... | <p>Use <code>np.isinf()</code></p>
<pre><code>x = pandas.DataFrame([
[1, 2, np.inf],
[4, np.inf, 5],
[6, 7, 8]
])
x[np.isinf(x)] = np.nan
print(x)
0 1 2
0 1 2 NaN
1 4 NaN 5
2 6 7 8
</code></pre>
<p>so then <code>x.dropna()</code> gives me:</p>
<pre><code> 0 1 2
2 6 7 8
</code></... | python|pandas | 2 |
351,745 | 23,666,346 | I don't understand why/how one of these methods is faster than the others | <p>I wanted to test the difference in time between implementations of some simple code. I decided to count how many values out of a random sample of 10,000,000 numbers is greater than 0.5. The random sample is grabbed uniformly from the range [0.0, 1.0).</p>
<p>Here is my code:</p>
<pre><code>from numpy.random import... | <ol>
<li><p>Method 1 generates a full list in memory before using it. This is slow because the memory has to be allocated and then accessed, probably missing the cache multiple times.</p></li>
<li><p>Method 2 uses an generator, which never creates the list in memory but instead generates each element on demand.</p></li... | python|optimization|numpy | 2 |
351,746 | 23,926,267 | Calling np.array on a list of RandomForestRegressors returns an array of DecisionTreeRegressors | <p>When I try to convert a list of RandomForestRegressors to a numpy array, I get an array of Decision Trees. How do I get an array of RandomForestRegressors instead?</p>
<p>e.g.</p>
<pre><code>clf0=RandomForestRegressor()
clf1=RandomForestRegressor()
X = np.random.randn(10,1)
y = np.random.randn(10,1)
clf0.fit(X,... | <p>This was recently answered on the scikit-learn mailing list: a random forest behaves as <a href="https://docs.python.org/dev/glossary.html#term-sequence" rel="nofollow">sequence</a> of decision trees:</p>
<pre><code>>>> len(clf0)
10
>>> clf0[:2]
[DecisionTreeRegressor(compute_importances=None, cri... | python|numpy|scikit-learn | 1 |
351,747 | 22,798,608 | Merging two DataFrames using an aggregate on a column on one of the DataFrames | <p>In Python-Pandas, lets say I have two DataFrames</p>
<pre><code>A = pd.DataFrame({'key1': np.random.randint(4, size=10), 'val1': np.random.rand(10) })
B = pd.DataFrame({'key1': np.random.randint(4, size=10), 'val2': np.random.rand(10) })
</code></pre>
<p>I want to add a column to B which is the mean of the values... | <p>Do you mean something like this?</p>
<pre><code>A1 = A.groupby('key1').mean().reset_index()
pd.merge(B, A1, on='key1')
</code></pre> | python|pandas | 0 |
351,748 | 22,461,307 | How can I plot from a maximum range to a minimum range in Python | <p>I have some troubles trying to plot a figure in python for a homework I had in university. I want to plot a figure from the maxim range to the minimum range in the x-axis. My code is the next one:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
# function that plots the cummulative histogram
def ... | <p>Use the xlim function or the set_xlim method of the axes:</p>
<pre><code>plt.xlim(200, 20)
</code></pre> | python|numpy|plot|histogram | 2 |
351,749 | 22,605,614 | Using partial with groupby and apply in Pandas | <p>I am having trouble using partial with groupby and apply in Pandas. Perhaps I am not using this right? </p>
<pre><code>data = {'a':[1,1,2,2],'b':['Y','Y','N','Y'], 'c':['Y','Y','N','Y']}
df = pandas.DataFrame(data)
def countY(columnName, group): return len(group[group[columnName] == 'Y'])
df.groupby('a').apply(par... | <p>There is no need to use <code>functools.partial</code> here, as you can provide arguments to the function inside the <code>apply</code> call.</p>
<p>If your function has as first argument the group (so switch the order of the arguments), then the other arguments in <code>apply</code> are passed to the function and ... | python|pandas | 2 |
351,750 | 22,441,823 | Is there are more pythonic way to write a while loop that only updates a variable? | <p>I have this while loop, and I was wondering if their is a more pythonic way to write it:</p>
<pre><code>k = 1
while np.sum(s[0:k]) / s_sum < retained_variance:
k += 1
</code></pre>
<p><code>s</code> is a numpy vector. Thanks!</p> | <p>I'd say it's pretty pythonic: explicit is better than implicit.</p> | python|numpy | 4 |
351,751 | 22,578,058 | Numpy polyfit - covariance matrix | <p>When fitting a straight line to a set of data, weighted with errors, I was expecting polyfit to return a 2x2 covariance matrix from which I could square root the diagonal elements to find the uncertainty in the coefficients, but I don't.</p>
<p>Here's a minimum working example:</p>
<pre><code>from numpy import pol... | <p>The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html" rel="nofollow">document</a> says:</p>
<ul>
<li><p>cov : bool, optional</p>
<p>Return the estimate and the covariance matrix of the estimate If full is True, then cov is not returned.</p></li>
</ul>
<p>So set <code>cov=True</code>... | python|numpy|covariance | 4 |
351,752 | 22,622,571 | Difference between import numpy and import numpy as np | <p>I understand that when possible one should use </p>
<pre><code>import numpy as np
</code></pre>
<p>This helps keep away any conflict due to namespaces. But I have noticed that while the command below works</p>
<pre><code>import numpy.f2py as myf2py
</code></pre>
<p>the following does not</p>
<pre><code>import n... | <p><strong>numpy</strong> is the top package name, and doing <code>import numpy</code> doesn't import submodule <code>numpy.f2py</code>. </p>
<p>When you do <code>import numpy</code> it creats a link that points to <code>numpy</code>, but <code>numpy</code> is not further linked to <code>f2py</code>. The link is estab... | python|numpy | 22 |
351,753 | 22,583,917 | Indices in a numpy array where slice in another array | <p>The actual problem is in some machine learning application, and the data gets a little complex. So here's an MWE that captures the essence of the problem:</p>
<p>I have two arrays made as follows:</p>
<pre><code>L = np.arange(12).reshape(4,3)
M = np.arange(12).reshape(6,2)
</code></pre>
<p>Now, I want to find the... | <p>Ok, I think I got it. The trick is to add another dimension to <code>M</code>, and then you can use broadcasting:</p>
<pre><code>M.shape += (1,)
E = np.all(L[:,:-1].T == M, 1)
</code></pre>
<p>and you get a 6x4 boolean matrix <code>E</code> that gives you the results of comparing all rows of L with all rows of M.<... | python|arrays|numpy|python-3.3 | 4 |
351,754 | 22,575,050 | Why is numpy.dtype('float64') special? | <p>Can someone explain the logic behind the output of the following script?</p>
<pre><code>import numpy
if(numpy.dtype(numpy.float64) == None):
print "Surprise!!!!"
</code></pre>
<p>Thanks :)</p> | <p>Looks like an unfortunate accident: someone decided that <code>dtype(None)</code> would "default" to float (though <code>dtype()</code> is an error). Then someone else wrote <code>dtype.__eq__</code> such that it converts its second argument to a dtype before comparing. So <code>dtype(float) == None</code> is <cod... | python|numpy | 8 |
351,755 | 15,440,812 | Dataframe manipulation | <p>Goal: To add a column to a dataframe consisting of labels as follows:</p>
<pre><code>(-10,5]=-2
(-5,0]= -1
[0,5) = 0
[5,10)= 1
[10,15)= 2
</code></pre>
<p>....etc</p>
<p>If the <code>df.ptdelta</code> is between <code>(-10,5]</code> it receives -2 added to a column of <code>df</code>.</p>
<p>Attempt 1: </... | <p>You are binning the data and labeling it by bin. Happily, <code>numpy.digitize</code> can do that for you.</p>
<pre><code>bins = [-10, -5, 0, 5, 10, 15]
labels = np.digitize(data, bins) - 3
</code></pre>
<p>Example:</p>
<pre><code>In[1]: df = DataFrame({'d': np.random.randint(-20, 20, 100)})
In[2]: bins = [-10, ... | python|pandas | 0 |
351,756 | 15,161,856 | Slice syntax to object | <p>I have a class holding data (a numpy ndarray) that includes a method storing the data to a mat-file (using scipy.io.savemat). The data can be very large, so I may only want to store a segment of the data. Therefore I pass a slice-object, like this:</p>
<pre><code>def write_mat(self, fn, fields=None, sel=None):
... | <p>The answer on <a href="https://stackoverflow.com/questions/13706258/passing-python-slice-syntax-around-to-functions">Passing Python slice syntax around to functions</a> is correct, but as you're already using NumPy you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.s_.html" rel="nofollow ... | python|numpy|slice | 3 |
351,757 | 15,214,024 | Python: Produce increments from a list to form an array | <p>I have the following data</p>
<pre><code>a= [1 1.1 1.2 1.3 1.4 1.5]
</code></pre>
<p>What I want to do is for each value of this data produce a series of points in increments with a spacing of 10%. Creating a new array:</p>
<pre><code>b= [[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0], [0 0.11 ... 1.1],.....]
</cod... | <p>Mixing list comprehensions and <code>np.linspace</code> it is pretty straightforward:</p>
<pre><code>>>> a = [1, 1.1, 1.2, 1.3, 1.4, 1.5]
>>> b = [np.linspace(0, j, 11) for j in a]
>>> b
[array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]),
array([ 0. , 0.11, 0.... | python|arrays|numpy|scipy | 2 |
351,758 | 15,463,057 | Null numpy array to be appended to | <p>I'm writing a feature selection code. Basically get the output from featureselection function and concatenate it to the numpy array data</p>
<pre><code>data=np.zeros([1,4114]) # put feature length here
for i in range(1,N):
filename=splitpath+str(i)+'.tiff'
feature=featureselection(filename)
data=np.vsta... | <p>Appending to a numpy array in a loop is inefficient, there might be some situations when it cannot be avoided but this doesn't seem to be one of them. If you know the size of the array that you'll end up with, it's best to just per-allocate the array, something like this:</p>
<pre><code>data = np.zeros([N, 4114])
f... | python|numpy | 3 |
351,759 | 15,420,213 | numexpr.evaluate("a+b",out=a) | <p>Is it safe in python numexpr to assign values to the same array you are operating on to avoid creating a temporary array?</p>
<p>From the description of memory usage on the <a href="https://github.com/pydata/numexpr" rel="nofollow noreferrer">project homepage</a> it looks okay, but without diving into the source co... | <p>It works, because numexpr still uses temporary arrays internally, albeit in chunk sizes of 1024 elements (or 4096 if using VML). You can think of these chunks of the inputs as slices, though they are stored as appropriate C data types for speed and memory compactness during the evaluation. The results will be stor... | python|numpy|numexpr | 8 |
351,760 | 14,941,097 | Selecting pandas column by location | <p>I'm simply trying to access named pandas columns by an integer. </p>
<p>You can select a row by location using <code>df.ix[3]</code>.</p>
<p>But how to select a column by integer?</p>
<p>My dataframe:</p>
<pre><code>df=pandas.DataFrame({'a':np.random.rand(5), 'b':np.random.rand(5)})
</code></pre> | <p>Two approaches that come to mind:</p>
<pre><code>>>> df
A B C D
0 0.424634 1.716633 0.282734 2.086944
1 -1.325816 2.056277 2.583704 -0.776403
2 1.457809 -0.407279 -1.560583 -1.316246
3 -0.757134 -1.321025 1.325853 -2.513373
4 1.366180 -1.265185 -2.184617 0.881514... | python|pandas|indexing | 213 |
351,761 | 13,723,953 | Stack arrays in sequence | <p>I read linewise <code>data</code> from a file and I want to store them in an <code>array</code>.</p>
<p>EDIT: The data cannot be read with <code>loadtxt()</code>.</p>
<p>So I do it like this:</p>
<pre><code>data = array([])
for frame in frames:
# ....
# get some lines and make some calculations e.g. final... | <p>If the number of elements in <code>line</code> is fixed and you just want to avoid an "ugly" solution, you can do this:</p>
<pre><code>data = []
for f in frames:
# do your calculation
# line = [1, 2, 3, 4]
data += line
data = np.array(data).reshape((-1,4))
</code></pre> | python|numpy | 1 |
351,762 | 13,757,239 | Combining rows in DataFrame | <p>I have a pandas <code>DataFrame</code> with 18 columns and about 10000 rows.</p>
<p>My first 3 columns have separate values for <code>YEAR</code>, <code>MONTH</code>, and <code>DAY</code>. I need to merge these three columns and have the entire date in one column for all the rows.</p>
<p>My code so far is:</p>
<p... | <p>You are looking for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html?highlight=apply#pandas.DataFrame.apply" rel="noreferrer"><code>apply</code></a> <em>(<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html?highlight=merge#pandas.DataFra... | python|numpy|python-3.x|python-2.7|pandas | 5 |
351,763 | 13,762,121 | merge two dataframe and create a new one with multiindex | <p>I all,</p>
<p>I have two dataframes in Pandas:</p>
<p><strong>a</strong>:</p>
<pre><code>In [96]: a
Out[96]:
count mean std min max 25% 50% 75%
10m 604656 4.19 2.43 0 25.92 2.43 3.71 5.5
In [98]: a.to_dict()
Out[98]:
{'25%': {'10m': 2.429999828338623},
'50%': {'10m': 3.710000038146... | <p>@unutbu is correct, here is without constructing the index by hand.</p>
<pre><code>df = a.append(b)
df.index = MultiIndex.from_arrays([a.index.tolist()*(len(b) + 1),
["all"] + b.index.tolist() ] )
df
25% 50% 75% count max mean min std
10... | python|dataframe|pandas|multi-index | 2 |
351,764 | 13,726,573 | Create a 24 hour 1 min resolution data set in pandas | <p>I have a 1 min resolution time series contained in a <code>pandas</code> data frame. What is the easiest (and most efficient) way for me to pad these times series in such way that on each date present in the data frame I have 1 min time steps for all 1 min intervals (so the date would have 24 hours worth of 1 min da... | <p>You can use the <code>resample</code> method (<a href="http://pandas.pydata.org/pandas-docs/dev/timeseries.html#up-and-downsampling" rel="nofollow">http://pandas.pydata.org/pandas-docs/dev/timeseries.html#up-and-downsampling</a>) if you have a time series (if the time is used as the index):</p>
<pre><code>df.resamp... | python|pandas|time-series | 1 |
351,765 | 13,737,992 | Indexing timeseries by date string | <p>Given a timeseries, <code>s</code>, with a datetime index I expected to be able to index the timeseries by the date string. Am I misunderstanding how this should work?</p>
<pre><code>import pandas as pd
url = 'http://ichart.finance.yahoo.com/table.csvs=SPY&d=12&e=4&f=2012&g=d&a=01&b=01&c... | <p>Try indexing with a <code>Timestamp</code> object:</p>
<pre><code>>>> import pandas as pd
>>> from pandas.lib import Timestamp
>>> url = 'http://ichart.finance.yahoo.com/table.csv?s=SPY&d=12&e=4&f=2012&g=d&a=01&b=01&c=2001&ignore=.csv'
>>> df = pd.... | python|pandas|time-series | 2 |
351,766 | 13,353,233 | Best way to split a DataFrame given an edge | <p>Suppose I have the following DataFrame:</p>
<pre><code> a b
0 A 1.516733
1 A 0.035646
2 A -0.942834
3 B -0.157334
4 A 2.226809
5 A 0.768516
6 B -0.015162
7 A 0.710356
8 A 0.151429
</code></pre>
<p>And I need to group it given the "edge B"; that means the groups will be:</p>
<pre><c... | <p>here's a oneliner:</p>
<pre><code>zip(*dff.groupby(pd.rolling_median((1*(dff['a']=='B')).cumsum(),3,True)))[-1]
[ 1 2
0 A 1.516733
1 A 0.035646
2 A -0.942834
3 B -0.157334,
1 2
4 A 2.226809
5 A 0.768516
6 B -0.015162,
1 2
7 A 0.710356
8 A 0.151429]
</code></pre> | python|pandas | 3 |
351,767 | 13,742,266 | SciPy NumPy and SciKit-learn , create a sparse matrix | <p>I'm currently trying to classify text. My dataset is too big and as suggested <a href="https://stackoverflow.com/questions/13741460/text-classification-with-scikit-learn-and-a-large-dataset/13741595#13741595">here</a>, I need to use a sparse matrix. My question is now, what is the right way to add an element to a sp... | <p>Scikit-learn has a great documentation, with great tutorials that you really <em>should</em> read before trying to invent it yourself. <a href="https://scikit-learn.org/0.19/tutorial/text_analytics/working_with_text_data.html" rel="nofollow noreferrer">This</a> one is the first one to read it explains how to classif... | python|matrix|numpy|scipy|scikit-learn | 14 |
351,768 | 13,629,994 | new pythonic style for shared axes square subplots in matplotlib? | <p>Related to: <a href="https://stackoverflow.com/questions/13612610/plotting-autoscaled-subplots-with-fixed-limits-in-matplotlib">plotting autoscaled subplots with fixed limits in matplotlib</a></p>
<p>I would like to make a set of subplots that are all on the same scale, using the <code>subplots</code> new compact s... | <p>Just use <code>adjustable='box-forced'</code> instead of <code>adjustable='box'</code>. </p>
<p>As @cronos mentions, you can pass it in using the <code>subplot_kw</code> kwarg (additional keyword arguments to <code>subplots</code> are passed on to the <code>Figure</code> not the <code>Axes</code>, thus the need fo... | python|numpy|matplotlib|scipy | 19 |
351,769 | 29,567,507 | Different results with Python and Matlab interpolation functions | <p>I'm converting code from Matlab to Python 2.7 and am having a problem with the conversion of the interp1 function. I have looked at similar questions already posted but have not yet managed to solve it. The problem is that the first value of the vector of newly generated values (yn) is different while the rest are a... | <p>Your (reversed) <code>x</code> array is not increasing (<code>-0.00275 < -0.000935</code>) which is should be to use <code>np.interp1d</code> properly. See <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html" rel="nofollow">the docs</a>. No warning is issued.</p>
<p>I don't have access... | python|matlab|python-2.7|numpy|scipy | 0 |
351,770 | 29,384,588 | How to reset an unordered index to an ordered one in python? | <p>I have a dataframe like below </p>
<p>textdata</p>
<pre><code> id user_category operator circle
0 23 1 vodafone mumbai
1 45 2 airtel andhra
2 65 3 airtel chennai
3 23 6 vodafone mumbai
4 45 1 airtel ... | <p>Use the <code>drop=True</code> option of <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>.</p>
<blockquote>
<p>drop : boolean, default False.
Do not try to insert index into dataframe columns. This resets the index to the ... | python|pandas|dataframe | 1 |
351,771 | 29,463,068 | Return rows in pandas dataframe where tuple in column contains a certain value | <p>I am trying to query a pandas dataframe for rows in which one column contains a tuple containing a certain value.</p>
<p>As an example:</p>
<pre><code> User Col1
0 1 (cat, dog, goat)
1 1 (cat, sheep)
2 1 (sheep, goat)
3 2 (cat, lion)
4 2 (fish, goa... | <p>You could use a lambda function within <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply()</code></a>:</p>
<pre><code>df[df["Col1"].apply(lambda x: True if "cat" in x else False)]
</code></pre>
<p>The lambda returns <code>True</code> when <code>"cat... | python|pandas|tuples|dataframe | 2 |
351,772 | 29,686,808 | Indexing/reshaping matrix in Python to match target matrix | <p>I have a NumPy array that looks like the following:</p>
<pre class="lang-python prettyprint-override"><code>>>> import numpy
>>> foo = numpy.array(
[[ 1. , 0.3491, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,
1. , 0.1648, 0. , 0. , 0. , 0... | <p>First, create a numpy array:</p>
<pre><code>import numpy as np
arr = np.asarray(a)
arr
array([[ 1. , 0.3491, 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 1. , 0.1648, 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 1. ,
0. , 0. , ... | python|numpy|matrix|indexing | 1 |
351,773 | 29,642,404 | Iterating over groups (Python pandas dataframe) | <p>I want to iterate over groups that are grouped by strings or dates.</p>
<pre><code>df = pd.DataFrame({'A': ['foo', 'bar'] * 3,
'B': ['me', 'you', 'me'] * 2,
'C': [5, 2, 3, 4, 6, 9]})
groups = df.groupby('A')
</code></pre>
<p>For eg in this code, I have groups by their names '... | <p>The <code>.groupby()</code> object has a <code>.groups</code> attribute that returns a Python dict of indices. In this case:</p>
<pre><code>In [26]: df = pd.DataFrame({'A': ['foo', 'bar'] * 3,
....: 'B': ['me', 'you', 'me'] * 2,
....: 'C': [5, 2, 3, 4, 6, 9]})
In [27]: g... | python|pandas|iterator|dataframe|grouping | 13 |
351,774 | 29,616,487 | Why numpy/scipy is faster without OpenBLAS? | <p>I made two installations:</p>
<ol>
<li><code>brew install numpy</code> (and scipy) <code>--with-openblas</code></li>
<li>Cloned GIT repositories (for numpy and scipy) and built it myself</li>
</ol>
<p>After I cloned two handy scripts for verification of these libraries in multi-threaded environment:</p>
<pre><cod... | <p>There are two obvious differences that might account for the discrepancy:</p>
<ol>
<li><p>You are comparing two different versions numpy. The OpenBLAS-linked version you installed using Homebrew is 1.9.1, whereas the one you built from source is 1.10.0.dev0+3c5409e.</p></li>
<li><p>Whilst the newer version is not l... | python|performance|numpy|scipy|openblas | 9 |
351,775 | 62,408,910 | error while inserting python dataframe to mysql | <p><strong>Here is the Python code:</strong></p>
<pre><code>from sqlalchemy import create_engine
import pandas as pd
mydb = create_engine("mysql://xx:xx@localhost/xx")
df = pd.DataFrame({'name' : ['User P', 'User Q', 'User R']})
df.to_sql('CARS', con=mydb)
</code></pre>
<p><strong>Error:</strong></p>
<blockquote>
... | <p>Ah, so apparently it seems I had to install PyMySQL (python3 -m pip install PyMySQL)</p>
<p>And a little change here:</p>
<pre><code>mydb = create_engine("mysql+pymysql://xx:xx@localhost/xx")
</code></pre>
<p>It worked after this. :) </p> | python|mysql|pandas|sqlalchemy | 1 |
351,776 | 62,248,822 | Numpy Argmax Over Multiple Axes for an Array Slice | <p>Suppose that I have an array which has mxn dimensions. </p>
<p>How do I do the argmax using numpy over the last n dimensions?</p>
<p>So the output array should, given the first m indices, return a list of n indices that correspond the the maximal value of array[m indices]. </p>
<p>For example:</p>
<p>Input:</p>
... | <p>The Numpy's argmax has an option to input the axis. In your case <code>MxN</code> is always two dimensional. Hence this should do the trick:</p>
<pre><code>m = 1
n = 2
array = [[[3,1],[2,2]],[[1,2],[2,4]],[[1,2],[7,4]]]
np.argmax(array,axis=2)
>>array([[0, 0],[1, 1]], dtype=int64)
</code></pre> | python|numpy|argmax | 1 |
351,777 | 62,169,293 | Offsetting an existing date value, where values exist in another column in dataframe | <p>I'm trying to offset an existing date (in this case by 2 months), based on a value in another column (Type).</p>
<pre><code>df.loc[df['Type'] == 'Lock', 'Start'] = df['Start'] + pd.DateOffset(months=-2)
Error: ValueError: cannot reindex from a duplicate axis
</code></pre>
<p>Can this be accomplished in one line l... | <pre><code>df['Start'] = np.where(df['Type'] == 'Lock',
df['Start'] + pd.DateOffset(months=-2),
df['Start'])
</code></pre> | python|python-3.x|pandas | 0 |
351,778 | 62,303,911 | How to select only one part of a Tensorflow dataset, and change the dimensions | <p>I wish to train my model on 10 frame segments of UCF101, without any label. Currently I have this:</p>
<pre><code>import tensorflow as tf
import tensorflow_datasets as tfds
x_train = tfds.load('ucf101', split='train', shuffle_files=True, batch_size = 64)
>>> print(x_train)
<_OptionsDataset shapes: {labe... | <p>Forgive me for the approximate answer, because I won't download the 6GB dataset to test my answer.</p>
<p>Why don't you just select the video when you iterate through the dataset:</p>
<pre><code>next(iter(x_train))['video']
</code></pre>
<p>To select the dimensions, you can use normal <code>numpy</code> indexing.... | python|tensorflow|tensorflow2.0|tensorflow-datasets | 2 |
351,779 | 62,130,020 | ZeroPadding2D pad twices when I set padding to 1 | <p>I've just started to learn Tensorflow (2.1.0), Keras (2.3.7) with Python 3.7.7.</p>
<p>I'm trying an encoder-decoder network using VGG16.</p>
<p>I need to Upsample a layer from <code>(12, 12, ...)</code> to <code>(25, 25, ...)</code> to make <code>conv7_1</code> has the same shape as <code>conv4_3</code> layer. Th... | <p>I did it using padding as a tuple of 2 tuples of 2 ints: interpreted as ((top_pad, bottom_pad), (left_pad, right_pad)). And setting <code>ZeroPadding2D</code> at the end of convolution 7 layer:</p>
<pre><code>#################################
# Decoder
#################################
#conv1 = Conv2DTranspose(512,... | tensorflow|keras|conv-neural-network|autoencoder|encoder-decoder | 0 |
351,780 | 62,349,596 | How gather lists and load into dataframe | <p>The following code creates a dataframe, tokenizes, and filters stopwords. However, <strong>am I stuck trying to properly gather the results to load back into a column of the dataframe</strong>. Trying to put the results back into the dataframe (using commented code) produces the following error <code>ValueError: Len... | <p>As you mentioned you need a list of lists in order for the assignment to work.
Another solution can be to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">pandas.apply</a> as you used in the beginning of your code.</p>
<pre><code>import n... | python|pandas|dataframe | 1 |
351,781 | 62,110,722 | Create two dataframes from two dataframes based on multiindex in one dataframe and columns in another dataframe | <p>I m not sure if this has been answered before. But my requirement is that
I have a dataframe like this:</p>
<p><code>df1:</code></p>
<pre><code> A B
I1 I2
x11 x12 a11 b11
x12 x22 a21 b21
</code></pre>
<p>Note that this has multiindex of <code>[I1, I2]</code> and columns <code>[A, B]</code></p>
<p>an... | <p>Let us try <code>reset_index</code> with <code>merge</code> </p>
<pre><code>df3=df1.reset_index().merge(df2).set_index(['I1','I2'])
df4=df1.drop(df3.index)
</code></pre>
<p>Or </p>
<pre><code>idx=pd.MultiIndex.from_frame(df2)
df3=df1.reindex(idx).dropna()
df4=df1.drop(df3.index)
</code></pre> | pandas|dataframe | 1 |
351,782 | 62,234,634 | Reading images from adjacent folders | <p>I have 4 different path to folders, but each folder are adjacent to each other and they're called faces 1, faces 2, faces 3 and faces 4. I'm using that path to read the faces images from inside and extract features from them and put them inside a feature_vector. </p>
<p>What i need to do is: read each face images f... | <p>For what I see, <code>coord_list</code> is always the same for every set of images, so you could condensate the assignation of all the four <code>vec_n</code> lists into one single <code>for</code> loop, by performing the appropriate string interpolation.</p>
<p>This solution will substitute the four <code>vec_n</c... | python|python-3.x|numpy|data-structures | 0 |
351,783 | 62,293,107 | Splitting a Pandas single column into multiple sum columns | <p>Here's a Noob question. </p>
<p>Let's say I have this Pandas DataFrame of data:</p>
<pre><code> id Name Sex Age Country Sport Medal
119932 K Thompson M 26 United States Basketball Gold
120121 V Thrasher F 19 United States Shooting Gold
122093 M Troy ... | <ol>
<li>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> to split the dataframe into groups based on "Country" and "Medal"</li>
<li>Then apply the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/gr... | pandas | 0 |
351,784 | 62,328,913 | get first, second and third date of each file opened - Pandas | <p>I have this code to group by col1 to get the nsmallest dates in order of the times the file was opened but it seems to come in random order but that is what I don't need.
Here is my code.</p>
<pre><code>data=(df.groupby(['col1']).date
.apply(lambda x: pd.Series(x.value_counts()
.ns... | <p>I think you want this:</p>
<pre><code>df['count'] = df.sort_values('date').groupby('col1').cumcount()
df.set_index(['col1', 'count']).query('count <= 2')['date'].unstack()
</code></pre>
<p>Output:</p>
<pre><code>count 0 1 2
col1 ... | python|pandas|numpy | 0 |
351,785 | 62,308,992 | Need to create bins having equal population. Also need to generate a report that contains cross tab between bins and cut | <p>I'm using the diamonds dataset, below are the columns </p>
<p><a href="https://i.stack.imgur.com/0kmdj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0kmdj.png" alt="enter image description here"></a></p>
<p>Question: to create bins having equal population. Also need to generate a report that c... | <p>You are on the right path: <code>pd.qcut()</code> attempts to break the data you provide into <code>q</code> equal-sized bins (though it may have to adjust a little, depending on the shape of your data). </p>
<p><code>pd.qcut()</code> also lets you specify <code>labels=False</code> as an argument, which will give y... | python|pandas|data-science | 1 |
351,786 | 62,420,970 | How to get results of partial match in either SQL/Pandas/Python and fill column with conditional value? | <p>I am looking to find values that have a partial match in one column and replace the 'subcategory' column with a value derived from the 'item name' column. The 'subcategory' column is currently a duplicate of the 'item name' column. </p>
<p>For example, in the image below, I would like to replace the current values ... | <p>Consider pure SQL conditional <code>CASE</code> statement in <code>UPDATE</code>. Either run below single statement in Postgres or call it via Python. Leave <code>pandas</code> for data analytics!</p>
<pre class="lang-sql prettyprint-override"><code>UPDATE public.all_beers_specs
SET "Sub_Category" = CASE
... | python|sql|pandas|postgresql|dataframe | 0 |
351,787 | 62,216,105 | Issue with str.replace() and replace() pandas Dataframe | <p>I have the following data:</p>
<pre><code>print(df):
Name
James (C)
Mick
Tash (C)
Liv
Nathan
Chris
</code></pre>
<p>I am simply trying to get</p>
<pre><code>print(df):
James
Mick
Tash
Liv
Nathan
Chris
</code></pre>
<p>I have tried:</p>
<pre><code>df['Name'] = df['Name'].str.replace(' (C)','')
</code></pre>
<p>... | <p>Use <code>\</code> for escape regex, because <code>()</code> are special regex characters:</p>
<pre><code>df['Name'] = df['Name'].str.replace(' \(C\)','')
print (df)
Name
0 James
1 Mick
2 Tash
3 Liv
4 Nathan
5 Chris
</code></pre> | python|pandas | 6 |
351,788 | 62,414,091 | Vectorized Custom function not working as expected In pandas | <p>With <a href="https://www.youtube.com/watch?v=HN5d490_KKk" rel="nofollow noreferrer">this</a> pycon talk as a source.</p>
<pre><code>def clean_string(item):
if type(item)==type(1):
return item
else:
return np.nan
</code></pre>
<p>dataframe object has a column containing numerical and strin... | <p>Vectorizing an operation in pandas isn't always possible. I'm not aware of a pandas built-in vectorized way to get the type of the elements in a Series, so your <code>.apply()</code> solution may be the best approach.</p>
<p>The reason that your code doesn't work in the second case is that you are passing the entir... | python|python-3.x|pandas|data-science|vectorization | 1 |
351,789 | 62,295,936 | swap columns with pandas | <p>I want to swap these two columns:</p>
<pre><code>khushboo खुशबू
khushbuu खुशबू
khushbu खुशबू
khusbhu खुशबू
tera तेरा
teraa तेरा
thera तेरा
teraaa तेरा
badan बदन
sulgeh सुलगे
sulage सुलगे
sulge सुलगे
mehke महके
mahake महके
</code></pre>
<p>I know I can read these columns with pandas using lik... | <p>Let's say the first column header is <code>khushboo</code> and the second column header is
<code>खुशबू</code> </p>
<pre><code>dataset = pd.read_csv('/file.txt', delimeter ='\t', encoding='utf-8')
dataset = dataset[['खुशबू','khushboo']]
dataset.to_csv('file.csv', index=False) #you may also have to pass `encoding=... | python|pandas | 0 |
351,790 | 62,108,886 | How can I Hash hundred thousand records taken as a input from CSV file? | <p><strong>By using this code I'm able to hash only 1 record without any errors or warnings. How can I hash a hundred thousand records taken as input from the CSV file?</strong></p>
<pre><code>import pandas as pd
proper = []
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
for line in f:
toke... | <p>What you need to do, is acctually use your methods.
right now you <code>__init__</code> a new object <code>t</code>. Then you are refering to a index in your <code>list</code> and set <code>"Tanzania"</code> as value. så you actually dont use your methods in your object <code>t</code> only the function <code>list</c... | python|pandas|list|csv|hash | 0 |
351,791 | 62,423,017 | Cython fastest way to pass a float numbers for high frequency control loops | <p>I have a function(func) in a c++ class and want to call it from the python side to invoke the following sequence with the <strong>lowest latency possible</strong>:</p>
<p>1_on the python side: func(np.array([1,2,3,4,5]) or func([1,2,3,4,5]) or 2D array and any other suggestion you may have for lower latency.</p>
<... | <p>When it comes to performance optimizations you have to measure! </p>
<p>First make sure, that you exactly know, where your hotspot is. You can use <code>perf</code> or Intels <code>vTune</code> to make sure you optimize the right location.</p>
<p>Than you can write a <code>google benchmark</code> test for that spe... | python|c++|numpy|cython|memoryview | 0 |
351,792 | 62,379,033 | pandas set cell length | <p>I sometime want to read the output dataframe and want it to be indented.
For example, if I have dataframe</p>
<pre><code>A |B |C |D | E
abc|def|ghij|k|ooo
lorem|ipsumjkl|d|amet|hel
</code></pre>
<p>And I have a list of length I want to apply <code>alist = [5,8,4,1,3]</code></p>
<pre><code>A ... | <p>You could try something like this: </p>
<pre><code>for i,colum in enumerate(list(df.columns)):
df[colum]=df[colum].apply(lambda x: str(x).ljust(alist[i]))
df.to_csv("report.csv", sep="|", index=False)
</code></pre>
<p>Or, you can try this:</p>
<pre><code>def returncolumindex(val):
i, j = np.where(df.val... | python|pandas|lambda | 1 |
351,793 | 62,110,002 | Heatmap using lists of different size | <p>I would like to compare two list of different size using JaroWinkler similarity. <code>List_1</code> has <code>5</code> elements and it comes from a column dataframe, e.g. </p>
<pre><code>List_1=df['Movements'].tolist()
</code></pre>
<p>i.e. <code>List_1=['surrealism', 'futurism', 'impressionism', 'realism', 'neor... | <p>You can simply do:</p>
<pre><code>for m in all_mov:
#compute similarity
df[m] = df.Movements.apply(lambda x: jarowinkler.similarity(x, m))
# filter out low similarity scores
df[m] = np.where(df[m] > 0.1, df[m], np.nan)
sns.heatmap(data=df.set_index('Movements')[all_mov])
</code></pre>
<p>which... | python|pandas|matplotlib|seaborn | 1 |
351,794 | 62,123,115 | TFRecord Reads and Memory Usage | <p>I have a simple question about reading a TFRecord:</p>
<p>Lets say you have a record which has 10 features - each being large numpy array. When you read the record, are all 10 numpy arrays loaded into memory? or is a feature only loaded into memory with you read that particular feature -- allowing me to read 1 feat... | <p>No, you don't have to load all features present in the TFRecord file into memory.</p>
<p>You can be selective by parsing with a custom feature description: <a href="https://www.tensorflow.org/tutorials/load_data/tfrecord#reading_a_tfrecord_file" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/load_da... | numpy|tensorflow|memory|tfrecord | 0 |
351,795 | 62,222,719 | Matplotlib - Pie Chart from dataframe | <p>I saw a sample from the internet to build a simple pie chart from Matplotlib but not sure how to embed it with my dataset (<a href="https://gist.github.com/datomnurdin/33961755b306bc67e4121052ae87cfbc" rel="nofollow noreferrer">https://gist.github.com/datomnurdin/33961755b306bc67e4121052ae87cfbc</a>).</p>
<pre><cod... | <p>I would do something like this:</p>
<pre><code>my_labels = {1:'Positive',0:'Neutral',-1:'Negative'}
my_colors = ['lightblue','lightsteelblue','silver']
# count the values to plot pie chart
s = df.sentiment.map(my_labels).value_counts()
plt.pie(s, labels=s.index, autopct='%1.1f%%', colors=my_colors)
# also
# s.plo... | python|pandas|matplotlib | 2 |
351,796 | 62,089,240 | Drop rows in pandas based on the same key | <p>How can I drop rows where column A is the key, and any rows for that key contain both "foo" and "moo" in column C</p>
<p>df_before: </p>
<pre><code>"cat" |"waverly way"|"foo"|10.0
"cat" |"smokey st" |"moo"|9.7
"rabbit"|"rapid ave" |"foo"|6.6
"rabbit"|"far blvd" |"too"|3.2
</code></pre>
<p>df_after: </p>
... | <p>You can do it this way:</p>
<pre><code>df.columns = ['A', 'B', 'C', 'D']
</code></pre>
<p>df:</p>
<pre><code> A B C D
0 cat waverly way foo 10.0
1 cat smokey st moo 9.7
2 rabbit rapid ave foo 6.6
3 rabbit far blvd too 3.2
</code></pre>
<p>.</p>
<pre><code... | python|pandas|dataframe | 4 |
351,797 | 62,347,998 | SqlAlchemy recreates pool after engine.dispose() | <p>I am using sqlalchemy with <code>pandas.to_sql()</code> to copy some data into SQL server. After the copying is done and <code>engine.dispose()</code> is called, I see the following INFO message in logs:</p>
<pre><code>[INFO] sqlalchemy.pool.impl.QueuePool: Pool recreating
</code></pre>
<p>I was wondering if this ... | <p>If there is a connection which is already checked out from the pool, those connections will still be alive as they are being referenced by something.</p>
<p>You may refer to following links for detailed information.
<a href="https://github.com/sqlalchemy/sqlalchemy/blob/master/lib/sqlalchemy/engine/base.py#L2512-L... | python|pandas|sqlalchemy | 0 |
351,798 | 62,279,514 | How to sort a pandas Series on values while randomizing the order of ties? | <p>I'm using sort_values() to sort values in a pandas Series from largest to smallest. I wonder if there is an easy way of randomizing the order of ties(?). It appears that the indexes of ties come in the descending order given as argument in this case:</p>
<pre><code>s = pd.Series([3.0, 15.0, 1.0, 22.0, 11.0, 12.0, 2... | <p>You can first shuffle the series by taking a random 100 % <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html" rel="nofollow noreferrer"><code>sample</code></a> and then sort it:</p>
<pre><code>s.sample(frac=1).sort_values(ascending=False)
</code></pre>
<p>You can also ... | python|pandas|sorting | 4 |
351,799 | 62,134,409 | How to compile torch 1.5.0 without GPU support? | <p>I want to install pytorch 1.5.0 on AWS lambda. Since the torch library is very large, I need to make it as small as possible to fit within the size limits. My script looks like this so far:</p>
<pre class="lang-sh prettyprint-override"><code> mkdir python
docker run \
--rm \
-v $(pwd):/build ... | <p>PyTorch also distributes CPU only versions, that you can install with pip. Although they aren't published to PyPI, so you need to get them from their own registry.</p>
<p>You can get the CPU version on <a href="https://pytorch.org/get-started/locally/" rel="nofollow noreferrer">PyTorch - Getting Started Locally</a>... | python-3.x|aws-lambda|pip|pytorch | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.