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 |
|---|---|---|---|---|---|---|
362,900 | 42,916,063 | TensorFlow security: Evaluate untrusted graphDef | <p>Is it safe to have TensorFlow evaluate untrusted graphDefs?</p>
<p>Imagine a web service in which users will send me a graphDef file, which TensorFlow will load and evaluate. What evil can an attacker do by sending this service a malicious graphDef file?</p>
<p>I will limit number of requests per hour, file size, ... | <p>More recent TensorFlow documentation makes it fairly clear that, while one can forbid dangerous operations, the TensorFlow runtime presents a sufficiently large attack surface that one should assume it to be exploitable, and hence, run it in a sandbox or other mitigation.</p>
<p><a href="https://chromium.googlesourc... | security|tensorflow | 0 |
362,901 | 42,706,761 | closing session in tensorflow doesn't reset graph | <p>The number of nodes available in the current graph keep increasing at every iteration. This seems unintuitive since the session is closed, and all of it's resources should be freed.
What is the reason why the previous nodes are still lingering even when creating a new session?
Here is my code:</p>
<pre><code>for i ... | <p>Closing session does not reset graph by design. If you want to reset graph you can either call <code>tf.reset_default_graph()</code> like this</p>
<pre><code>for _ in range(3):
tf.reset_default_graph()
var = tf.Variable(0)
with tf.Session() as session:
session.run(tf.global_variables_initializer... | python|tensorflow | 19 |
362,902 | 42,987,200 | Plotting a barplot from Pandas dataframe with points | <p>I want to plot a horizontal barplot from a Pandas dataframe but have no idea how to begin.</p>
<p>My data looks like this</p>
<pre><code> max min point1 point2
Series 1 50 10 40 30
Series 2 60 20 50 40
</code></pre>
<p>Couldn't help myself but to draw something with paint. ... | <p>Here is a plot that closely resembles to picture from the question. It's produced by <code>matplotlib.pyplot</code>.</p>
<p><a href="https://i.stack.imgur.com/iJxiS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iJxiS.png" alt="enter image description here"></a></p>
<pre><code>import pandas as ... | python|pandas|matplotlib | 3 |
362,903 | 43,021,896 | Construct Sparse Matrix in Matlab from Compressed Sparse Column (CSC) format | <p>I have a large sparse matrix (~5 billion non-zero values) in Python, stored in the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.html#scipy.sparse.csc_matrix" rel="nofollow noreferrer">csc_matrix</a> format. I need to open it as a sparse matrix in Matlab. <a href="https://do... | <p>The following code works, but is very slow. Any suggestions would be appreciated.</p>
<pre><code>X=zeros(shape(1),shape(2));
for k=1:length(indptr)-1
i=indptr(k)+1:indptr(k+1);
y=indices(i)+1;
X(y,k)=data(i);
end
</code></pre> | python|matlab|numpy|matrix|scipy | 0 |
362,904 | 42,759,360 | How to switch to cuda7.5 after install tensorflow using .whl file? | <p>I have installed tensorflow using the 1.0.1 whl file.
When I run the command <code>python -c 'import tensorflow'</code> an import error says cannot open shared object file <code>libcublas.so8.0</code>.
However I have only cuda7.5 in my machine.</p>
<p>So how can I change tensorflow to use cuda7.5 in my machine??</p... | <p>As per the <a href="https://www.tensorflow.org/versions/master/get_started/os_setup" rel="nofollow noreferrer">tensorflow website</a>:</p>
<blockquote>
<p>The GPU version works best with Cuda Toolkit 8.0 and cuDNN v5.1. Other
versions are supported (Cuda toolkit >= 7.0 and cuDNN >= v3) only when
installing fr... | python|tensorflow | 0 |
362,905 | 42,927,865 | Read complex numbers from a csv file using python | <p>I am having problem reading complex number from a csv file.
The format of the file is the following: </p>
<pre><code>( -353.10438 +j1.72317617 ),( -23.16000 +j0.72512251 )
</code></pre>
<p>I tried importing the data using numpy.genfromtxt: </p>
<pre><code>data=genfromtxt(fname, dtype=complex, skip_header=10, ski... | <p>I moved each 'j' to the position immediately behind the imaginary part of the complex number and squeezed out all the blanks to get a sample file like this.</p>
<pre><code>(-353.10438+1.72317617j),(-23.16000+0.72512251j)
(-353.10438+1.72317617j),(-23.16000+0.72512251j)
(-353.10438+1.72317617j),(-23.16000+0.72512251... | python|csv|numpy | 5 |
362,906 | 42,970,664 | How to pass variable as a column name pandas | <p>I'm using Python 2.7
I try do create new column based on variable form a list</p>
<p>tickers=['BAC','JPM','WFC','C','MS']
returns=pd.DataFrame
for tick in tickers:
returns[tick]=bank_stocks[tick][<img src="https://i.stack.imgur.com/Bscce.png" alt="[">]<a href="https://i.stack.imgur.com/Bscce.png" rel="nofollo... | <p>Your code is correct except the line in In[73] where you must call dataframe(i.e., pd.DataFrame()) you have created an object by not using '()' after DataFrame. Thats why the error is type object doesnot support assignment.</p> | python-2.7|pandas|data-science | 1 |
362,907 | 42,594,881 | Installing tensorflow CPU with windows 10 anaconda python 2.7 | <p>I am using anaconda, python 2.7, windows 10. I would like to install tensorflow with conda. However, I am having this error:</p>
<pre><code>(tensorflow) C:\Users\cenk>conda install -c conda-forge tensorflow python=2.7
Fetching package metadata ...............
Solving package specifications: .
UnsatisfiableErro... | <p>TensorFlow only supports Python 3.5 64-bit on Windows.
You need the corresponding Anaconda distribution. </p>
<p>Make sure to create an environment for <code>Python=3.5</code> as Anaconda recently upgraded their distribution from <code>3.5</code> to <code>3.6</code> which is also not supported with a pre-build bin... | python-2.7|tensorflow|anaconda | 1 |
362,908 | 42,847,828 | Can't plot dataframe when index is a date | <p>I have a CSV file that looks like this:</p>
<pre><code>Date,Close
16-Mar-17,848.78
15-Mar-17,847.2
</code></pre>
<p>Whenever I try to load it in and set the date as the index by doing:</p>
<pre><code>df = pd.read_csv("new_data.csv")
df.set_index("Date")
</code></pre>
<p>I get<code>ValueError: could not convert s... | <p>Now, you need to convert string <code>Date</code> to <code>datetime</code>: </p>
<pre><code>Close['Date'] = pd.to_datetime(Close['Date'])
</code></pre> | python|python-3.x|pandas | 3 |
362,909 | 42,814,512 | Nested keys in a dictionary concatenation of arrays | <p>I have a large multi level key dictionary as:</p>
<pre><code>mydict = {}
mydict['a1'] = {}
mydict['a1']['b1'] = {}
mydict['a1']['b1']['c1'] = np.array([1,2,3])
mydict['a1']['b1']['c2'] = np.array([11,21,31])
mydict['a2'] = {}
mydict['a2']['b1'] = {}
mydict['a2']['b1']['c1'] = np.array([1,22,3])
mydict['a2']['b1'][... | <p>If I understand your question correctly, here's a solution using recursion on the dict and flatten method of np.ndarray (<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html<... | python|numpy|dictionary | 4 |
362,910 | 42,841,824 | In pandas, check if a master string contains a string from a list, if it does remove the substring from the master string and add it to a new column | <p>I have two DataFrames:</p>
<pre><code>df1=
A
0 Black Prada zebra leather Large
1 green Gucci striped Canvas small
2 blue Prada Monogram calf leather XL
df2=
color pattern material size
0 black zebra leather small
1 green striped canvas xl
2 yellow che... | <p><strong>Updated</strong></p>
<p>It sounds like you may want to rank the way you are searching the columns of <code>df2</code> from <code>df1</code> (I'm calling that <code>search</code> now below).</p>
<p>Here it checks what the maximum percentage of the words in your <code>search</code> string match with words in... | python|pandas | 0 |
362,911 | 42,598,887 | Python OpenCV 3 not reading images properly | <p>In MacOS 10.11.6, I’m reading a batch of 192 *.jpg images, each of shape 160x320x3, using OpenCV 3 <code>cv2.imread()</code> from filesystem then I create a NumPy array using that batch of images. If I load it from <code>data01/</code> path (<code>/data01/IMG/center_2017_03_03_11_52_56_652.jpg</code>) then I get a r... | <p>In the comments to the question, you say that the type of some of the objects in <code>read_images</code> is <code>NoneType</code>, which means some of the values are <code>None</code>. You'll have to fix the code that generates <code>read_images</code>, or filter out the <code>None</code> values with something lik... | python|opencv|numpy | 1 |
362,912 | 27,346,232 | Correctly annotate a numba function using jit | <p>I started with this code to calculate a simple matrix multiplication. It runs with %timeit in around 7.85s on my machine.</p>
<p>To try to speed this up I tried cython which reduced the time to 0.4s. I want to also try to use numba jit compiler to see if I can get similar speed ups (with less effort). But adding th... | <p>I figured out how to do this with some help from someone else.</p>
<pre><code>@jit('i4[:](c16[:],c16[:],i4,i4[:])',nopython=True)
def calculate_z_numpy(q, z, maxiter,output):
"""use vector operations to update all zs and qs to create new output array"""
for iteration in range(maxiter):
for i in rang... | python|performance|numpy|numba | 4 |
362,913 | 27,260,799 | Using counts and tfidf as features with scikit learn | <p>I'm trying to use both counts and tfidf as features for a multinomial NB model. Here's my code:</p>
<pre><code>text = ["this is spam", "this isn't spam"]
labels = [0,1]
count_vectorizer = CountVectorizer(stop_words="english", min_df=3)
tf_transformer = TfidfTransformer(use_idf=True)
combined_features = FeatureUnio... | <p>The error didn't come from the <code>FeatureUnion</code>, it came from the <code>TfidfTransformer</code></p>
<p>You should use <code>TfidfVectorizer</code> instead of <code>TfidfTransformer</code>, the transformer expects a numpy array as input and not plaintext, hence the TypeError</p>
<p>Also your test sentence ... | python|numpy|nlp|scikit-learn|ml | 11 |
362,914 | 26,974,089 | How do I calculate date difference between rows with respect to a grouped index PANDAS | <p>I have a repeated measured data set (many observations per person, one row per observation).</p>
<p>I need to calculate the date difference in number of days from a subjects first observation until their last. So for the following toy problem...</p>
<pre><code>## toy problem
d = {'one' : Series(['a', 'a', 'a', 'b'... | <pre><code>datediff = lambda x: (x - x.min())
transformed = df.groupby('one').date_d.transform(datediff)
df['days_since'] = transformed - date(1970, 1, 1)
</code></pre>
<p>did the trick</p> | python|pandas | 0 |
362,915 | 27,006,176 | dot product of subarrays without for loop | <p>when we have: </p>
<pre><code>array 1: A, shape (49998,3,3)
array 2: B, shape (3, 49998)
</code></pre>
<p>and i want to multiply their subarrays to get </p>
<pre><code>array 3: C, shape(3,49998)
</code></pre>
<p>for which im using generator:</p>
<pre><code>def genC(A,B):
for a,b in itertools.izip(A,B.T):
... | <p>If I am getting your code right, you want to perform 49998 dot products of a 3x3 matrix with a 3 vector, right? That is very easy to do with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html"><code>np.einsum</code></a>:</p>
<pre><code>np.einsum('ijk,ki->ij', A, B)
</code></pre> | python|arrays|numpy|dot-product | 4 |
362,916 | 27,251,864 | Mean of y value in vertical bin | <p>So I have Stock market data (date from 0 onwards, & a close price) and with this I use numpy.fft to calculate the fast fourier transform, and corresponding frequencies, and then have these in the form of a zipped list, 'FFT,Frequency'. I have the Frequency values separated into vertical logarithmic bins using:</... | <p>I was overthinking everything.... </p>
<p>I was able to calculate the y value averages in a very similar way, using the frequency binning as such:</p>
<pre><code>for k in range(1,len(logbins)):
mean_freq.append(np.mean(np.array(logTfreq)[freqdig==k]))
mean_fft.append(np.mean(np.array(logTFAS)[freqdig==k]))... | python|numpy|binning | 1 |
362,917 | 27,098,529 | Numpy float64 vs Python float | <p>I'm battling some floating point problems in Pandas read_csv function. In my investigation, I found this:</p>
<pre><code>In [15]: a = 5.9975
In [16]: a
Out[16]: 5.9975
In [17]: np.float64(a)
Out[17]: 5.9974999999999996
</code></pre>
<p>Why is builtin <code>float</code> of Python and the <code>np.float64</code> ... | <pre><code>>>> numpy.float64(5.9975).hex()
'0x1.7fd70a3d70a3dp+2'
>>> (5.9975).hex()
'0x1.7fd70a3d70a3dp+2'
</code></pre>
<p>They are the same number. What differs is their representation; the Python native type uses a "sane" representation, and the NumPy type uses an accurate representation.</p> | python|numpy|floating-point | 52 |
362,918 | 26,954,710 | how do I transform a DataFrame in pandas with a function applied to many slices in each row? | <p>I want to apply a function f to many slices within each row of a pandas DataFrame.
For example, DataFrame df would look as such:</p>
<pre><code>df = pandas.DataFrame(np.round(np.random.normal(size=(2,49)), 2))
</code></pre>
<p>So, I have a dataframe of 2 rows by 49 columns, and my function needs to be applied to e... | <p>To avoid redundant code you can just do a loop like this:</p>
<pre><code>STEP = 7
for i in range(0,len(df),STEP):
df1.T[i:i+STEP] = f(df1.T[i:i+STEP]) # could also do an apply here somehow, depending on what you want to do
</code></pre> | python|pandas | 2 |
362,919 | 14,718,643 | Pandas undocumented DataFrame.keys() method | <p>Im new in Pandas, and while playing with its <code>Dataframe</code>, i found method <code>keys()</code> which works pretty like <code>dict.keys()</code>. But I cannot find it in <a href="http://pandas.pydata.org/pandas-docs/dev/api.html#dataframe" rel="nofollow">docs</a>. What am i missing?</p> | <p>You can see where this is defined in <a href="https://github.com/pydata/pandas/blob/master/pandas/core/frame.py#L708">the source</a>:</p>
<pre><code>def keys(self):
return self.columns
</code></pre>
<p>And, if you look at the git blame, you can see it was added as a fix for <a href="https://github.com/pydata/p... | python|dictionary|dataframe|pandas|data-analysis | 11 |
362,920 | 14,476,415 | Reshape an array in NumPy | <p>Consider an array of the following form (just an example):</p>
<pre><code>[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]
[16 17]]
</code></pre>
<p>It's shape is [9,2]. Now I want to transform the array so that each column becomes a shape [3,3], like this:</p>
<pre><code>[[ 0 6 12]
[ 2 ... | <pre><code>a = np.arange(18).reshape(9,2)
b = a.reshape(3,3,2).swapaxes(0,2)
# a:
array([[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9],
[10, 11],
[12, 13],
[14, 15],
[16, 17]])
# b:
array([[[ 0, 6, 12],
[ 2, 8, 14],
[ 4, 10, 16]],
... | python|arrays|numpy|reshape | 69 |
362,921 | 25,038,336 | Pandas: convert a multiindex column headers into normal column header? | <p>My data frame looks like this, with columns header being MultiIndex, (True, False are boolean type).</p>
<pre><code> date a value
id False True
0 2013-11-26 0 346.749819 0.000000
1 2013-11-27 1 1786.449591 21442.388942
2 2013-11-28 1 67783... | <p>If names aren't important, you could do this, which will reset the row index, and replace the MultiIndex columns with a tuple with each level.</p>
<pre><code>df = df.reset_index()
df.columns = list(df.columns)
</code></pre> | python|pandas | 2 |
362,922 | 25,258,553 | Flask, Javascript : Refresh with SQL query | <p>I want to update my template querying every 5 second but I get the same value for every case. How do I keep refreshing and retrieve the values per each 5 second?
I want to implement monitoring script querying my database every 5 second.</p>
<pre><code>@app.route('/')
def index():
while True:
conn = MySQLd... | <p>The <code>while True</code> part of your code doesn't do anything - when a request is made, the template will be rendered once and the function exits.</p>
<p>You'll need to do something on the client side to refresh the data. This could be as a simple as an <a href="https://stackoverflow.com/questions/4644027/auto... | python|pandas|flask|jinja2 | 3 |
362,923 | 25,041,905 | Matplotlib timelines | <p>I'm looking to take a python DataFrame with a bunch of timelines in it and plot these in a single figure. The DataFrame indices are Timestamps and there's a specific column, we'll call "sequence", that contains strings like "A" and "B". So the DataFrame looks something like this:</p>
<pre><code>+-------------------... | <p>I would just map each category to a y-value using a dictionary.</p>
<pre><code>import random
import numpy as np
import matplotlib.pyplot as plt
import pandas
categories = list('ABCD')
# map categories to y-values
cat_dict = dict(zip(categories, range(1, len(categories)+1)))
# map y-values to categories
val_dict ... | python|matplotlib|pandas|timeline | 14 |
362,924 | 25,144,146 | Python - Pandas - Plotting Count of Column by Group - Graphing Each Group Over Time | <p>Sorry if the title is horribly vague, its hard to express the issue in a few words.</p>
<p>I have recently read 'Python For Data Analysis' and have been trying to bring it over to real world examples. I did have to replace some information in my Dataframe/images to generics (e.g. app1, app2). Otherwise the data a... | <pre><code>d = {'level' : ['ERROR', 'ERROR', 'ERROR', 'ERROR', 'ERROR', 'ERROR', 'ERROR', 'ERROR', 'ERROR', 'ERROR'],
'DATE' : ['2014-07-29 12:35:55.916', '2014-07-29 12:35:55.916', '2014-07-29 12:35:55.916', '2014-07-29 12:35:55.874', '2014-07-29 12:35:55.908', '2014-07-29 12:35:55.908', '2014-07-29 12:35:55.908', '... | python|matplotlib|pandas | 0 |
362,925 | 25,382,019 | index column not being parsed as date | <p>When I import a few records, the read_csv correctly reads the index column as date-time.
But if the number of records is more than a few thousand then the index column seems to be automatically changing to object instead of time.</p>
<pre><code>import pandas as pd
myheader=['ticketId' , ... a lot of columns ... ,... | <p>While a custom parser works, I think a faster path might be to do no parsing as you read the data in, the set the index like this. The <code>coerce=True</code> forces bad values to <code>NaT</code></p>
<pre><code>df.index = pd.to_datetime(df["ticketDate"] + df["ticketTime"], coerce=True, format='%Y-%m-%d %H:%M:%S'... | python|pandas | 1 |
362,926 | 25,101,699 | Synchronizing Data in Python (or Excel) | <p>I frequently use Python (and occasionally Excel) to process and compare test data between multiple experiments. In some cases the data might be out of sync which makes direct comparisons difficult. For example, a typical test specification would be:</p>
<pre><code>1) Stabilize test temperature to a value of 20 +/- ... | <p>There are many ways to approach this. The first thing that comes to mind is to numerically differentiate the data, and look for the jump in the slope from 0 to 0.5. But (as you observed) noisy data can prevent this from working well. If you google for "numerical differentiation of noisy data", you'll find <em>a l... | python|excel|numpy|pandas|scipy | 2 |
362,927 | 25,404,818 | Writing and reading floats and strings in a CSV file - python | <p>I am a bit new to python and programming. In my code, I have developed a feature (which is a 1-D array of 39 elements) for each audio file. I want to write the name of the file, the feature and its target value {0,1} into a CSV file to train my SVM classifier. I used the CSV writer as follows.</p>
<pre><code>with o... | <p>To convert string like "[1.0, 2.0, 3.0]" to list [1.0, 2.0, 3.0]:</p>
<pre><code># string to convert
s = '[1.0, 2.0, 3.0]'
lst = [float(x) for x in s[1: -1].split(',')]
# and result will be
[1.0, 2.0, 3.0]
</code></pre>
<p>This works both with standard python string type and with numpy.string type.</p> | python|csv|numpy|svm | 1 |
362,928 | 25,171,611 | Unexpected memory error when regriding data with scipy interpolate griddata method | <p>I have a <code>3000x6000</code> 2D grid (from a tiff image). I want to regrid it into a lower resolution grid using <code>griddata</code> method from <code>scipy.interpolate</code> library. First, I need to form a <code>18000000x2</code> <code>numpy array</code> as the input for <code>griddata</code> based on what I... | <p>As the comments point out, you run out of memory. A 32-bit Python running on 64-bit Windows 7 is limited to 2 GB of memory, and you just banged into that.</p>
<p>There are three solutions:</p>
<ol>
<li>Get a 64-bit Python. (<em>suggested</em>)</li>
<li>Interpolate in several chunks (split the image into some suita... | python|numpy|memory-leaks|grid|scipy | 3 |
362,929 | 30,650,734 | Python: How can I get the previous 5 values in a Pandas dataframe after skipping the very last one? | <p>I have a Pandas dataframe, df as follows:</p>
<pre><code> 0 1 2
0 k86e 201409 180
1 k86e 201410 154
2 k86e 201411 157
3 k86e 201412 153
4 k86e 201501 223
5 k86e 201502 166
6 k86e 201503 163
7 k86e 201504 169
8 k86e 201505 157
</code></pre>
<p>I know that in order to get the... | <p>Use negative indices and pass these to <code>iloc</code> to slice the rows of interest:</p>
<pre><code>In [5]:
df.iloc[-6:-1]
Out[5]:
0 1 2
3 k86e 201412 153
4 k86e 201501 223
5 k86e 201502 166
6 k86e 201503 163
7 k86e 201504 169
</code></pre>
<p>You can then index the col of interes... | python|pandas|dataframe | 5 |
362,930 | 30,607,895 | Applying transformations to dataframes with multi-level indices in Python's pandas | <p>I'm trying to do apply simple functions to mostly numeric data in pandas. the data is a set of matrices indexed by time. I wanted to use hierarchical/multilevel indices to represent this and then use a split-apply-combine like operation to group the data, apply an operation, and summarize the result as a dataframe. ... | <blockquote>
<p>how to view just the 'time' column values?</p>
</blockquote>
<pre><code>In [11]: c.index.levels[0].values
Out[11]: array(['t1', 't2'], dtype=object)
</code></pre>
<blockquote>
<p>how to group matrix by time, subtract value from each matrix, and then
take the mean across the columns and get a dat... | python|numpy|pandas | 1 |
362,931 | 30,475,674 | NumPy's repeat command on a matrix: how to do this in OpenCV with cv::Mat? | <p>I am rather new to OpenCV and need to translate some Python code to OpenCV (C++). Given a certain matrix, I need to create a larger matrix with a specific pattern. Suppose the original matrix is a matrix with random integers:</p>
<pre><code>>>> import numpy as np
>>> a = np.random.randint(0, 10,... | <p>cv::repeat function is what you need</p> | python|opencv|numpy|matrix|repeat | 1 |
362,932 | 30,584,924 | Why does my array lose its mask after doing multidimensional indexing in Numpy? | <p>I wish to use a multidimensional MaskedArray as an index array:</p>
<p>Data:</p>
<pre><code>In [149]: np.ma.arange(10, 60, 2)
Out[149]:
masked_array(data = [10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58],
mask = False,
fill_value = 999999)
</code></pre>
<p>Indices... | <p>Looks like indexing with a masked array just ignores the mask. Without digging much into the docs or code, I'd say the <code>numpy</code> array indexing has no special knowledge of the masked array subclass. The array you get is just the normal <code>arange(20)</code> indexing.</p>
<p>But you could perform normal... | python|numpy|multidimensional-array|indexing | 3 |
362,933 | 30,530,663 | How to "select distinct" across multiple data frame columns in pandas? | <p>I'm looking for a way to do the equivalent to the SQL </p>
<pre><code>SELECT DISTINCT col1, col2 FROM dataframe_table
</code></pre>
<p>The pandas sql comparison doesn't have anything about <code>distinct</code>.</p>
<p><code>.unique()</code> only works for a single column, so I suppose I could concat the columns,... | <p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html"><code>drop_duplicates</code></a> method to get the unique rows in a DataFrame:</p>
<pre><code>In [29]: df = pd.DataFrame({'a':[1,2,1,2], 'b':[3,4,3,5]})
In [30]: df
Out[30]:
a b
0 1 3
1 2 4... | python|pandas|dataframe|duplicates|distinct | 260 |
362,934 | 30,641,509 | forwardfill combined with calculation (method='ffill' * xyz) in python pandas | <p>I need to fill NaN spaces with a calculation, that depends on the previous values in the dataframe = df. What I have so far is this:</p>
<pre><code>df = pd.DataFrame({'a': [None] * 6, 'b': [2, 3, 10, 3, 5, 8]})
df["c"] =np.NaN
df["c"][0] = 1
df["c"][2] = 3
i = 1
while i<10:
df.c.fillna(df.c.shift(i)*df.b,i... | <p>I can't figure out a way to do this in a single loop, the problem here is that you want some kind of rolling apply that can then look at the previous row, the problem here is that the previous row update will not be observable until the <code>apply</code> finishes so for instance the following works because we in ru... | python|pandas | 4 |
362,935 | 30,324,167 | Creating 3rd order tensors with python and numpy | <p>I have a two 1 dimensional arrays, <code>a</code> such that <code>np.shape(a) == (n,)</code> and <code>b</code> such that <code>np.shape(b) == (m,)</code>.</p>
<p>I <strong>want</strong> to make a (3rd order) tensor <code>c</code> such that <code>np.shape(c) == (n,n,m,)</code>by doing <code>c = np.outer(np.outer(a,... | <p>You could perhaps use <code>np.multiply.outer</code> instead of <code>np.outer</code> to get the required outer product:</p>
<pre><code>>>> a = np.arange(4)
>>> b = np.ones(5)
>>> mo = np.multiply.outer
</code></pre>
<p>Then we have:</p>
<pre><code>>>> mo(mo(a, a), b).shape
(4,... | python|arrays|numpy|matrix | 2 |
362,936 | 26,663,314 | Best practice for fancy indexing a numpy array along multiple axes | <p>I'm trying to optimize an algorithm to reduce memory usage, and I've identified this particular operation as a pain point.</p>
<p>I have a symmetric matrix, an index array along the rows, and another index array along the columns (which is just all values that I wasn't selecting in the row index). I feel like I sho... | <p>"Broadcasting" applies to indexing. You could convert <code>inliers</code> into column matrix (e.g. <code>inliers.reshape(-1,1)</code> or <code>inliers[:, np.newaxis]</code>, so it has shape (m,1)) and index <code>mat</code> with that in the first column:</p>
<pre><code>s1 = mat[inliers.reshape(-1,1), outliers]
sc... | python|arrays|numpy|indexing | 5 |
362,937 | 26,539,163 | Elementwise operations in mpmath slow compared to numpy and its solution | <p>I have some calculations that involve factorials that explode pretty fast so I resolved to use the arbitrary precision library <code>mpmath</code>.</p>
<p>The code I have looks like this:</p>
<pre><code>import numpy as np
import mpmath as mp
import time
a = np.linspace( 0, 100e-2, 100 )
b = np.linspace( 0, ... | <p><code>gmpy2</code> is significantly faster that <code>mpmath</code> for this type of calculation. The following code runs about 12x faster on my machine.</p>
<pre><code>import numpy as np
import gmpy2 as mp
import time
a = np.linspace(0, 100e-2, 100)
b = np.linspace(0, np.pi)
c = np.arange(30)
t = time.time()
M =... | python|numpy|factorial|mpmath | 3 |
362,938 | 26,880,989 | Pandas dataframe: return row AND column of maximum value(s) | <p>I have a dataframe in which all values are of the same variety (e.g. a correlation matrix -- but where we expect a unique maximum). I'd like to return the row and the column of the maximum of this matrix. </p>
<p>I can get the max across rows <em>or</em> columns by changing the first argument of</p>
<pre><code>df.... | <p>I figured out the first part:</p>
<pre><code>npa = df.as_matrix()
cols,indx = np.where(npa == np.amax(npa))
([df.columns[c] for c in cols],[df.index[c] for c in indx])
</code></pre>
<p>Now I need a way to get the top n. One naive idea is to copy the array, and iteratively replace the top values with <code>NaN<... | python|pandas | 3 |
362,939 | 26,758,655 | How to make grid of the irregular data? | <p>I have the numpy arrays of longitudes, latitudes, and the data.
I want to plot this data as a raster image using numpy, scipy, and matplotlib.</p>
<pre><code>import numpy as np
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
longitudes = np.array([[139.79391479492188, 140.51760864257812, 141.1... | <p>You can use interpolation to convert the distorted grid into a regular grid. The interpolation fits the original data points and returns a function that can be evaluated at any point of your choosing, and in this case, you would choose a regular grid of points.</p>
<p>Here's an example:</p>
<pre><code>import nump... | python|numpy|matplotlib|scipy | 2 |
362,940 | 39,400,043 | Pandas: ignore null values when using .astype(str)? | <p>So I have a dataframe, call it <code>TABLE</code> and I'm using Pandas with Python 2.7 to analyze it. It's mostly categorical data so right now my goal is to have a summary of my table where I list each column name and the average length of the values in that column.
Example table:</p>
<pre><code> A B C ... | <p><code>stack</code> to get series<br>
<code>dropna</code> to get rid of <code>NaN</code><br>
<code>astype(str).str.len()</code> to get lengths<br>
<code>unstack().mean()</code> for average length<br>
<code>reindex(TABLE.columns)</code> to ensure we get all original columns represented</p>
<pre><code>TABLE.stack().dr... | python-2.7|pandas | 3 |
362,941 | 39,195,179 | How can I extract data using the 'groupby' | <pre><code>import pandas as pd
df= pd.DataFrame({'date':[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5],
'name':list('aaaaabbbbbccccc'),
'v1':[10,20,30,40,50,10,20,30,40,50,10,20,30,40,50],
'v2':[10,20,30,40,50,10,20,30,40,50,10,20,30,40,50],
'v3':[10,20,30,40,50,10,20,30,40,50,10,20,30,40,50]})
a= list(set(list(... | <p>looking at your desired data set i don't think you need to <code>groupby</code> your <code>df</code>, you can simply filter it:</p>
<pre><code>In [112]: df.query('v1 >= 10 and v2 >= 20 and v3 <= 40')
Out[112]:
date name v1 v2 v3
1 2 a 20 20 20
2 3 a 30 30 30
3 4 a 40 ... | python|python-3.x|pandas|dataframe | 0 |
362,942 | 39,323,071 | COUNT DISTINCT / nunique within groups | <p>I want to count the number of distinct tuples within each group:</p>
<pre><code>df = pd.DataFrame({'a': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'b': [1, 2, 1, 2, 1, 2, 1, 2],
'c': [1, 1, 2, 2, 2, 1, 2, 1]})
counts = count_distinct(df, by='a', columns=['b', 'c'])
assert counts == pd.Ser... | <p>I think your logic is equivalent to count the size of data frames grouped by column <code>a</code> after dropping the duplicated values of combined columns <code>a</code>, <code>b</code> and <code>c</code>, since duplicated tuples within each group must also be duplicated records in the data frame assuming your data... | python|python-3.x|pandas | 3 |
362,943 | 38,972,934 | Broadcasting logical operators along a different axis | <p>I have a DataFrame and a Series:</p>
<pre><code>np.random.seed(0)
df = pd.DataFrame(np.random.binomial(1, 0.3, (5, 4)).astype(bool))
ser = pd.Series(np.random.binomial(1, 0.3, 5).astype(bool))
</code></pre>
<pre>df
Out:
0 1 2 3
0 False True False False
1 False False False True
2 ... | <p>Since this computation is array-based (no alignment of index labels necessary),
you could compute this with NumPy arrays and NumPy broadcasting:</p>
<pre><code>np.logical_and(df.values, ser.values[:, None])
</code></pre>
<hr>
<p>Here is a speed comparison of a few alternatives:</p>
<pre><code>import numpy as np
... | python|pandas | 2 |
362,944 | 39,353,917 | Inheriting from numpy.recarray, __unicode__ issue | <p>I have made a subclass of a numpy.recarray. The purpose of the class is to provide pretty printing for record arrays while maintaining the record array functionality. </p>
<p>Here is the code:</p>
<pre><code>import numpy as np
import re
class TableView(np.recarray):
def __new__(cls,array):
return np.... | <p>Your diagnosis is right. A single element of this class is a <code>record</code>, not an <code>Tableview</code> array. </p>
<p>And indexing with a slice or list, <code>[0:1]</code> or <code>[[0]]</code>, is the immediate solution.</p>
<p>Trying to subclass <code>np.record</code> and changing the elements of the ... | python|numpy|recarray | 1 |
362,945 | 39,360,479 | How to aggregate values of pandas series | <h3>Data manipulation using pandas</h3>
<p>Anyone having bright ways to manipulate the values of concatenated pandas series to find total counts? </p>
<hr>
<p>Current data (type: <code>pandas.core.series.Series</code>)
FYI, this data is generated by using 'groupby' function from the raw data.</p>
<pre><code>date ... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.cumsum.html" rel="nofollow"><code>DataFrameGroupBy.cumsum</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.groupby.html" rel="nofollow"><code>groupby</co... | python|pandas|series|multi-index|cumsum | 2 |
362,946 | 39,009,122 | Iterating Over Every Item in a Series in Pandas With A Custom Function | <p>I have a dataframe in Pandas that lists its information like this:</p>
<pre><code> Player Year Height
1 Stephen Curry 2015-16 6-3
2 Mirza Teletovic 2015-16 6-10
3 C.J. Miles 2015-16 6-7
4 Robert Covington 2015-16 6-9
</code></pre>
<p>Right now data['Height'] stores its values... | <p>You can use apply on the <code>Height</code> column after it gets splitted into lists and pass a lambda function to it for conversion:</p>
<pre><code>df['Height'] = df.Height.str.split("-").apply(lambda x: int(x[0]) * 12 + int(x[1]))
df
# Player Year Height
# 1 Stephen Curry 2015-16 ... | python|pandas | 1 |
362,947 | 39,025,644 | Python: Find mean of points within radius of a an element in 2D array | <p>I am looking for an efficient way to find the mean of of values with a certain radius of an element in a 2D NumPy array, excluding the center point and values < 0.</p>
<p>My current method is to create a disc shaped mask (using the method <a href="https://stackoverflow.com/questions/8647024/how-to-apply-a-disc-s... | <p>is this helpful? This takes only a couple of seconds on my laptop for ~ 18000 points:</p>
<pre><code>import numpy as np
#generate a random 300x300 matrix for testing
inputMat = np.random.random((300,300))
radius=50
def radMask(index,radius,array):
a,b = index
nx,ny = array.shape
y,x = np.ogrid[-a:nx-a,-b:ny... | python|arrays|numpy|mean | 1 |
362,948 | 39,365,697 | Find eigenvalues of Complex valued matrix in python | <p>I need to find the eigenvvalues of of this matrix, and similar such matrices (spaces denote separators):</p>
<pre><code>[[1.0000 -0.7071*I 0 -0.7071*I 0 0 0 0 0]
[0.7071*I 0.5000 -0.7071*I 0 -0.70710*I 0 0 0 0]
[0 0.7071*I 1.0000 0 0 -0.7071*I 0 0 0]
[0.7071*I 0 0 0.5000 -0.7071*I 0 -0.7071*I 0 0] ... | <p>As more than one commenter has explained, your matrix works fine with <code>eigvalsh</code>.</p>
<pre><code>import numpy as np
from numpy.linalg import eigvalsh
I = 1j
arr = np.array([[1.0000, -0.7071*I, 0, -0.7071*I, 0, 0, 0, 0, 0],
[0.7071*I, 0.5000, -0.7071*I, 0, -0.70710*I, 0, 0, 0, 0],
[0, 0.7071*I, 1... | python|numpy|matrix|linear-algebra|eigenvalue | 1 |
362,949 | 19,644,698 | How to call function for scipy.optimize.fmin_cg(func) in Python | <p>I will simply explain the problem in short. This problem is exactly similar as shown in <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_cg.html#scipy.optimize.fmin_cg" rel="nofollow noreferrer">scipy.doc</a>. The problem is on error occurance as <strong>float argument required, not n... | <p>The root of your problem is that <code>fmin_cg</code> expects the function to return a single scalar value for the misfit instead of an array.</p>
<p>Basically, you want something vaguely similar to:</p>
<pre><code>def func(z, y, T, t):
return np.linalg.norm(y - counter(T,z,t))
</code></pre>
<p>I'm using <cod... | python|numpy|scipy | 4 |
362,950 | 19,738,169 | Convert column of date objects in Pandas DataFrame to strings | <p>How to convert a column consisting of datetime64 objects to a strings that would read
01-11-2013 for today's date of November 1.</p>
<p>I have tried </p>
<pre><code>df['DateStr'] = df['DateObj'].strftime('%d%m%Y')
</code></pre>
<p>but I get this error</p>
<p><strong>AttributeError: 'Series' object has no attribu... | <p>As of <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/whatsnew.html#whatsnew-0170-strftime" rel="noreferrer">version 17.0</a>, you can format with the <code>dt</code> accessor:</p>
<pre><code>df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y')
</code></pre> | python|datetime|pandas | 73 |
362,951 | 19,379,949 | Pandas Multi-Colum Boolean Indexing/Selection with Dict Generator | <p>Lets imagine you have a DataFrame df with a large number of columns, say 50, and df does not have any indexes (i.e. index_col=None). You would like to select a subset of the columns as defined by a required_columns_list, but would like to only return those rows meeting a mutiple criteria as defined by various boolea... | <p>Suppose this is your df:</p>
<pre><code>df = pd.DataFrame(np.random.randint(0,4,(100,50)),index=None,columns=["Col" + ("%03d" % (i + 1)) for i in range(50)])
# the first five cols and rows:
df.iloc[:5,:5]
Col001 Col002 Col003 Col004 Col005
0 2 0 2 3 1
1 0 1 0... | python|pandas | 1 |
362,952 | 19,758,259 | Reshaping Error in python | <p>I am new to python, and I am trying to execute the following code, but I get the following error:</p>
<pre><code>im[:,:,0] = f
ValueError: could not broadcast input array from shape (700,900,3) into shape (700,900)
</code></pre>
<p>Can someone assist me with it?</p>
<pre><code>img = numpy.zeros((700, 900))
row_i... | <p>It should work with:</p>
<pre><code>im[..., 0] = f[..., 0]
</code></pre>
<p>The problem is that you were trying to put the whole <code>f</code> into <code>im[..., 0]</code>, giving the <code>ValeError</code> due to the dimension incompatibilty.</p> | python|numpy | 1 |
362,953 | 12,964,803 | Numpy + Python 15x slower than MATLAB? | <p>Here is some code I wrote in Python / Numpy that I pretty much directly translated from MATLAB code. When I run the code in MATLAB on my machine, it takes roughly 17 seconds. When I run the code in Python / Numpy on my machine, it takes roughly 233 seconds. Am I not using Numpy effectively? Please look over my Pytho... | <p>Difference in performance between Numpy and Matlab for basic array/matrix operation is most probably due to Numpy being installed against a slower Lapack implementation. For maximum performance you may consider building numpy against LAPACK (<a href="http://www.scipy.org/Installing_SciPy/Linux" rel="nofollow">instru... | python|matlab|numpy | 1 |
362,954 | 13,146,542 | Broadcasting columns from a 2D numpy array to a larger 2D array based on an array of floats | <p>I'm not quite sure how to say this so I'll try to be clear in my description.
Right now I have a 3D numpy array where the 1st column represents a depth and the 2nd a position on the x-axis. My goal is to make a pcolor where the columns are spread out along the x-axis based on the values in a 1D float array.</p>
<p... | <p>Since there is so much whitespace, perhaps it would be easier to draw the <a href="http://matplotlib.org/api/artist_api.html#matplotlib.patches.Rectangle" rel="nofollow noreferrer">Rectangles</a>, rather than use <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pcolor" rel="nofollow noreferrer">p... | python|numpy|matplotlib|scipy | 4 |
362,955 | 13,132,009 | Numpy: placing values into an 1-of-n array based on indices in another array | <p>Suppose we had two arrays: some values, e.g. <code>array([1.2, 1.4, 1.6])</code>, and some indices (let's say, <code>array([0, 2, 1])</code>) Our output is expected to be the values put into a bigger array, "addressed" by the indices, so we would get</p>
<pre><code>array([[ 1.2, 0. , 0. ],
[ 0. , 0. , 1.... | <p>With</p>
<pre><code>a = zeros((3,3))
b = array([0, 2, 1])
vals = array([1.2, 1.4, 1.6])
</code></pre>
<p>You just need to index it (with the help of <code>arange</code> or <code>r_</code>):</p>
<pre><code>>>> a[r_[:len(b)], b] = vals
array([[ 1.2, 0. , 0. ],
[ 0. , 0. , 1.4],
[ 0. , ... | python|numpy | 2 |
362,956 | 12,804,928 | Finding the vertical and the horizontal gradients of a image using python | <p>I'm just starting off on Image processing in python using Scipy, Numpy, Image libraries. I need to find the gradient field of the image in order to divide the pixels into bins. For that, I calculated the low pass Gaussian filter to reduce pixel by pixel noise. Now, I've to calculate the horizontal and vertical gradi... | <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html#scipy.signal.convolve2d" rel="nofollow">scipy.signal.convolve2d</a> should work for this.</p> | python|image|image-processing|numpy|scipy | 0 |
362,957 | 13,115,335 | How to plot a 3d scatterplot with the color determined from another variable? | <p>I made a 3d scatterplot that displays the position of galaxies in a cluster (basically like the latitude and longitude) as a function of their velocity. However, I've been asked to make the color of the data points be determined by another variable, h in the code. The purpose of the variable isn't important to kno... | <p>'Changing color upon redraw' issue was a <a href="https://github.com/matplotlib/matplotlib/issues/152" rel="nofollow">bug</a> but looks like it's fixed in the latest release (1.1.1). I've tested and confirmed that it's working as it should with 1.1.1.</p>
<p>For the <code>colorbar</code>, it needs a mappable. You c... | python|numpy|matplotlib | 1 |
362,958 | 13,216,087 | pandas DataFrame pivoting issue | <p>I've got some radar data that's in a bit of an odd format, and I can't figure out how to correctly pivot it using the pandas library.</p>
<p>My data:</p>
<pre><code> speed time
loc
A 63 0000
B 61 0000
C 63 0000
D 65 0000
A 73 0005
B 71 0005
C 73 0005
D 75 0005
</code></pre... | <p>You can use the pivot method here:</p>
<pre><code>In [71]: df
Out[71]:
speed time
loc
A 63 0
B 61 0
C 63 0
D 65 0
A 73 5
B 71 5
C 73 5
D 75 5
In [72]: df.reset_index().pivot('loc', 'time', 'speed')
Out[72]:
time ... | python|pandas | 5 |
362,959 | 28,961,082 | python package installation gives "error: command 'gcc' failed with exit status 1" | <p>I'm trying to install a python package called <code>mlabwrap-1.1</code> on Ubuntu, with python2.7. However, the installation fails and reports:</p>
<pre><code>error: command 'gcc' failed with exit status 1
</code></pre>
<p>Note: A while back I updated numpy and got a bunch of warnings, but I don't know if that has a... | <p>I've had this before and needed to install libevent-dev.</p>
<pre><code>apt-get install libevent-dev
</code></pre>
<p>I have no way to check this now, but it's worth a try I think.</p> | python|gcc|numpy|installation | 1 |
362,960 | 29,270,067 | How can I use python pandas add new columns in specific index | <p>I want to use the Google API to get the "location"s latitude and longitude in CSV file,and I can get 'lat' , 'lng' with the Google API Module. But I can not save the file back to the original file and insert behind "location"</p>
<p>my original file looks like:</p>
<pre><code>date time location bi... | <p>You can change the column order by using fancy indexing:</p>
<pre><code>In [179]:
# add the columns
df['lat'] = np.random.randn(len(df))
df['lng'] = np.random.randn(len(df))
df
Out[179]:
date time location birdName count birdName.1 count.1 \
0 1990-02-10 0900:1200 balabala bird1 15 ... | python|google-maps|csv|pandas | 0 |
362,961 | 29,111,708 | How can I keep the pyqt GUI responsive when performing a cpu intensive task? | <p>I'm writing a data acquisition program and I'm interested in keeping the GUI responsive at all times. That's why I'm using QThreads for the job. Even though the result is slightly better when comparing with case in which the whole job is done in a single thread, my GUI still hangs until the task is done. This is the... | <p>You can use threading to solve your problem.</p>
<p>You can put your image writing function inside a new thread and then that task will get independent of your UI part and hence it will not lag.</p>
<p>I have done it and let me know if you need any further help.</p>
<pre><code>class ThreadLiveViewProcessing(QThread)... | python|numpy|pyqt | -1 |
362,962 | 29,114,427 | How to place a NumPy array in between another array? | <p>I have two arrays, array A and B as:</p>
<pre><code>import numpy as np
A = np.array(['A', 'B', 'C', 'D', 'E'])
B = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]])
</code></pre>
<p>which I want to be mixed so that array B is placed in between A to give me an array C of the form:</p>
<pre><code>... | <p>You can use a combination of <code>reshape</code> (to expose the target axis) and <code>concatenate</code> (to join the arrays along this axis), with <code>reshape</code>ing back to the desired form:</p>
<pre><code>import numpy as np
A = np.array(['A', 'B', 'C', 'D', 'E'])
B = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9... | python|arrays|numpy | 2 |
362,963 | 28,892,244 | Data which would give me same eigenvectors? | <p>Any suggestion on what kind of dataset lets say nXd (n rows, d columns) would give me same eigenvectors?. </p>
<p>I believe it should be the one with like same absolute values in each cell. Like alternating +1 and -1. But it seems to work otherwise. </p>
<p>Any pointers?</p> | <p>This is a bit open ended, but there are many ways with the basic idea being <strong>start with the eigenvectors you want and alter the eigenvalues and/or re-arrange the eigenvectors to create different data sets</strong>. </p>
<p>Here's two simple working examples. First, you can just scale the eigenvalues of mat... | python|pandas|statistics | 0 |
362,964 | 29,082,412 | append rows to a Pandas groupby object | <p>I am trying to figure out the best way to insert the means back into a multi-indexed pandas dataframe.</p>
<p>Suppose I have a dataframe like this:</p>
<pre><code> metric 1 metric 2
R P R P
foo a 0 1 2 3
b 4 5 6 7
bar a 8 9 ... | <p>The main thing you need to do here is append your means to the main dataset. The main trick you need before doing that is just to conform the indexes (with the <code>reset_index()</code> and <code>set_index()</code> so that after you append them they will be more or less lined up and ready to sort based on the same... | python|pandas | 2 |
362,965 | 33,815,129 | Create test/train split based on two groups with Pandas Scikit-learn | <p>I have a Pandas dataframe: <code>comb</code>
the number of <code>ENROLLED_Response</code> entries is quite small, so just random sampling of the entire DataFrame may lose too much of the enrolled data.</p>
<p>the solution is to take a 75% sample of all the entries where <code>ENROLLED_Response == True</code>
and th... | <p>Updated after comment:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed(42)
truePct = 0.75
falsePct = 0.70
comb = pd.DataFrame({
"feat1": np.random.randint(low=1, high=4, size=20),
"feat2": np.random.randint(low=1, high=4, size=20),
"ENROLLED_Response": np.random.randint(low=0, h... | python|pandas|scikit-learn | 0 |
362,966 | 33,762,831 | Error when building seq2seq model with tensorflow | <p>I'm trying to understand the seq2seq models defined in seq2seq.py in tensorflow. I use bits of code I copy from the translate.py example that comes with tensorflow. I keep getting the same error and really do not understand where it comes from.</p>
<p>A minimal code example to reproduce the error:</p>
<pre><code>i... | <p>Most of the models (seq2seq is not an exception) expect their input to be in batches, so if the shape of your logical input is <code>[n]</code>, then a shape of a tensor you will be using as an input to your model should be <code>[batch_size x n]</code>. In practice the first dimension of the shape is usually left o... | python|machine-learning|neural-network|deep-learning|tensorflow | 8 |
362,967 | 33,566,939 | timedelta error with numpy.longdouble dtype | <p>I have times with dtype <code>numpy.longdouble</code> and when I'm trying to use that values with <code>timedelta</code> function I've got errors. But when I convert it to <code>numpy.float64</code> everything is fine. Could somebody explain that behaviour?</p>
<pre><code>import numpy as np
from datetime import tim... | <blockquote>
<p>So maybe <code>timedelta</code> for dtype <code>np.longdouble</code> isn't implemented?</p>
</blockquote>
<p>In short, yes.</p>
<p>From <a href="https://docs.python.org/2/library/datetime.html#timedelta-objects" rel="nofollow noreferrer">the documentation</a>:</p>
<blockquote>
<p><em>class</em> <code>da... | python|numpy|types|timedelta|python-datetime | 8 |
362,968 | 33,710,198 | Saving a matrix with columns' header in python | <p>I have the following code. When i save it. The headers of columns don't save. Could u please guide me? </p>
<pre><code>import numpy as np
import pandas as pd
A = np.random.randint(0, 10, size=36).reshape(6, 6)
df = pd.DataFrame(A, columns=['one', 'two', 'three','four','five','six'])
np.savetxt("/home/dataset/te... | <p>Use the built-in <code>pandas</code> function for this:</p>
<pre><code>df.to_csv("your_file_path_here")
</code></pre> | python|numpy|import | 2 |
362,969 | 33,857,115 | subset rows of pandas dataframe by string match on column | <p>pool is a dataframe, and one of the columns is "Name"
If key == 'Bob', then this line correctly gives me all the rows where Name=='Bob':</p>
<pre><code>keyrows = pool[key == pool.Name]
</code></pre>
<p>I instead want to get all the rows that match 'Bob', like "Bob Jones" and "Bob Marley", etc.</p>
<p>So I changed... | <p>@behzad.nouri gave me the solution:</p>
<pre><code>keyrows = pool[pool.Name.str.contains(key)]
</code></pre>
<p>does exactly what I want.</p> | python|pandas | 4 |
362,970 | 33,864,581 | Vectorized version of Brent's algorithm (root-finding) | <p>I'm working on a Python version of the equation of state of seawater (<a href="http://www.teos-10.org/" rel="nofollow">http://www.teos-10.org/</a>). The library depends on inverting equations like <code>p = f(t,d)</code> where you can directly calculate <code>f(t,d)</code> if you knew <code>t</code> and <code>d</cod... | <p>If you write a fully vectorized or array-oriented version of any iterative method, it can be come very inefficient. For example, you might need a large number of iterations over a small part of your range while most of your range converges on a small number of iterations.</p>
<p>You could solve your equation over ... | python|numpy|vectorization|mathematical-optimization | 5 |
362,971 | 33,622,888 | How to Plot 2 lines based on the value not column | <p>I have a data set:</p>
<pre><code>ReviewDate_year,ReviewDate_month,Sales
2010,11,1
2011,02,2
2011,11,1
2011,12,6
2012,01,11
2012,02,8
2012,03,3
2012,04,1
2012,05,8
2012,06,3
2012,07,1
2012,08,2
2012,09,1
2012,11,1
2012,12,8
2013,01,2
2013,02,2
2013,03,4
2013,04,4
2013,05,7
2013,06,5
2013,07,6
... | <p>You can use <code>groupby</code> plot. Instead of creating one <code>ax</code> for each group, you can specify an <code>ax</code> and have everything plotted on that <code>ax</code>:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
ax = plt.subplot(11... | python|pandas|matplotlib|plot | 4 |
362,972 | 33,838,465 | Perform function on pairs of rows in Pandas dataframe | <p>Say I have the following dataframe:</p>
<pre><code>>>> df=pd.DataFrame(data=['A','B','C','D','E'], columns=['Name'])
>>> df
Name
0 A
1 B
2 C
3 D
4 E
>>>
</code></pre>
<p>I want to create a list of values for adjacent rows in the dataframe. If I create an index of pairs ... | <p>You can groupby by "adjacency" in one go (without mutating the DataFrame):</p>
<pre><code>In [11]: g = df.groupby(df.index // 2)
</code></pre>
<p>and then do whatever it is you need to do:</p>
<pre><code>In [12]: g.get_group(0)
Out[12]:
Name
0 A
1 B
In [13]: g.sum()
Out[13]:
Name
0 AB
1 CD
2 E
<... | python|pandas | 8 |
362,973 | 23,944,242 | How do numpy and GMPY2 compare with GMP in terms of speed? | <p>I understand that GMPY2 supports the GMP library and numpy has fast numerical libraries. I want to know how the speed compares to actually writing C (or C++) code with GMP. Since Python is a scripting language, I don't think it will ever be as fast as a compiled language, however I have been wrong about these genera... | <p>numpy and GMPY2 have different purposes.</p>
<p>numpy has fast numerical libraries but to achieve high performance, numpy is effectively restricted to working with vectors or arrays of low-level types - 16, 32, or 64 bit integers, or 32 or 64 bit floating point values. For example, numpy access highly optimized rou... | python|c|numpy|gmp|gmpy | 8 |
362,974 | 23,889,048 | Reshaping two-column data using pandas pivot | <p>I am trying to reshape a long text file with two columns (a repeating date_time sequence and a single column of numerical values) into a Pandas dataframe with a single index of date_time and multiple columns of data. The actual file is 100 sets of 82 years of daily rainfall data (from a stochastic generator) and is ... | <p>You should first create a new column that indicates in which column the value has to come. </p>
<p>Supposing you know the starting date of each sequence (and it is the same each time), you can e.g. do that like this:</p>
<pre><code>In [7]: df['set'] = (df['date'] == '2014/01/01').cumsum()
In [8]: df
Out[8]:
... | python|python-3.x|pandas|pivot | 5 |
362,975 | 23,739,277 | How should I pass a matplotlib object through a function; as Axis, Axes or Figure? | <p>Sorry in advance if this is a little long winded but if I cut it down too much the problem is lost. I am trying to make a module on top of pandas and matplotlib which will give me the ability to make profile plots and profile matrices analogous to scatter_matrix. I am pretty sure my problem comes down to what object... | <p>You should pass around <code>Axes</code> objects and break your functions up to operate on a single axes at a time. You are close, but just change </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def _profile(ax, x, y):
ln, = ax.plot(x, y)
# return the Artist created
return ln
def... | python|matplotlib|pandas|histogram|canopy | 17 |
362,976 | 23,887,135 | pandas indexing in multiindex dataframe | <p>i do have an excel file:</p>
<pre><code><> 1 2 3
A
B
C
</code></pre>
<p>with my data in each cell.</p>
<p>in another sheet i do have my description:</p>
<pre><code> name pH salt id
A1 sample 8.5 50 1
A2 sample 8.5 50 1
A3 sample 8.5 50 2
B1 sample ... | <p>See the basic indexing documentation: <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#basics" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/indexing.html#basics</a></p>
<p>When indexing a Series, <code>s['some_name']</code> will access the <em>row</em> with label <code>some_name</cod... | python|pandas | 1 |
362,977 | 23,499,751 | Scatter plot (2D), which shows a dotted circle and other 2D-shapes made by geometrical functions with ipython, numpy and matplotlib | <p>I would to create an array with the "shape" (n, 2), which is creating a dotted circle, when plotted on a scatterplot.</p>
<p>This would be the wanted form of the array:</p>
<pre><code>array([ (x1, y1),
(x2, y2),
(x3, y3),
(x4, y4),
....
(xN, yN),
])
</code></pre>
<p>This ... | <p>Here is a method for the circle in 2D.</p>
<pre><code>def CreateCircleArray(radius=1):
theta = np.linspace(0, 2*np.pi, 50)
x = radius * np.cos(theta)
y = radius * np.sin(theta)
return np.array([x, y]).T
def PlotArray(array):
ax = plt.subplot(111, aspect="equal")
ax.scatter(array[:, 0], arra... | numpy|multidimensional-array|matplotlib|ipython|projection | 2 |
362,978 | 22,674,869 | Sorting Multi-Index levels based on column properties | <p>Say I have a MultiIndex dataframe <code>df</code>:</p>
<pre><code> C D E
A B
bar one 0.934232 0.518263 0
three 0.079759 0.192417 2
flux six 1.484391 -0.607172 2
three -1.816136 -0.660524 1
foo five -0.695819 -0.406685 0
one -... | <p>One efficient hack is to replace the levels (of the MultiIndex) inplace, sort, then put them back:</p>
<pre><code>In [11]: levels = df.index.levels
In [12]: e0 = -df.groupby(level=0).E.median()
In [13]: d1 = df.groupby(level=1).D.min()
In [14]: df.index.levels = [e0, d1]
In [15]: df = df.sort_index()
In [16]: ... | python|pandas | 2 |
362,979 | 22,649,896 | Creating and modifying an empty Pandas DataFrame results in unpredictable behavior | <p>I am trying to understand why my code, which initializes and then modifies a new column in a Pandas DataFrame, is behaving erratically. My code is as follows:</p>
<pre><code>pos = df['sign'] == 'Pos'
neg = df['sign'] == 'Neg'
df['signed_val'] = 0
df['signed_val'][pos] = df['abs_val'][pos]
df['signed_val'][neg] = ... | <p>you are doing chained assignment, see here: <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy</a></p>
<p>on a single dtyped frame this will consistently work ; in general on... | python|pandas | 3 |
362,980 | 22,749,489 | Why does 'rmagic' %R cause an error when reading a file, while %%R does not? | <p>Using <code>rmagic</code> I'm getting inconsistent behavior between <code>%R</code> and <code>%%R</code> when reading <a href="https://courses.edx.org/c4x/MITx/15.071x/asset/USDA.csv" rel="nofollow">a particular file</a> (and not others): Why does </p>
<pre><code>%%R
usda = read.csv("USDA.csv")
</code></pre>
<p>w... | <p>That's a missing value handling issue I have seen before. It should happen whenever you have missing values. I am not sure if we should consider it as a bug. But <code>%R -n usda = read.csv('USDA.csv')</code> to suppress returning (a <code>numpy</code> <code>array</code>) using <code>-n</code> will avoid the problem... | python|r|csv|pandas|dataframe | 1 |
362,981 | 22,667,093 | How to convert the numpy.ndarray to a cv::Mat using Python/C API? | <p>I use python as an interface to operate the image, but when I need to write some custom functions to operate the matrix, I find out that numpy.ndarray is too slow when I iterate. I want to transfer the array to cv::Mat so that I can handle it easily because I used to write C++ code for image processing based on cv::... | <p>It's been a while since I've played with raw C python bindings (I usually use <code>boost::python</code>) but the key is <a href="http://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.PyArray_FromAny" rel="nofollow noreferrer">PyArray_FromAny</a>. Some untested sample code would look like</p>
<pre><code>PyO... | python|c++|opencv|numpy|python-c-api | 0 |
362,982 | 22,820,143 | Python:Numpy Function not yielding correct results | <p>I had a question concerning the results of a polynomial equation while using python/numpy.
I have defined a function using a polynomial having a rather small leading coefficient.
The following is my code and the equation:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
def myfunction(X):
ret... | <p>This is an <code>int</code> vs. <code>float</code> issue. You're getting integer overflow:</p>
<pre><code>>>> np.int32(100)**6
-727379968
>>> np.float32(100)**6
1000000000000.0
</code></pre>
<p>because <code>np.arange(0, 100, 1)</code> is giving you integers.</p>
<p>You can make them floats how... | python|arrays|numpy|polynomial-math|polynomials | 4 |
362,983 | 22,779,437 | Cython function with variable sized matrix input | <p>I am trying to convert part of a native python function to cython to improve the compute time. I would like to write a cython function just for the loop component that is taking up the time (as ipython lprun kindly told me). However this function takes in variably sized matrices .. and I can't see how to bring that ... | <p>Cython code is (strategically) statically typed, but that doesn't mean that arrays must have a fixed size. In straight C passing a multidimensional array to a function can be a little awkward maybe, but in Cython you should be able to do something like the following:</p>
<p>Note I took the function and variable nam... | python|numpy|cython | 3 |
362,984 | 22,685,871 | Efficiently select elements from numpy array with multiple criteria | <p>I'm looking for the fastest way to select the elements of a numpy array that satisfy several criteria. As an example, say I want to select all elements that lie between 0.2 and 0.8 from an array. I normally do something like this:</p>
<pre><code>the_array = np.random.random(100000)
idx = (the_array > 0.2) * (the... | <p>You could implement a custom C call for the select. The most basic way to do this is through a <code>ctypes</code> implementation.</p>
<p><strong>select.c</strong></p>
<pre><code>int select(float lower, float upper, float* in, float* out, int n)
{
int ii;
int outcount = 0;
float val;
for (ii=0;ii<n;ii++... | python|arrays|numpy | 1 |
362,985 | 15,327,099 | Strategies for handling nominal values with numerical attributes | <p>I'm using a data set that consists of mostly nominal values from SFDC (e.g. EE Names, Title, Role, Lead Source, Account Name, etc.) and am trying to correlate the features to a boolean class of whether a Sales Lead was converted to a Sales Contact. </p>
<p>I wanted to run this data through some basic feature select... | <p>I would first try to use <a href="http://scikit-learn.org/stable/modules/feature_extraction.html#loading-features-from-dicts" rel="nofollow">sklearn.feature_extraction.DictVectorizer</a> and then try Chi2 univariate feature selection that can work with sparse data representations. For instance there is an applicatio... | numpy|machine-learning|pandas|scikit-learn|feature-selection | 1 |
362,986 | 15,329,557 | My numpy array always ends in zero? | <p>I think I missed something somewhere. I filled a numpy array using two for loops (x and y) and a function based on the x,y position. The only problem is that the value of the array always ends in zero irregardless of the size of the array. </p>
<pre><code>thetamap = numpy.zeros(36, dtype=float)
thetamap.shape = (6... | <p><code>range(0, 5)</code> produces <code>0, 1, 2, 3, 4</code>. The endpoint is always omitted. You want simply <code>range(6)</code>.</p>
<p>Better yet, use the <em>awesome power of NumPy</em> to make the array in one line:</p>
<pre><code>thetamap = np.arange(6) + np.arange(6)[:,None]
</code></pre>
<p>This makes a... | python|math|numpy | 8 |
362,987 | 15,412,061 | Numpy nonzero/flatnonzero index order; order of returned elements in boolean indexing | <p>I'm wondering about the order of indices returned by numpy.nonzero / numpy.flatnonzero. </p>
<p>I couldn't find anything in the docs about it. It just says:</p>
<pre><code>A[nonzero(flag)] == A[flag]
</code></pre>
<p>While in most cases this is enough, there are some when you need a sorted list of indices. Is it ... | <p>Given the specification for <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer" rel="nofollow">advanced (or "fancy") indexing with integers</a>, the guarantee that <code>A[nonzero(flag)] == A[flag]</code> is also a guarantee that the values are sorted low-to-high in the 1-d case. However... | python|numpy | 1 |
362,988 | 15,395,127 | arithmetic comparisons on numpy arrays | <pre><code>>>> import numpy as np
>>> x = np.eye(3)
>>> x[1, 2] = .5
>>> x
array([[ 1. , 0. , 0. ],
[ 0. , 1. , 0.5],
[ 0. , 0. , 1. ]])
>>> 0 < x.any() < 1
False
>>>
</code></pre>
<p>I would like to check if numpy array contains any valu... | <pre><code>>>> np.any((0 < x) & (x < 1))
True
</code></pre>
<p>What <code>x.any()</code> actually does: it's the same as <code>np.any(x)</code>, meaning it returns <code>True</code> if any elements in <code>x</code> are nonzero. So your comparison is <code>0 < True < 1</code>, which is false b... | python|numpy | 2 |
362,989 | 15,317,822 | Calculating Covariance with Python and Numpy | <p>I am trying to figure out how to calculate covariance with the Python Numpy function cov. When I pass it two one-dimentional arrays, I get back a 2x2 matrix of results. I don't know what to do with that. I'm not great at statistics, but I believe covariance in such a situation should be a single number. <a href=... | <p>When <code>a</code> and <code>b</code> are 1-dimensional sequences, <code>numpy.cov(a,b)[0][1]</code> is equivalent to your <code>cov(a,b)</code>.</p>
<p>The 2x2 array returned by <code>np.cov(a,b)</code> has elements equal to</p>
<pre><code>cov(a,a) cov(a,b)
cov(a,b) cov(b,b)
</code></pre>
<p>(where, again, <... | python|numpy|covariance | 136 |
362,990 | 13,628,491 | how to convert an image from BGR to LAB with opencv 2.4 python 2.7 and numpy | <p>I am working with opencv 2.4 and numpy. I would like to open an image and get all the information about it (8 bit - if its RGB-BGR etc) and also try to change the color space.
I have this code:</p>
<pre><code>if __name__ == '__main__':
img = cv2.imread('imL.png')
conv= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)... | <p>That rigtht you will get a different image colour because imwrite() saves file in the format specified (PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with ‘BGR’ channel order). images can be saved using this function. imwrite() doesn't know the format LAB to save image as it always expect the image in BGR. ... | image-processing|opencv|numpy|python-2.7 | 3 |
362,991 | 13,714,357 | Using Numpy to get an average of an array within a matrix | <pre><code>columnFour = [data[0::, 1] == 1, data[0::, 4]]
</code></pre>
<p>The data is a table, with 1 being the variable I'm selecting for (where it equals 1), and 4 the variable I'm trying to draw out into an array of one dimension. </p>
<p>Some of the values in the 4 column are blank (''), and the error I'm gettin... | <p>I think you want something like:</p>
<pre><code>mask = data[:, 1] == 1
average = np.mean(data[mask, 4])
</code></pre>
<p>There is no list comprehension in the code you've provided, you just create a list with two elements, the first <code>data[:, 1] == 1</code> and the second <code>data[:, 4]</code>.</p> | python|numpy|list-comprehension | 0 |
362,992 | 13,592,841 | PCA on large Sparse matrix using Correlation matrix | <p>I have a large (500k by 500k), sparse matrix. I would like to get the principle components of it (in fact, even computing just the largest PC would be fine). Randomized PCA works great, except that it is essentially finding the eigenvectors of the covariance matrix instead of the correlation matrix. Any ideas of a p... | <p>Are they not the same thing? As far as I understand it, the correlation matrix is just the covariance matrix normalised by the product of each variable's standard deviation. And, if I recall correctly, isn't there a scaling ambiguity in PCA anyway?</p> | python|matlab|numpy|machine-learning|sparse-matrix | 0 |
362,993 | 13,588,684 | Independence of variables bound to NumPy arrays | <p>I have a NumPy array, let's call it <code>A</code>. The behavior of the following code is not clear to me:</p>
<pre><code>b = A[3,:];
A[3,:] = 0;
</code></pre>
<p>The third row must be saved in <code>b</code>, but surprisingly <code>b</code> becomes zero also!</p>
<p>Any Help?</p> | <p>To make a copy, you must, in fact, make a <code>copy</code>!</p>
<pre><code>b = A[3,:].copy()
</code></pre>
<p>(By the way, python is not C: no semicolons after statements needed.)</p> | python|numpy | 2 |
362,994 | 13,476,807 | probability density function from histogram in python to fit another histrogram | <p>I have a question concerning fitting and getting random numbers.</p>
<p>Situation is as such:</p>
<p>Firstly I have a histogram from data points. </p>
<pre><code>import numpy as np
"""create random data points """
mu = 10
sigma = 5
n = 1000
datapoints = np.random.normal(mu,sigma,n)
""" create normalized histro... | <p>You can use a cumulative density function to generate random numbers from an arbitrary distribution, as <a href="http://www.av8n.com/physics/arbitrary-probability.htm" rel="noreferrer">described here</a>.</p>
<p>Using a histogram to produce a smooth cumulative density function is not entirely trivial; you can use i... | python|numpy|matplotlib|scipy | 8 |
362,995 | 13,627,576 | Pythonic way to import data from multiple files into an array | <p>I'm relatively new to Python and wondering how best to import data from multiple files into a single array. I have quite a few text files containing 50 rows of two columns of data (column delimited) such as:</p>
<pre><code>Length=10.txt:
1, 10
2, 30
3, 50
#etc
END OF FILE
</code></pre>
<p>-</p>
<p... | <p><em>"But the problem with this code, is that I can only process data when it's in the for loop. "</em></p>
<p>Assuming your code works:</p>
<pre><code># Get folder path containing text files
file_list = glob.glob(source_dir + '/*.TXT')
data = []
for file_path in file_list:
data.append(
np.genfromtxt(fi... | python|arrays|file|import|numpy | 7 |
362,996 | 13,256,482 | if statement in numpy array always needs vectorization | <p>The if statement in this function, works without vectorization?</p>
<pre><code>def K(T0,z,v):
for i in range(len(T0)-1):
GDens[i+1]=(Dens[i+1]-Dens[i])/(z[i+1]-z[i])
for i in range(len(T0)):
B[i]=(((ws/Dens0)*k0)**2)*np.exp(-2*alfa*z[i])-((g/Dens0)*GDens[i])
for i in range(len(T0)):
... | <p>I'm not sure what you're asking but this is how you can vectorize this code:</p>
<pre><code> GDens = np.zeros_like(z)
GDens[:-1] = (Dens[1:] - Dens[:-1]) / (z[1:] - z[:-1])
B = (((ws/Dens0)*k0)**2)*np.exp(-2*alfa*z)-((g/Dens0)*GDens)
kz = np.where(B > 0, ((0.05*h1)**2)*np.sqrt(B)+kmin, kmin)
</code></pre> | numpy|vectorization | 2 |
362,997 | 29,422,129 | How to multiply two dataframes if they have the same index value along the corresponding row? | <p>Suppose I have something like this (which may have the forecast_date index repeated):</p>
<pre><code>df1:
forecast_date value
2015-04-11 18952
2015-04-12 18938
2015-04-13 18940
2015-04-14 18949
2015-04-15 18955
2015-04-16 18956
...
2015-04-02 18950
2015-04-03 189... | <p>If you set the index to be the dates for both df's then multiplication will align where the indices match:</p>
<pre><code>In [46]:
df['value'] * df1['value']
Out[46]:
2015-04-01 NaN
2015-04-02 25582.50
2015-04-03 25417.12
2015-04-04 NaN
2015-04-11 NaN
2015-04-12 NaN
2015-04-13... | python|pandas|dataframe | 1 |
362,998 | 29,428,294 | pandas - apply datetime functions | <p>I'm going beyond <a href="https://stackoverflow.com/questions/29366572/pandas-how-to-filter-most-frequent-datetime-objects/29366831?noredirect=1#comment46916575_29366831">this</a> question to get further information about a datetime dataframe. Working with a DataFrame like this:</p>
<pre><code>User_ID Datetime
0... | <p>Here is an alternative way to do it using pandas magic:</p>
<pre><code>df['Datetime'] = pd.to_datetime(df.Datetime) # You can skip this step if you already have it as Datatime object
df1 = df.groupby(['User_ID', df.Datetime.dt.year]).apply(lambda x: x.Datetime.dt.month.nunique())
ids = df1[df1 >= 12].index.get_... | python|datetime|pandas | 2 |
362,999 | 29,389,525 | Pandas - Delete rows with two or more NaN values in dataframe | <p>I want to delete column values that contain too many NaN values; specifically: 2 or more.
I have a dataframe with column which looks like this. The below column had 40 rows . I want to remove NaN values from 19th row (after 17.9 value).</p>
<pre><code>AvgWS
0.12
1
2.04
3.01
3.99
5
6
7
7.99
9
1... | <p>You can call <code>isnull()</code> on the column, this will return a series with boolean values, you then cast this to <code>int</code>, the <code>True</code> values become <code>1</code> and <code>False</code> becomes <code>0</code> and then call <code>cumsum()</code>, we then filter the df where the cumumlative su... | numpy|pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.