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 |
|---|---|---|---|---|---|---|
8,800 | 66,539,653 | Pandas - Number of rows to the last row in a group that meets a requirement | <p>My data is like this</p>
<pre><code>date group meet_criteria
2020-03-31 1 no
2020-04-01 1 yes
2020-04-02 1 no
2020-04-03 1 no
2020-04-04 1 yes
2020-04-05 1 no
2020-03-31 2 yes
2020-04-01 2 no
... | <p>This can be done using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>pd.merge_asof</code></a> & subsequent calculations in pandas.</p>
<p>Here's a fully worked example with your data (original data loaded into a variable called <code>d... | python|pandas | 0 |
8,801 | 66,731,885 | How Encoder passes Attention Matrix to Decoder in Tranformers 'Attention is all you need'? | <p>I was reading the renowned paper <a href="https://arxiv.org/abs/1706.03762" rel="nofollow noreferrer">'Attention is all you need'</a>. Though I am clear with most of the major concepts, got buggy with a few points
<a href="https://i.stack.imgur.com/8wE8A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur... | <ol>
<li><p>The Encoder passes the 'Attention' matrix calculated. This attention matrix is considered as the 'Key' & 'Value' matrix for the Decoder Multi-Head Attention module</p>
</li>
<li><p>Why do we need shifted output for testing? It is not required as when testing, we need to predict from token one for which ... | machine-learning|nlp|artificial-intelligence|huggingface-transformers|attention-model | 0 |
8,802 | 66,415,018 | Rearrange dataframe in pandas - move sets of rows into new column | <p>I have a dataframe file <code>df</code> that looks like:</p>
<p><a href="https://i.stack.imgur.com/cNX4a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cNX4a.png" alt="input dataframe" /></a></p>
<p>which I am trying to convert into:</p>
<p><a href="https://i.stack.imgur.com/XiUUo.png" rel="nofol... | <p>Do you need the column "Unnamed:0"? if not, a simple way would be to do:</p>
<pre><code>df = pd.DataFrame({0:df[range(3)].values[[0,2,4]].flatten(),1:df[range(3)].values[[1,3,5]].flatten()}).T
</code></pre>
<p>if you need the column 'Unnamed: 0', you could add the following line:</p>
<pre><code>df['Unnamed... | python|pandas|dataframe | 0 |
8,803 | 57,346,628 | Most elegant way to select rows by a string value | <p>Is there a more elegant way to write this code:</p>
<pre><code>df['exchange'] = frame.loc[frame['Description'].str.lower().str.contains("on wallet exchange")]
</code></pre>
<p>The .str twice seems ugly.</p>
<p>When I iterate over the entire dataframe row by row, I can use:</p>
<pre><code>if "on wallet exchange" ... | <p>Use <code>case=False</code> , also add <code>na=False</code> to be safe so if the series contains either numerics(@ jezrael-Thank you ) or NaN , this will be evaluated as False</p>
<pre><code>frame.loc[frame['Description'].str.contains("on wallet exchange",case=False,na=False)]
</code></pre> | python|pandas | 6 |
8,804 | 57,366,684 | Import file with pandas to Jupyter Notebook running on iPad with the app carnets | <p>I’m running a Jupyter notebook on my iPad with an app called Carnets (vs. creating a remote server). I have been attempting to import a dataset into the notebook to create a panda’s dataframe. </p>
<p>So the dataset I’m tying to use is from kaggle. I first tried uploading it to GitHub LFS. I was able to successfull... | <p>I’m the author of the app. The issue is related to iOS limitations on file access. </p>
<p>Carnets can access all files in the App directory. Since you have issues, I guess the notebook is not in the App directory, but in another App. By opening the notebook, you granted Carnets access to the notebook, but not to ... | python|pandas|jupyter-notebook|kaggle | 5 |
8,805 | 73,064,148 | Why does a derived MultiIndex retain unused level data from the original index in pandas? | <p>When a filtered <code>MultiIndex</code> is derived from a larger <code>MultiIndex</code> instance, it appears that there's a discrepancy between the level values returned by <code>MultiIndex.levels</code> and <code>MutliIndex.get_level_values()</code>:</p>
<pre><code>import pandas as pd
times = pd.date_range('2012-... | <p>If use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.remove_unused_levels.html" rel="nofollow noreferrer"><code>MultiIndex.remove_unused_levels</code></a> then get:</p>
<pre><code>new_index = index[index.get_level_values(0) > '20120701'].remove_unused_levels()
</code></pre>
... | pandas | 1 |
8,806 | 70,544,368 | Setting (Dynamic) String Equal to Output of a Function | <p>Is it possible to set a (dynamic) string equal to the output of a function?</p>
<p>Please see picture below...unfortunately, I'm not able to get it to work using the method shown here.</p>
<p><a href="https://i.stack.imgur.com/ZgRjI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZgRjI.png" alt="e... | <p>The code <em>is</em> actually working, but you need to make your <code>simulator()</code> function <strong>return</strong> the dataframe it makes. It <em>prints</em> it, but it doesn't return it:</p>
<p>Change the code for your <code>simulator</code> function to this:</p>
<pre><code>def simulator():
df = pd.Data... | python|pandas|string|dataframe|function | 1 |
8,807 | 70,392,276 | How to compare rows within a dataframe column and check if value is changing? | <p>I have a data frame as seen:</p>
<p><a href="https://i.stack.imgur.com/jAZB8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jAZB8.png" alt="enter image description here" /></a></p>
<p>How to check conditions when results change from 'NO' to 'OK' and if it does populate the next column as true. Re... | <p>Try:</p>
<pre><code>df['check'] = df['Result'].eq('OK') & df['Result'].shift().eq('NO')
print(df)
# Output:
Result check
0 NO False
1 OK True
2 OK False
3 NO False
4 OK True
5 OK False
6 OK False
7 NO False
</code></pre>
<p>To display correctly:</p>
<pre><code>df['ch... | python|pandas|dataframe | 1 |
8,808 | 51,333,491 | pandas groupby NA behavior not consistent with R? | <p>The pandas documentation says: </p>
<p>"NA groups in GroupBy are automatically excluded. This behavior is consistent with R, for example"</p>
<p>I understand the documentation but not how this is consistent with R? Here's an example using a dataframe x with tidyverse. </p>
<pre><code>> x
c b a
1 NA 1 NA
2 ... | <p><a href="https://github.com/pwwang/datar" rel="nofollow noreferrer"><code>datar</code></a> tries to follow the API designs of <code>tidyrverse</code>:</p>
<pre class="lang-py prettyprint-override"><code>>>> from datar.all import f, c, tibble, group_by, summarise, mean, NA
>>> x = tibble(c=[NA,NA,NA... | r|pandas | 0 |
8,809 | 71,024,914 | install python huggingface datasets package without internet connection from python environment | <p>I dont have access to internet connection from my python environment. I would like to install this <a href="https://pypi.org/project/datasets/" rel="nofollow noreferrer">library</a></p>
<p>I also noticed this <a href="https://pypi.org/project/datasets/#files" rel="nofollow noreferrer">page</a> which has files requir... | <p>Unfortunately the method 1 not working because not yet supported: <a href="https://github.com/huggingface/datasets/issues/761" rel="nofollow noreferrer">https://github.com/huggingface/datasets/issues/761</a></p>
<blockquote>
<p><strong>Method 1.:</strong> You should use the <code>data_files</code> parameter of the
... | python|package|huggingface-transformers|huggingface-datasets | 2 |
8,810 | 70,770,746 | Python parallel apply on dataframe | <p>I have this part of code in my application.
What I want is to iterate over each row in my data frame (pandas) and modify column to function result.</p>
<p>I tried to implement it with multiprocessing, but I'm to see if there is any faster and easier to implement way to do it.
Is there any simple way to run this part... | <p>I have a project which it is done there: <a href="https://github.com/mjafari98/dm-classification/blob/main/inference.py" rel="nofollow noreferrer">https://github.com/mjafari98/dm-classification/blob/main/inference.py</a></p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from functools import pa... | python|pandas|parallel-processing | 0 |
8,811 | 70,751,495 | How do you group pandas dataframe rows based on permutation of booleans? | <p>Imagine there is a pandas dataframe with five columns and n rows. Each column holds a boolean value.</p>
<p>Maths says there should be 32 permutations of boolean values.</p>
<p>How do I group them by the permutation of boolean values associated with each row so I can get a count on each group or return other propert... | <p>There are a couple of ways of doing this. One way would be to just group by all the columns you care about at once. If you want the counts, you can call the <code>GroupBy.count</code> method on the result:</p>
<pre><code>df.groupby(['c1', 'c2', 'c3', 'c4', 'c5']).count()
</code></pre>
<p>Or more simply, if all the c... | python|pandas|permutation | 1 |
8,812 | 51,733,136 | Pandas: Reading excel files when the first row is NOT the column name Excel Files | <p>I am using pandas to read an excel file. It doesn't have column name but it continues to read the first row as the column name. </p>
<p>Following is the excel file that is being read. </p>
<pre><code>data1 0.994676
data2 0.994588
data3 0.99488
data4 0.994483
data5 0.994312
data6 0.993823
data7 0.9935... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="noreferrer"><code>read_excel</code></a> with <code>header=None</code> for default columns with <code>rangeIndex</code>:</p>
<pre><code>df = pd.read_excel('file.xlsx',
sheet_name ='Data_sheet',... | python-3.x|pandas | 15 |
8,813 | 36,043,717 | Theano: Operate on nonzero elements of sparse matrix | <p>I'm trying to take the <code>exp</code> of nonzero elements in a sparse theano variable. I have the current code:</p>
<pre><code>A = T.matrix("Some matrix with many zeros")
A_sparse = theano.sparse.csc_from_dense(A)
</code></pre>
<p>I'm trying to do something that's equivalent to the following numpy syntax:</p>
<... | <p>The support for sparse matrices in Theano is incomplete, so some things are tricky to achieve. You can use <code>theano.sparse.structured_exp(A_sparse)</code> in that particular case, but I try to answer your question more generally below.</p>
<p><strong>Comparison</strong></p>
<p>In Theano one would normally use ... | python|numpy|theano | 1 |
8,814 | 37,304,309 | Type error on my fit function using gaussian process in scikit | <p>Ok, so I have been working on some code that takes an image that represents sparse point data from Houdini and interpolates it into a usable complete map. This has been working really well, except that now I am running into some memory issues. I have narrowed down the memory problem in the kriging algorithm I am u... | <p>This looks like a bug in scikit-learn in python 3 - the division <a href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/gaussian_process/gaussian_process.py#L510" rel="nofollow">here</a> results in a float in python 3, which <code>range</code> then rightly balks on.</p>
<p>There's a <a href="htt... | python|numpy|scipy|scikit-learn|interpolation | 3 |
8,815 | 41,831,214 | What is SYCL 1.2? | <p>I am trying to install tensorflow</p>
<pre><code>Please specify the location where ComputeCpp for SYCL 1.2 is installed. [Default is /usr/local/computecpp]:
Invalid SYCL 1.2 library path. /usr/local/computecpp/lib/libComputeCpp.so cannot be found
</code></pre>
<p>What should I do?What is SYCL 1.2?</p> | <p><a href="https://www.khronos.org/sycl" rel="noreferrer">SYCL</a> is a C++ abstraction layer for OpenCL. TensorFlow's <a href="https://www.codeplay.com/portal/tensorflow%E2%84%A2-for-opencl%E2%84%A2-using-sycl%E2%84%A2" rel="noreferrer">experimental support</a> for OpenCL uses SYCL, in conjunction with a SYCL-aware C... | tensorflow | 30 |
8,816 | 7,891,247 | numpy: reorder array by specified values | <p>I have a matrix:</p>
<pre><code>A = [ [1,2],
[3,4],
[5,6] ]
</code></pre>
<p>and a vector of values:</p>
<pre><code>V = [4,6,2]
</code></pre>
<p>I would like to reorder A by 2nd column, using values from V. The result should
be:</p>
<pre><code>A = [ [3,4],
[5,6],
[1,2] ] # 2nd columns' ... | <p>First, we need to find the indicies of the values in the second column of <code>A</code> that we'd need to match the order of <code>V</code>. In this case, that's <code>[1,2,0]</code>. Once we have those, we can just use numpy's "fancy" indexing to do the rest.</p>
<p>So, you might do something like this:</p>
<p... | python|numpy | 7 |
8,817 | 37,646,501 | How can I slice a dataframe by timestamp, when timestamp isn't classified as index? | <p>How can I split my pandas dataframe by using the timestamp on it?</p>
<p>I got the following prices when I call <code>df30m</code>:</p>
<pre><code> Timestamp Open High Low Close Volume
0 2016-05-01 19:30:00 449.80 450.13 449.80 449.90 74.1760
1 2016-05-01 20:00:00 449.90... | <p>You can use <code>loc</code> to index your data. Do you know if your timestamps at datetime.datetime formats or Pandas Timestamps?</p>
<pre><code>df30m.loc[(df30m.Timestamp <= d0) & (df30m.Timestamp >= d1)]
</code></pre>
<p>You can set the index to the Timestamp column and then index as follows:</p>
<p... | python|pandas|dataframe|split|timestamp | 8 |
8,818 | 37,857,254 | Does ComputeBandStats take nodata into account? | <p>I am trying to compute the stats for an image which is only partly covered by data. I would like to know if ComputeBandStats ignores the pixels with the same value as the files nodata.</p>
<p>Here is my code:</p>
<pre><code>inIMG = gdal.Open(infile)
# getting stats for the first 3 bands
# Using ComputeBandStats i... | <p>Setting the NoData value has no effect on the data itself. You can try it this way:</p>
<pre><code># First image, all valid data
data = numpy.random.randint(1,10,(10,10))
driver = gdal.GetDriverByName('GTIFF')
ds = driver.Create("stats1.tif", 10, 10, 1, gdal.GDT_Byte)
ds.GetRasterBand(1).WriteArray(data)
print ds.G... | python|python-2.7|python-3.x|numpy|gdal | 1 |
8,819 | 37,714,241 | pandas: how to combine matrix with different index and columns? | <p>I am using python, pandas and numpy to read a few data.</p>
<p>I have two data frames:</p>
<p>Input 1- Cost matrix(it has the cost per season and region): index = regions and columns = seasons
Input 2- Binary matrix(value 1 when a month "a" belongs to a season "b": index=seasons, columns=months</p>
<p>The output ... | <p>I believe that there is a mistake in the relationship dataframe from your example, since you clearly state that it should be the relationship between <strong>season</strong> (and not region) and month, so I changed it accordingly.</p>
<pre><code>import pandas as pd
import numpy as np
regions = ['Region A', 'Region... | python|numpy|pandas | 0 |
8,820 | 37,716,383 | noob at MNIST and I do not know what to look for in the documentation | <p>I am getting errors like </p>
<p>from: can't read /var/mail/tensorflow.examples.tutorials.mnist</p>
<p>from: can't read /var/mail/<strong>future</strong></p>
<p>what am i doing wrong?</p> | <p>From the error messages, it sounds like you are trying to run a TensorFlow program by (i) typing commands into a <code>bash</code> (or other command) prompt, or (ii) running it using a command-line interpreter (e.g. by running <code>source mnist.py</code>).</p>
<p>To run a TensorFlow Python program, e.g. <code>tens... | tensorflow | 0 |
8,821 | 37,890,373 | Python reshape array | <p>I have a very unique error I feel. I am working with an array 'A' of shape</p>
<pre><code>>>> A.shape
(1L, 1823L, 24L)
</code></pre>
<p>I am trying to get rid of first dimension as it is empty. So, I do something as:</p>
<pre><code>>>> z1 = A[0,:,:]
>>> z1.shape
(1253L,)
>>> z1... | <p>You can use <code>np.reshape()</code> for this.</p>
<p>Example <a href="http://docs.scipy.org/doc/numpy-1.10.4/reference/generated/numpy.reshape.html" rel="nofollow">from the docs</a>:</p>
<pre><code>>>> a = np.arange(6).reshape((3, 2))
>>> a
array([[0, 1],
[2, 3],
[4, 5]])
</code><... | python|numpy | 0 |
8,822 | 31,238,079 | How to split Test and Train data such that there is garenteed at least one of each Class in each | <p>I have some fairly unbalanced data I am trying to classify.
However, it is classifying fairly well.</p>
<p>To evaluate exactly how well, I must split the data into training and test subsets.</p>
<p>Right now I am doing that by the very simple measure of:</p>
<pre><code>import numpy as np
corpus = pandas.DataFrame... | <p>The following meets your 3 conditions for partitioning the data into test and training:</p>
<pre><code>#get rid of items with fewer than 2 occurrences.
corpus=corpus[corpus.groupby('label').label.transform(len)>1]
from sklearn.cross_validation import StratifiedShuffleSplit
sss=StratifiedShuffleSplit(corpus['lab... | python|pandas|machine-learning|scikit-learn|classification | 3 |
8,823 | 64,408,663 | Printing Coordinates to a csv File | <p>I would like to extract coordinates to a .csv file with the brackets and comma delimiter format (x,y).</p>
<p>I have a 4x4 matrix written as a list (network1) and need to identify the coordinates where a 1 occurs to then export these coordinates to a .csv file.</p>
<p>The code below was suggested by another user whi... | <p>I have seen your problem. Now fix this issue..</p>
<pre><code>df.to_csv(quotechar='"')
</code></pre>
<p>bydefault <code>quotechar</code> is string. Think about it.</p>
<p>So try this like...</p>
<pre><code>import numpy as np
import pandas as pd
network1 = [0,1,0,0,0,0,1,0,0,0,1,1,0,0,1,1]
network1_matri... | python|pandas|numpy|coordinates|export-to-csv | 1 |
8,824 | 64,328,617 | Python Pandas Replace Values with NAN from Tuple | <p>Got the Following Dataframe:</p>
<pre><code> A B
Temp1 1
Temp2 2
NaN NaN
NaN 4
</code></pre>
<p>Since the A nad B are correlated, I am able to create new column where I have calculated the nan value of A and B and form a tuple:</p>
<pre><code> A B C
Temp1 1 (1,Temp1)
Temp2 2 (2, T... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Series.fillna</code></a> with select values in tuple by indexing with <code>str</code>, last remove <code>C</code> column:</p>
<pre><code>#if values are not in tuples
#df.C = df.C.str.s... | python|pandas|tuples|nan|fillna | 1 |
8,825 | 64,464,585 | Pandas Python How to handle question mark that appeared in dataframe | <p>I have these question marks that appeared in my data frame just next to numbers and I dont know how to erase or or replace them. I dont want to drop the whole row since it may result in inaccurate results.
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snipp... | <p>I agree with the comments above that you should look into how you imported the data. But here is the answer to your question of how to remove the non numeric characters:</p>
<p>This will remove the non numeric characters</p>
<pre><code>df['Value'] = df['Value'].str.extract('(\d+)')
</code></pre>
<p>Then if you wish... | pandas | 1 |
8,826 | 47,664,026 | How to read arrays to form a matrix from file using numpy | <p>I have a file with data as:
2 arrays in each row. Total= 10,000 rows.</p>
<pre><code>[1,2,3,4,5][2,4,6,8,10]
[3,6,9,12,24][6,12,18,24,48]
....]
</code></pre>
<p>I am planning to give this input to Linear Regression in the fit command.
I am having issue how to construct a matrix with entries.</p>
<p>I am looking a... | <p>Solution using pandas</p>
<pre><code>import pandas as pd
df = pd.read_csv('input.txt', delimiter="\]\[", header=None, engine='python')
df[0] = (df[0] + ']')
df[1] = ('[' + df[1])
x = df[0].tolist()
y = df[1].tolist()
</code></pre> | python|numpy | 0 |
8,827 | 47,735,836 | How to manipulate numpy arrays in this way? | <p>I have a (28,28) array <code>a</code>. And I want to obtain a (28,28,3) array <code>b</code> s.t. <code>b[i][j][0] = b[i][j][1] = b[i][j][2] = a[i][j]</code>.</p>
<p>Is there any numpy shortcut to do this without tedious for loops?</p> | <pre><code>>>> import numpy as np
>>> a = np.zeros((28,28))
>>> b = np.dstack((a,a,a))
>>> a.shape
(28, 28)
>>> b.shape
(28, 28, 3)
</code></pre>
<p>Example:</p>
<pre><code>>>> a = np.array([[1,2],[3,4]])
>>> b = np.dstack((a,a,a))
>>> a
array([[... | python|numpy | 1 |
8,828 | 47,985,787 | How to use numpy fillna() with numpy.where() for a column in a pandas DataFrame? | <p>Here is an example pandas DataFrame:</p>
<pre><code>import pandas as pd
import numpy as np
dict1 = {'file': ['filename2', 'filename2', 'filename3', 'filename4',
'filename4', 'filename3'], 'amount': [3, 4, 5, 1, 2, 1],
'front': [21889611, 36357723, 196312, 11, 42, 1992],
'back':[219738... | <p><code>fillna</code> is base on index </p>
<pre><code>df['New']=np.where(df1['type']=='B', df1['front'], df1['front'] + df1['back'])
df
Out[125]:
amount back file front type end New
0 3 21973805 filename2 21889611 A NaN 43863416
1 4 36403870 filename2 363577... | python|pandas|numpy|dataframe|fillna | 3 |
8,829 | 58,633,364 | Max pool a single image in tensorflow using "tf.nn.avg_pool" | <p>I want to apply "tf.nn.max_pool()" on a single image but I get a result with dimension that is totally different than the input:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import numpy as np
ifmaps_1 = tf.Variable(tf.random_uniform( shape=[ 7, 7, 3], minval=0, maxval=3, dtype=tf.in... | <p>Your input is <code>(7,7,3)</code>, kernel size is <code>(3,3)</code> and stride is <code>(2,2)</code>. So if you do not want any paddings, (state in your comment), you should use <code>padding="VALID"</code>, that will return a <code>(3,3)</code> tensor as output. If you use <code>padding="SAME"</code>, it will ret... | python|numpy|tensorflow|conv-neural-network|max-pooling | 1 |
8,830 | 70,325,648 | NumPy genfromtxt OSError: file not found | <p>I'm learning the NumPy library and when I try to read something from the file I get this error:</p>
<pre><code>Traceback (most recent call last):
File "c:\Users\user\Desktop\folder\Reading_from_file.py", line 3, in <module>
example = genfromtxt("example.txt", delimiter=',')
File &qu... | <p>You probably aren't running the script from the same folder that <code>example.txt</code> is in. <code>example.txt</code> doesn't need to be in the same directory as the script itself, it needs to be in the same directory as you are when you're running the script.</p> | python|numpy|file-not-found | 1 |
8,831 | 70,191,014 | solve_ivp - TypeError: 'numpy.ndarray' object is not callable | <p>I'm working on the code below for a class and no matter what I try I can't figure out how to fix it so I can move on.</p>
<pre><code>def eqs(t, x):
return np.array([[(1 - np.multiply((1 - f(z(t), z_thresh)), (1 - f(x(1), y_thresh)))) - x(0)],
[(1 - np.multiply((1 - f(z(t), z_thres... | <p>the traceback tells you that the problem is in</p>
<pre><code>np.array([[(1 - np.multiply((1 - f(z(t), z_thresh)), (1 - f(x(1), y_thresh)))) - x(0)], [(1 - np.multiply((1 - f(z(t), z_thresh)),(1 - f(x(0), x_thresh)))) - x(1)]]
</code></pre>
<p>So we look for apparent function calls, <code>fn(...)</code>. <code>np.m... | python|numpy|scipy | 0 |
8,832 | 56,371,996 | Conversion of Daily pandas dataframe to minute frequency | <p>I have a dataframe as defined below (df) with daily frequency and I would like to convert this to minute frequency, starting at 8:30 and ending at 16:00.</p>
<pre><code>import pandas as pd
dict = [
{'ticker':'jpm','date': '2016-11-28','returns': '0.2'},
{ 'ticker':'ge','date': '2016-11-28','returns': '0.2'}... | <p>I believe you need reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>DataFrame.unstack</code></a> for <code>DatetimeIndex</code>, then set minute frequency by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/... | python|pandas|dataframe | 2 |
8,833 | 56,412,030 | Python- Looping through pandas Groupby object | <p>Here is a sample row that I have in my dataframe: </p>
<pre><code>{
"sessionId" : "454ec8b8-7f00-40b2-901c-724c5d9f5a91",
"useCaseId" : "3652b5d7-55b8-4bee-82b6-ab32d5543352",
"timestamp" : "1559403699899",
"endFlow" : "true"
}
</code></pre>
<p>I do groupby by 'sessionId', which will give me a group like this... | <p>You may try this: (<em>I assume <code>df.endFlow</code> contains string of <code>'true'</code> and <code>'false'</code>. If it contains boolean <code>True</code> and <code>False</code>, you just take out the <code>replace</code> command</em>.)</p>
<pre><code>df.endFlow.replace({'true': True, 'false': False}).groupb... | python|pandas|dataframe | 2 |
8,834 | 55,591,077 | How to reshape this array the way I need? | <p>I'm looking to reshape an array of three 2x2 matrices, that is of shape (3,2,2) i.e.</p>
<pre><code>a = np.array([[[a1,a2],[a3,a4]],
[[b1,b2],[b3,b4]],
[[c1,c2],[c3,c4]]])
</code></pre>
<p>to this array of shape (2,2,3):</p>
<pre><code>[[[a1,b1,c1],[a2,b2,c2]],
[[a3,b3,c3],[a4,b4,c4]]])... | <p>We simply need to permute axes. Two ways to do so.</p>
<p>Use <code>np.transpose</code> -</p>
<pre><code>a.transpose(1,2,0) # a is input array
# or np.transpose(a,(1,2,0))
</code></pre>
<p>We can also use <code>np.moveaxis</code> -</p>
<pre><code>np.moveaxis(a,0,2) # np.moveaxis(a, 0, -1)
</code></pre>
<p>Sa... | python|arrays|numpy|reshape | 2 |
8,835 | 55,669,882 | Python np.asarray does not return the true shape | <p>I spin a loop on two sub table of my original table.</p>
<p>When I start the loop, and that I check the shape, I get (1008,) while the shape must be (1008,168,252,3). Is there a problem in my loop?</p>
<pre><code>train_images2 = []
for i in range(len(train_2)):
im = process_image(Image.open(train_2['Path'][i]))
... | <p>The problem is that your <strong><code>process_image()</code></strong> function is returning a scalar instead of the processed image (i.e. a 3D array of shape <code>(168,252,3)</code>). So, the variable <code>im</code> is just a scalar. Because of this, you get the array <code>train_images2</code> to be 1D array. Be... | python|loops|numpy|multidimensional-array|numpy-ndarray | 0 |
8,836 | 64,838,581 | Why I'm getting zero accuracy in Keras binary classification model? | <p>I have a Keras Sequential model taking inputs from csv files. When I run the model, <strong>its accuracy remains zero</strong> even after 20 epochs.</p>
<p>I have gone through these two stackoverflow threads (<a href="https://stackoverflow.com/questions/41819457/zero-accuracy-training-a-neural-network-in-keras/42661... | <p>The problem is here:</p>
<pre><code>model = tf.keras.Sequential([
layers.Dense(256,activation='elu'),
layers.Dense(128,activation='elu'),
layers.Dense(64,activation='elu'),
layers.Dense(1,activation='sigmoid')
])
model.compile(optimizer='adam',
#Here is the problem
... | python|tensorflow|machine-learning|keras|deep-learning | 1 |
8,837 | 64,975,363 | Pandas when several columns meet a condition, assign value | <p>The use case is the following: If in a Pandas Dataframe, several columns are greater than zero, I want to create a new column with value <code>1</code>, if the same columns are negative, I wish to set <code>-1</code>, otherwise I wish to set <code>0</code>.</p>
<p>Now, I want to extend the previous. Let's say I want... | <p>You could use the <code>loc()</code> method withing padas <code>DataFrame</code> object. Like this:</p>
<pre class="lang-py prettyprint-override"><code>input_df.loc[conditions[0], dst_col] = choices[0]
input_df.loc[conditions[1], dst_col] = choices[1]
</code></pre>
<p>This will basically filter <code>input_df</code>... | python|pandas|numpy|dataframe | 0 |
8,838 | 64,678,636 | Sort dataframe by multiple columns while ignoring case | <p>I want to sort a dataframe by multiple columns like this:</p>
<pre><code>df.sort_values( by=[ 'A', 'B', 'C', 'D', 'E' ], inplace=True )
</code></pre>
<p>However i found out that python first sorts the uppercase values and then the lowercase.</p>
<p>I tried this:</p>
<pre><code>df.sort_values( by=[ 'A', 'B', 'C', 'D'... | <p>If check docs - <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</code></a> for correct working need upgrade pandas higher like <code>pandas 1.1.0</code>:</p>
<blockquote>
<p><strong>key</strong> - callable, op... | python|pandas|dataframe|sorting|case-insensitive | 3 |
8,839 | 64,902,795 | Creating a pandas column based on conditions from another column | <p>I have this 'Club' column in my pandas df that contains the names of English Premier League clubs but the naming of the club is not suited for what I want to achieve. I tried writing a function with conditional statements to populate another column with the names of the club in the format I want. I have tried applyi... | <p>I think this can be easier achieved through panda's replace().</p>
<p>Simply create a dictionary of your old values to new values:</p>
<p>eg:</p>
<pre><code>dict_replace = {
'Tottenham Hotspur TOT':'Tottenham',
'Liverpool LIV':'Liverpool',
'Southampton SOU':'Southampton',
'Chelsea CHE':'Chelsea'
... | python|pandas|dataframe|data-science|data-analysis | 1 |
8,840 | 64,683,408 | Find distance between all pairs of pixels in an image | <h3>Question</h3>
<p>I have a <code>numpy.array</code> of shape <code>(H, W)</code>, storing pixel intensities of an image. I want to generate a new array of shape <code>(H, W, H, W)</code>, which stores the Euclidean distance between each pair of pixels in the image (the "spatial" distance between the pixels... | <p>We can setup open grids with <code>1D</code> ranged arrays using <code>np.ogrid</code>, which could be operated upon in the same iterator notation for a vectorized solution and this will leverage <a href="https://numpy.org/doc/stable/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code><... | python|performance|numpy|linear-algebra | 2 |
8,841 | 39,552,773 | Apply Numpy function over entire Dataframe | <p>I am applying this function over a dataframe <code>df1</code> such as the following:</p>
<pre><code> AA AB AC AD
2005-01-02 23:55:00 "EQUITY" "EQUITY" "EQUITY" "EQUITY"
2005-01-03 00:00:00 32.32 19.5299 32.32 31.04... | <p>You need to do it the following way :</p>
<pre><code>def func(row):
return row/np.sum(row)
df2 = pd.concat([df[:1], df[1:].apply(func, axis=1)], axis=0)
</code></pre>
<p>It has 2 steps :</p>
<ol>
<li><code>df[:1]</code> extracts the first row, which contains strings, while <code>df[1:]</code> represents the r... | python|pandas|numpy|dataframe | 2 |
8,842 | 39,713,678 | Assigning indicators based on observation quantile | <p>I am working with a pandas DataFrame. I would like to assign a column indicator variable to 1 when a particular condition is met. I compute quantiles for particular groups. If the value is outside the quantile, I want to assign the column indicator variable to 1. For example, the following code prints the quantiles ... | <p>you want to use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="nofollow noreferrer"><code>transform</code></a> after your <code>groupby</code> to get an equivalently sized array. <code>gt</code> is greater than. <code>mul</code> is multiply. I multiply by <code>1</code> to ... | python|pandas|numpy|dataframe | 2 |
8,843 | 39,560,099 | Cannot combine bar and line plot using pandas plot() function | <p>I am plotting one column of a pandas dataframe as line plot, using plot() :</p>
<pre><code>df.iloc[:,1].plot()
</code></pre>
<p>and get the desired result:</p>
<p><a href="https://i.stack.imgur.com/6FFdq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6FFdq.png" alt="enter image description here"></a></... | <pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
</code></pre>
<p>some data</p>
<pre><code>df = pd.DataFrame(np.random.randn(5,2))
print (df)
0 1
0 0.008177 -0.121644
1 0.643535 -0.070786
2 -0.104024 0.872997
3 -0.033835 0.067264
4 -0.576762 0.571293
</code></pr... | python|pandas|matplotlib|plot | 8 |
8,844 | 43,925,624 | fastest method to dump numpy array into string | <p>I need to organized a data file with chunks of named data. Data is NUMPY arrays. But I don't want to use numpy.save or numpy.savez function, because in some cases, data have to be sent on a server over a pipe or other interface. So I want to dump numpy array into memory, zip it, and then, send it into a server.</p>
... | <p>You should definitely use <code>numpy.save</code>, you can still do it in-memory:</p>
<pre><code>>>> import io
>>> import numpy as np
>>> import zlib
>>> f = io.BytesIO()
>>> arr = np.random.rand(100, 100)
>>> np.save(f, arr)
>>> compressed = zlib.compre... | python|arrays|numpy|pickle | 12 |
8,845 | 69,438,417 | torch.cuda.is_available() is False only in Jupyter Lab/Notebook | <p>I tried to install CUDA on my computer. After doing so I checked in my Anaconda Prompt and is appeared to work out fine.</p>
<p><a href="https://i.stack.imgur.com/NPoaL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NPoaL.png" alt="enter image description here" /></a></p>
<p>However, when I start... | <p>Seems to be a problem with similar causes:</p>
<p><a href="https://stackoverflow.com/questions/62939415/not-able-to-import-tensorflow-in-jupyter-notebook/62939942#62939942">Not able to import Tensorflow in Jupyter Notebook</a></p>
<p>You are probably using other environment than the one you are using outside jupyter... | python|jupyter-notebook|pytorch | 1 |
8,846 | 69,574,128 | Changing the Structure of a Dataframe in Python | <p>I need help to change the structure to a pandas dataframe with many columns like the example:</p>
<p>original dataframe:</p>
<pre><code>| xx | yy | zz | a | b | c | k |
|:---|:---|:---|:--|:--|:--|:--|
| x1 | y1 | z1 | 0 | 2 | 1 | 3 |
| x2 | y2 | z2 | 1 | 0 | 2 | 0 |
</code></pre>
<p>I need just the first 3 columns ... | <pre><code>df1 = df.set_index(['xx','yy','zz']).stack()
df1.reset_index()
</code></pre>
<p><a href="https://i.stack.imgur.com/Mxok6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mxok6.png" alt="enter image description here" /></a></p> | python-3.x|pandas|dataframe | 1 |
8,847 | 69,434,334 | arranging data by date (month/day format) | <p>After I append 4 different dataframes in:</p>
<pre><code>list_1 = [ ]
</code></pre>
<p>I have the following data stored in list_1:</p>
<pre><code>| date | 16/17 |
| -------- | ------|
| 2016-12-29 | 50 |
| 2016-12-30 | 52 |
| 2017-01-01 | 53 |
| 2017-01-02 | 51 |
[4 rows x 1 columns],
... | <p>You can use <code>sort=False</code> in <code>groupby</code> and create new column for subtract by first value of <code>DatetimeIndex</code> and use it for sorting:</p>
<pre><code>def f(x):
x.index = pd.to_datetime(x.index)
return x.assign(new = x.index - x.index.min())
L = [x.pipe(f) for x in list_1]
df = ... | python|pandas|sorting|time-series|pandas-groupby | 0 |
8,848 | 69,454,833 | Pandas: to.datetime() quesiton | <p>I have Date/Time in the following format:</p>
<p>10/01/21 04:49:43.75<br />
MM/DD/YY HH/MM/SS.ms</p>
<p>I am trying to convert this from being an object to a datetime. I tried the following code but i am getting an error that it does not match the format. Any ideas?</p>
<pre><code>df['Date/Time'] = pd.to_datetime(df... | <p>you can try letting pandas infer the datetime format with:</p>
<pre><code>pd.to_datetime(df['Date/Time'], infer_datetime_format=True)
</code></pre> | python|pandas|dataframe | 0 |
8,849 | 69,431,747 | Replace an item in a column with a similar item from that column that has repeated the most | <p>I have a list of job titles, the no of unique job titles are around 24,000. Most of the job titles are very similar.</p>
<pre><code>For example:
Software Developer, Software engineer, software engineering, software engineer 2, senior software engineer, junior software engineer,....
</code></pre>
<p>I want to find t... | <p>Here's another try:</p>
<p>There are 5 steps in this solution:</p>
<ol>
<li><p>Use <code>pd.Series.value_counts().reset_index()</code> to get only unique titles in descending order of frequency.</p>
</li>
<li><p>Calculate the distances between these unique <code>titles</code> using the Levenshtein distance measure</... | python|pandas|string|nlp|cosine-similarity | 1 |
8,850 | 69,412,036 | Python OpenCV Duplicate a transparent shape in the same image | <p>I have an image of a circle, refer to the image attached below. I already retrieved the transparent circle and want to paste that circle back to the image to make some overlapped circles.</p>
<p>Below is my code but it led to the problem A, it's like a (transparent) hole in the image. I need to have circles on norma... | <p>If you already have a transparent black circle, then in Python/OpenCV here is one way to do that.</p>
<pre><code> - Read the transparent image unchanged
- Extract the bgr channels and the alpha channel
- Create a colored image of the background color and size desired
- Create similar sized white and black images
... | numpy|opencv|transparent|alpha | 1 |
8,851 | 41,227,373 | python pandas get ride of plural "s" in words to prepare for word count | <p>I have the following python pandas dataframe: </p>
<pre><code>Question_ID | Customer_ID | Answer
1 234 The team worked very hard ...
2 234 All the teams have been working together ...
</code></pre>
<p>I am going to use my code to count words in the answer column. But bef... | <p>You need to use a tokenizer (for breaking a sentence into words) and lemmmatizer (for standardizing word forms), both provided by the natural language toolkit <code>nltk</code>:</p>
<pre><code>import nltk
wnl = nltk.WordNetLemmatizer()
[wnl.lemmatize(word) for word in nltk.wordpunct_tokenize(sentence)]
# ['All', 't... | python|pandas|word-count | 7 |
8,852 | 53,818,775 | pandas, comparison within lambda | <p>I have a function which returns the names of the pandas dataframe columns which have a number of unique values <= 100:</p>
<pre><code>cols_unique = list(df[cols].loc[:, df[cols].apply(lambda x: x.nunique()) <= 100])
</code></pre>
<p>I would like to change this to return the column names in which the number o... | <p>IIUC you might try:</p>
<pre><code>cols_unique = list(df[cols].loc[:, df[cols].apply(lambda x: x.nunique() <= len(df) / 2)])
</code></pre>
<p>If you're open to an alternative that doesn't use a <code>lambda</code> function, you could try:</p>
<pre><code> list(cols[df[cols].nunique().le(len(df) // 2)])
</code><... | python|pandas|lambda | 2 |
8,853 | 65,955,827 | Tensorflow target column always returns 1 | <p>I'm working on a classification problem with Tensorflow and I'm new to this. I want to see two targets (1 and 0) after all. I'm asking because I don't know, is it normal for the whole target column to be 1 as below? Thank you.</p>
<pre><code>df['target'] = np.where(df['Class']== 2, 0, 1)
df = df.drop(columns=['Clas... | <p>Just change the last parameter to the array you are making the comparisons on.</p>
<p>This will replace the values of <code>2</code> with <code>1</code> in <code>df["Class"]</code></p>
<pre><code>df['target'] = np.where(df['Class']== 2, 1, df['Class'])
</code></pre> | python|pandas | 0 |
8,854 | 66,124,497 | How to use pandas or equivalent python library to parse a csv file | <p>I have a csv file data.csv with below file content(| delimited)</p>
<pre><code>A|B|X|Y|Z
S|T|U|V|W|X
</code></pre>
<p>I want to parse this file to print the data in below format(1st two columns constant and third column split by | and generate new row</p>
<pre><code>A|B|X
A|B|Y
A|B|Z
S|T|U
S|T|V
S|T|W
S|T|X
</code><... | <p>Try with <code>read_csv</code> and <code>melt</code>:</p>
<pre><code>df = pd.read_csv('data.csv', sep='|', header=None).melt([0,1])
</code></pre>
<p>Output:</p>
<p>print(df.melt([0,1]))</p>
<pre><code> 0 1 variable value
0 1338980 2528742011 2 B00HFPOXM4:0
1 1338981 2528742012... | python|pandas|csv | 0 |
8,855 | 66,164,305 | How to create histograms in pure Python? | <p>I know you can just use <code>numpy.histogram()</code>, and that will create the histogram for a respective image. What I don't understand is, how to create histograms without using that function.</p>
<p>Everytime I try to use sample code, it has issues with packages especially OpenCV.</p>
<p>Is there anyway to crea... | <p>You'd need to implement the histogram calculation using lists, dictionaries or any other standard Python data structure, if you explicitly don't want to have NumPy as some kind of import. For <a href="https://en.wikipedia.org/wiki/Image_histogram" rel="nofollow noreferrer">image histograms</a>, you basically need to... | numpy|opencv|image-processing|histogram|python-imageio | 1 |
8,856 | 52,620,354 | Creating a new Sheet instead of using existing sheet | <p>I am copying data from one workbook to another workbook. The problem is pandas is creating a new sheet in the with the name 'sheet_name1' instead of using 'sheet_name'. I am using openpyxl as the Pandas Engine. Can you help with the reason?</p>
<pre><code> input_file = "C:\Automations\FastenersAudit\ClassfiedExp... | <p>Slightly Edited Version:
Thank you so much for your solution. It worked perfectly with a slight modification.</p>
<pre><code> writer.sheets = {ws.title: ws for ws in writer.book.worksheets}
for sheetname in writer.sheets:
if sheetname == 'Attribute Analysis':
output_df.to_excel(writer, s... | python|python-3.x|pandas|openpyxl | 1 |
8,857 | 46,246,212 | Calculate into new Columns | <p>A dataframe columns looks like this:</p>
<pre><code>VALUE
1
2
3
4
5
...
40
</code></pre>
<p>i want to produce two new columns for eah value like this:</p>
<pre><code> df['VALUE1'] = math.cos(df['VALUE'] * 2 * math.pi / 48)
df['VALUE2'] = math.sin(df['VALUE'] * 2 * math.pi / 48)
</code></pre>
<p>... | <p><code>math.sin</code> and <code>math.cos</code> don't accept series. Use <code>numpy</code>, vector methods are fast.</p>
<pre><code>In [511]: df = pd.DataFrame({'VALUE': range(1, 41)})
In [512]: df['VALUE1'] = np.cos(df['VALUE'] * 2 * np.pi /48)
In [513]: df['VALUE2'] = np.sin(df['VALUE'] * 2 * np.pi /48)
In [5... | python|pandas|dataframe | 0 |
8,858 | 46,427,606 | Reload tensorflow model in Golang app server | <p>I have a Golang app server wherein I keep reloading a saved tensorflow model every 15 minutes. Every api call that uses the tensorflow model, takes a read mutex lock and whenever I reload the model, I take a write lock. Functionality wise, this works fine but during the model load, my API response time increases as ... | <p>Presumably destroyTFModel takes a long time. You could try this:</p>
<pre><code>old := TensorModel
ModelLoadMutex.Lock()
TensorModel = new
ModelLoadMutex.Unlock()
go destroyTFModel(old)
</code></pre>
<p>So destroy after assign and/or try destroying on another goroutine if it needs to clean up resources and someh... | go|tensorflow | 0 |
8,859 | 58,424,060 | Performing a variable number of array dot products in python? | <p>I'm looking for a quick way to dot and array with itself a variable number of times.</p>
<p>In Mathlab it would look like: </p>
<p>A = some array elements</p>
<p>A^d where d is some scalar. </p>
<p>Hence A^2 is = A*A </p>
<p>However in Python i'm having trouble finding something that does the same thing</p>
<p... | <p>This is called a <a href="http://mathworld.wolfram.com/MatrixPower.html" rel="nofollow noreferrer">"matrix power"</a>, and it is computed by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.matrix_power.html" rel="nofollow noreferrer"><code>numpy.linalg.matrix_power</code></a>.</p> | python|numpy|dot | 0 |
8,860 | 58,290,221 | Compare row value for duplication in adjacent columns in a loop to clean data in pandas | <h1>Summary</h1>
<pre><code>0 101 2017/11 -9999.0 -7.60 -4.00 -9999.0 -9999.0 -4.00 -0.22 1.76 4.64 6.98 8.96 12.56 15.98 19.58 22.46 25.34 28.40
1 101 2017/11 -9999.0 -7.78 -4.36 -9999.0 -9999.0 -4.36 -0.22 1.76 4.64 6.80 8.78 12.56 15.98 19.58 22.46 25... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.diff.html" rel="nofollow noreferrer"><code>pandas.diff()</code></a> is indeed the right function for you. However you need to check across the columns <em>in both directions</em> if values are equal or not. This code sets all values... | python|pandas|csv | 2 |
8,861 | 69,044,145 | Convert quarterly dataframe to monthly and fill missing values for each ID | <p>I have a dataframe that, for each ID, contains a timestamp and a value. The timestamp is for a given quarter:</p>
<pre><code>import pandas as pd
a = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3],
'date': ['2002Q1', '2002Q2', '2002Q3', '2002Q4', '2003Q1', '2002Q2', '2002Q3', '2002Q4', '2003Q... | <p>I imagine you can <code>groupby</code> and <code>resample</code>:</p>
<pre><code>a['date'] = pd.to_datetime(a['date'])
(a.set_index('date')
.groupby('id')
['value']
.resample('MS')
.first().ffill()
.reset_index()
)
</code></pre>
<p>output:</p>
<pre><code> date id value
0 2002-01-01 1.0 1.0
1... | python|pandas|dataframe | 2 |
8,862 | 68,940,728 | Syntax Error when calling the name of a model's layer in captum | <p>I'm trying to use the gradCAM feature of captum for PyTorch. Previously, I asked the question of how to find the name of layers in pyTorch (which is done using model.named_modules()). However, since getting the names of the modules (my model name is 'model') I have tried to use it with LayerGradCam from captum and a... | <p>Array or list indexing is done using <code>[]</code> syntax, not <code>.</code>.</p>
<pre><code>model.dl.backbone.layer4[2]conv3
</code></pre> | python|pytorch|syntax-error | 1 |
8,863 | 60,988,820 | read row and convert float to integer in pandas | <p>I have a dataframe with multiple rows and columns. One of my columns (lets call that column A) has rows that contain mix of strings, strings and integers (i.e RSE1023), integers only and floats only. I want to find a way to convert the rows of the column A that are floats to integers. Probably with something that c... | <p>You could try something like:</p>
<pre><code>df['A']=df['A'].apply(lambda r:int(r) if isinstance(r,float) else r)
</code></pre> | python|pandas|dataframe | 1 |
8,864 | 71,501,334 | 'Image data of dtype object cannot be converted to float' on imshow() | <p>I'm trying to show images from my dataset. But on imshow() function I have this error.
'Image data of dtype object cannot be converted to float'</p>
<p>This is my code:</p>
<pre><code>val_ds = tf.keras.utils.image_dataset_from_directory(
'/media/Tesi/',
validation_split=0.2,
subset="validation",
se... | <p><code>image_dataset_from_directory</code> function uses <code>cv2.imread()</code> as function to read images from your directory. Though, <code>cv2.imread()</code> returns <code>None</code> if file weren't found. None is type <code>object</code>. So, check your path</p> | python|tensorflow|matplotlib|machine-learning|google-colaboratory | 2 |
8,865 | 71,478,786 | Interpolate pandas dataframe around certain value | <p>I have a dataset showing water levels over time and I want to plot all the data above a certain value (-0.75m in the example) in green and all the data below this value in orange. The problem I am facing is that whenever my data crosses over my value, the plotted line stops at that value and there are multiple gaps ... | <p>First, if you have to iterate over data, using <code>NumPy</code> is faster than using <code>Pandas</code>.<br>
See: <a href="https://towardsdatascience.com/how-to-make-your-pandas-loop-71-803-times-faster-805030df4f06" rel="nofollow noreferrer">https://towardsdatascience.com/how-to-make-your-pandas-loop-71-803-time... | python|pandas|dataframe|plot|interpolation | 0 |
8,866 | 42,346,898 | Loading one dimensional data into a Dense layer in a sequential Keras model | <p>I have the results of a trained model, ending in a Flatten layer in numpy output files.
I try to load them and use them as inputs of a Dense layer.</p>
<pre><code>train_data = np.load(open('bottleneck_flat_features_train.npy'))
train_labels = np.array([0] * (nb_train_samples / 2) + [1] * (nb_train_samples / 2))
#
v... | <p>I have found my problem - I did not define the lables correctly. I have switched the model compilation to a sparse categorical crossentropy mode.</p>
<p>my current code is </p>
<pre><code>def train_top_model():
train_data = np.load(open('bottleneck_flat_features_train.npy'))
train_labels = np.array([0] * (... | python|numpy|keras | 1 |
8,867 | 69,770,425 | Querying data frames in Python/Pandas when columns are optional or missing | <p>I'm developing a script in Python/Pandas to compare the contents of two dataframes.</p>
<p>Both dataframes contain any combination of columns from a fixed list, for instance:</p>
<pre><code>"Case Name", "MAC", "Machine Name", "OS", "Exec Time", "RSS"
</code... | <p>I think you might want to try a simple merge, and depending on whether <code>MAC</code> is present, add it to the merge fields, no?</p>
<pre class="lang-py prettyprint-override"><code>merge_cols = ["Case Name"]
if "MAC" in df1.columns:
merge_cols.append("MAC")
print(merge_cols)
res... | python|pandas|dataframe | 1 |
8,868 | 72,339,990 | week of the year aggregation using python (week starts from 01 01 YYYY) | <p>I search in previous questions, and it does not resolve what i am searching, please can u help me</p>
<p>I have a dataset from</p>
<pre><code> Date T2M Y T F H G Week_Number
0 1981-01-01 11.08 17.35 6.94 0.00 5.37 4.63 1
1 1981-01-02 10.82 16.41 7.... | <p>If you want your week numbers to start from the 1st of January, irrespective of the day of week, simply get the day of year, subtract 1 and compute the integer division by 7:</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'])
df['week_number'] = df['Date'].dt.dayofyear.sub(1).floordiv(7).add(1)
</code></pre>
<p>... | python|pandas|datetime|week-number | 1 |
8,869 | 72,198,284 | Append rows to a dataframe efficiently | <p>I have a dataframe that looks like this</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Timestamp': ['1642847484', '1642847484', '1642847484', '1642847484', '1642847487', '1642847487','1642847487','1642847487','1642847487','1642847487','1642847487','1642847487', '1642847489', '1642847489', '1642847489'],
... | <p>I think <code>itterows</code> here is not necessary, you can use:</p>
<pre><code>def f(x):
x['Timestamp'] = ...
....
return x
df1 = df.groupby('Timestamp').apply(f)
</code></pre>
<p>EDIT: Create counter <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas... | python|pandas|dataframe|append | 2 |
8,870 | 72,309,955 | Python's Numpy dot function returning incorrect value, why? | <p>Real simple, my code is:</p>
<pre><code>import numpy as np
a = np.array([0.4, 0.3])
b = np.array([-0.15, 0.2])
print(np.dot(a,b))
</code></pre>
<p>The dot product of this should be 0, and instead i get:</p>
<pre><code>3.3306690738754695e-18
</code></pre> | <p>Floating-point!</p>
<p>Floating-point (i.e. non-integer) arithmetic tends not to be 100% accurate.</p>
<p>See <a href="https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate">here</a> for more info.</p>
<p>Also, note that your result is very close to zero.</p> | python|numpy|dot-product | 2 |
8,871 | 50,441,524 | RunMetadata in eager mode | <p>Does eager mode support <code>tf.profiler</code> in r1.8? Since it no longer has the session object, is there any way to pass in a <code>tf.RunMetadata()</code> into the execution? I saw the profiler constructor checks for eager mode; but without <code>RunMetadata</code> it doesn't work. Thanks!</p> | <pre><code>with context.eager_mode():
outfile = os.path.join(test.get_temp_dir(), 'dump')
opts = builder(
builder.time_and_memory()).with_file_output(outfile).build()
context.enable_run_metadata()
# run your model here #
profiler = model_analyzer.Profiler()
profiler.add_step(0, context.export_run_m... | tensorflow | -1 |
8,872 | 50,549,681 | Data type for gaussian Naive bayes classifivation using sklearn, how to clean data | <p>I'm trying to classify mobiles according to their features but when I apply the gaussian NB code through sklearn , I'm unable to do so because of the following error :
the code :</p>
<pre><code>clf = GaussianNB()
clf.fit(X_train,y_train)
GaussianNB()
accuracy = clf.score(X_test,y_test)
print(accuracy)
</code></pre... | <p>try the following:</p>
<pre><code>accuracy = clf.score(X_test.astype('float'),y_test.astype('float'))
</code></pre> | python|pandas|scikit-learn|classification | 1 |
8,873 | 50,441,794 | TypeError: unsupported operand type(s) for /: 'float' and 'csr_matrix' | <p>I want to write a sigmoid function:</p>
<pre><code>def fn(w, x):
return 1.0 / (np.expm1(-w.dot(x))+0.0)
</code></pre>
<p>Because -w.dot(x) is a sparse matrix, I used np.expm1() instead of np.exp(), but how to divide a float by a csr_matrix? Thanks!</p> | <pre><code>from spicy import sparse
res2 = np.expm1(-w.dot(x))
res1 = sparse.csr_matrix(np.ones(res2.shape()))
return res1/res2
</code></pre> | python|numpy|python-3.5|array-broadcasting | 0 |
8,874 | 50,565,880 | Quantization of mobilenet-ssd | <p>I wanted to quantize (change all the floats into INT8) a ssd-mobilenet model and then want to deploy it onto my raspberry-pi. So far, I have not yet found any thing which can help me with it. Any help would be highly appreciated.
I saw tensorflow-lite but it seems it only supports android and iOS.
Any library/fram... | <p>Tensorflow Lite now has support for the Raspberry Pi via Makefiles. <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/lite/build_rpi_lib.sh" rel="nofollow noreferrer">Here's the shell script</a>. Regarding Mobilenet-SSD, you can get details on how to use it with TensorFlow Lite in <a h... | tensorflow|raspberry-pi|deep-learning | 0 |
8,875 | 50,358,564 | computing the mean for python datetime | <p>I have a datetime attribute:</p>
<pre><code>d = {
'DOB': pd.Series([
datetime.datetime(2014, 7, 9),
datetime.datetime(2014, 7, 15),
np.datetime64('NaT')
], index=['a', 'b', 'c'])
}
df_test = pd.DataFrame(d)
</code></pre>
<p>I would like to compute the mean for that attribute. Runnin... | <p>You can take the mean of <code>Timedelta</code>. So find the minimum value and subtract it from the series to get a series of <code>Timedelta</code>. Then take the mean and add it back to the minimum.</p>
<pre><code>dob = df_test.DOB
m = dob.min()
(m + (dob - m).mean()).to_pydatetime()
datetime.datetime(2014, 7,... | python-3.x|pandas|datetime|mean|python-datetime | 10 |
8,876 | 50,305,206 | How To Normalize Array Between 1 and 10? | <p>I have a numpy array with the following integer numbers: </p>
<pre><code>[10 30 16 18 24 18 30 30 21 7 15 14 24 27 14 16 30 12 18]
</code></pre>
<p>I want to normalize them to a range between 1 and 10. </p>
<p>I know that the general formula to normalize arrays is:</p>
<p><a href="https://i.stack.imgur.com/gztOl... | <p>Your range is actually 9 long: from 1 to 10. If you multiply the normalized array by 9 you get values from 0 to 9, which you need to shift back by 1:</p>
<pre><code>start = 1
end = 10
width = end - start
res = (arr - arr.min())/(arr.max() - arr.min()) * width + start
</code></pre>
<p>Note that the denominator here... | python|python-3.x|numpy | 7 |
8,877 | 50,319,837 | mapping similar text strings in between two pandas dataframes | <p>I have dataset named <code>data_feed</code> contains feedbacks given as:</p>
<pre><code>feedback
Fast Delivery. Always before time.Thanks
I have order brown shoe .And I got olive green shoe
Delivery guy is a decent nd friendly guy ... | <p>One strategy you could use is to analyze the feedback with <a href="https://en.wikipedia.org/wiki/Latent_Dirichlet_allocation" rel="nofollow noreferrer">LDA</a> to discover common topics. You could then use the topics to map like to like between the two tables.</p>
<p>LDA analyzes what is referred to as a 'corpus' ... | python-2.7|pandas|nlp|mapping|sentiment-analysis | 0 |
8,878 | 45,687,723 | JSON object inside Pandas DataFrame | <p>I have a JSON object inside a pandas dataframe column, which I want to pull apart and put into other columns. In the dataframe, the JSON object looks like a string containing an array of dictionaries. The array can be of variable length, including zero, or the column can even be null. I've written some code, show... | <p>First, a general piece of advice about pandas. <strong>If you find yourself iterating over the rows of a dataframe, you are most likely doing it wrong.</strong></p>
<p>With this in mind, we can re-write your current procedure using pandas 'apply' method (this will likely speed it up to begin with, as it means far f... | python|json|pandas|dataframe | 4 |
8,879 | 62,711,102 | Is there an inbuilt method in python(pandas) which can simulate a single day from multiple days | <p>I have a time series data for solar radiation with 15 min time step values (from 1st June till 30th June) for a month. My aim is to simulate one single day from all the 30 days by taking an average of each time instants. For example, initially i have 30 different values at 11am , 11.15am, 11.45am and so on. I want t... | <p>You can extract minutes to separate column an group by it:</p>
<pre><code>data['Minutes15'] = data['Date'].apply(lambda x: int(x.minute/15) *15))
data.groupby('Minutes15').mean()
</code></pre>
<p>Where <em>Date</em> is your date column in datetime format</p> | python|pandas|time-series | 0 |
8,880 | 62,673,494 | pandas How to drop the whole row if any specific columns contains a specific values? | <p>I have a dataFrame like this:
<a href="https://i.stack.imgur.com/uPiBk.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I wonder how to drop the whole row if any specific columns contain a specific value?</p>
<p>For example, If columns Q1, Q2 or Q3 contain zero, delete the whole row. But if col... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> to filter with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>eq</code></a> and <a href="htt... | python|pandas | 1 |
8,881 | 54,654,772 | How to change read_csv handling of empty values | <p>When loading a header with missing values, pandas' read_csv creates a name like <code>Unnamed: 0_level_1</code>. How would I do to replace these with empty strings?</p>
<pre><code>import pandas as pd
file = """A,B,C,C
,,C1,C2
1,2,3,4
5,6,7,8
"""
with open('test.csv', 'w') as f:
f.write(file)
df = pd.read_csv... | <p>You can use built-in rename, something like:</p>
<pre><code>data.rename( columns={0:'whatever you want'}, inplace=True )
</code></pre>
<p>More info <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stabl... | python|pandas | 0 |
8,882 | 54,254,825 | Python read data from csv using space sep except first column | <p>Hi im wondering if there is a way to read data from csv file using pandas read_csv that every entry is separated by space except the first column:</p>
<pre><code>Alabama 400 300 200
New York 400 200 100
Missouri 400 200 50
District of Columbia 450 100 250
</code></pre>
<p>So there would be 4 columns, with the firs... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> with separator not in data like <code>|</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.rsplit.html" rel="nofollow noreferrer">... | python|pandas|dataframe | 3 |
8,883 | 54,451,362 | How to use GPUs with Ray in Pytorch? Should I specify the num_gpus for the remote class? | <p>When I use the Ray with pytorch, I do not set any num_gpus flag for the remote class. </p>
<p>I get the following <strong>error</strong>: </p>
<pre><code>RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False.
</code></pre>
<p>The main process is: I create a remote... | <p>If you also want to deploy the model on a gpu, you need to make sure that your actor or task indeed has access to a gpu (with @ray.remote(num_gpus=1), this will make sure that torch.cuda.is_available() will be true in that remote function). If you want to deploy your model on a CPU, you need to specify that when loa... | pytorch|ray | 5 |
8,884 | 73,636,779 | How to add column for every month and generate number i.e. 1,2,3..etc | <p>I have a huge csv file of dataframe. However, I don't have the date column. I only have the sales for every month from Jan-2022 until Dec-2034. Below is the example of my dataframe:</p>
<pre><code>import pandas as pd
data = [[6661, 'Mobile Phone', 43578, 5000, 78564, 52353, 67456, 86965, 43634, 32546, 56332, 5... | <p>Here is the simplest approach I can think of:</p>
<pre class="lang-py prettyprint-override"><code>for i, col in enumerate(ds.columns[2:]):
ds.insert(2 * i + 2, col.removeprefix("Sales"), (i - 6) // 12 + 2)
</code></pre> | python|pandas|loops | 1 |
8,885 | 73,559,949 | Fetch a column value based on another column value in Pandas | <p>Got stuck in figuring out extracting a column value based on another column value as I am new to pandas dataframe.</p>
<pre><code> Name Age City
0 Jim 19 NY
1 Tom 25 LA
2 Sid 33 PH
</code></pre>
<p>How to extract Name based on a value for City? ie, to get result as Sid when City =... | <p>This will work:</p>
<pre class="lang-py prettyprint-override"><code>name = df[df.City=='PH'].Name.iloc[0]
</code></pre>
<p>Alternatively, you can do:</p>
<pre class="lang-py prettyprint-override"><code>name = df.query("City=='PH'").Name.iloc[0]
</code></pre>
<p>Also this:</p>
<pre class="lang-py prettyprin... | python|pandas | 0 |
8,886 | 73,646,841 | Python add missing values to index | <p>Having the following DF :</p>
<pre><code>Index Date
1D 9/13/2022
1W 9/19/2022
2W 9/26/2022
3W 10/3/2022
1M 10/12/2022
2M 11/14/2022
3M 12/12/2022
4M 1/12/2023
5M 2/13/2023
6M 3/13/2023
7M 4/12/2023
8M 5/12/2023
9M 6/12/2023
10M 7/12/2023
11M ... | <p>Use:</p>
<pre><code>#filter Y index values
m = df.index.str.endswith('Y')
#processing only years
df1 = df[m].copy()
#extract numbers to index
df1.index = df1.index.str.extract(r'(\d+)', expand=False).astype(int)
#reindex by range for append missing rows
df1 = df1.reindex(range(df1.index.min(), df1.index.max()+1)).... | python|pandas | 2 |
8,887 | 71,436,163 | Pandas version upgrade causing value error while using groupby and aggregate max | <p>A and B are non numeric columns. A and B columns dont have NaN Values.However, dataframe has NaN values in other columns.</p>
<p>I got a related link on github issues : <a href="https://github.com/pandas-dev/pandas/issues/32077" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues/32077</a> but I a... | <p>Pandas Version 1.1.5 has a bug while doing aggregation for max on groupbydataframes. This was fixed in 1.3.1. Running the above code works fine in 1.3.1 version of pandas. Hence closing the ticket.</p> | python|python-3.x|pandas|dataframe|pandas-groupby | 1 |
8,888 | 71,409,586 | Efficiently combining groupby, last and count in pandas | <p>From a list of logs, i want to get the number of active events at each timestamp for a specific event type.</p>
<p>A sample log input looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>time</th>
<th>id</th>
<th>event</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-03-01 10:00</td... | <pre><code>df.set_index(['time', 'id']).unstack().fillna(method='ffill')\
.stack().value_counts(['time', 'event']).unstack().fillna(0)
</code></pre>
<p>The first line takes care of getting the latest event from each <code>id</code> at each hour by forward-filling the <code>NaN</code>s</p>
<pre><code> ... | python|pandas|pandas-groupby | 1 |
8,889 | 52,331,427 | numpy linspace returning negative numbers for a positive interval | <pre><code>np.linspace(10**3, 10**6, num=5, dtype=np.int16)
</code></pre>
<p>yelds</p>
<pre><code>array([ 1000, -11394, -23788, 29354, 16960], dtype=int16)
</code></pre>
<p>I don't understand the presence of negative numbers in a positive interval.</p>
<p>Can anyone point me to what I'm missing ? (And eventually... | <p>As mentioned in the comments, the reason for this is <a href="https://en.wikipedia.org/wiki/Integer_overflow" rel="nofollow noreferrer">overflow</a>. </p>
<p>More specifically, you asked for numbers between 1E3 to 1E6, but <code>int16</code> supports values in the range <code>[-32768, 32767]</code>. When we try to ... | python|numpy | 0 |
8,890 | 52,047,906 | Tensorflow how to read tensor from OpenCV image frame | <p>Tensorflow provides a <code>label_image.py</code> implementation for inference of an image. This works great for images on disk. But i have a case wherein I am reading a streaming video from a webcam and I would like to run inference on each image frame to detect the object in the camera feed.</p>
<p>Currently <a h... | <p>There are 3 ways. you can</p>
<ol>
<li>feed numpy array to tensorflow, considering opencv python wrapper read image as numpy array, </li>
<li><code>tf.py_func</code> is useful when you don't want to feed your input because of performance issue. </li>
<li>Also, if you use c++, you can define a custom op to wrap open... | opencv|tensorflow|computer-vision | 0 |
8,891 | 60,366,773 | Fill dataframe column with a value if multiple columns match values in a dictionary | <p>I have two dataframes - one large dataframe with multiple categorical columns and one column with missing values, and another that's sort of a dictionary with the same categorical columns and one column with a key value.</p>
<p>Essentially, I want to fill the missing values in the large dataframe with the key value... | <p>Try:</p>
<pre><code>missing_df.reset_index()[['index', 'Color', 'Number', 'Letter']]\
.merge(dict_df, on = ['Color', 'Number', 'Letter'])\
.set_index('index').reindex(missing_df.index)
</code></pre>
<p>Output:</p>
<pre><code> Color Number Letter Value
0 Red 2 B 15
1 Green... | python|pandas|dataframe|dictionary | 1 |
8,892 | 60,457,833 | Conditional Pandas Statement and Apply | <p>I can't share a lot of my code, but I'm using a conditional statement to then pass a function to a column in my dataframe. I'm getting a Database error <code>(<cx_Oracle._Error object at 0x00000114A0BE38D0></code>, <code>'occurred at index 880')</code>. </p>
<pre><code>def my_new_func(row):
return RCCheck... | <p>Figured it out:</p>
<pre><code>NSAM['Action'] = NSAM.loc[(NSAM['Security_Description'] == 'Update External User - Reporting') & (NSAM.Analyst.isin(analyst_list))].apply(my_new_func, axis=1)
</code></pre>
<p>In my original code I said NSAM.apply(my_new_func, axis =1). I was calling the whole dataframe to apply ... | python|pandas|dataframe | 0 |
8,893 | 60,543,446 | I can't save my Dataframe to Cloud Storage | <pre><code>def save_csv_to_cloud_storage(df,file_name,folder='output'):
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/Users/******/Desktop/*****.json'
storage_client = storage.Client()
bucket = storage_client.get_bucket('fluxlengow')
now = datetime.now()
dt_string = now.strftime("%Y%m%d-%H%M%S")... | <p>I strongly suggest to use the <code>gcsfs</code> package which allows to write to the bucket directly from pandas, given the URL</p>
<pre class="lang-py prettyprint-override"><code>def store_dataframe(df, filename, path = "news"):
url = f"gs://{BUCKET_NAME}/{path}/{filename}"
df.to_csv(u... | python|pandas|utf-8|character-encoding|google-cloud-storage | 1 |
8,894 | 59,805,321 | What is the best way to check if the last rows of a pandas dataframe meet a condition? | <p>I got stuck trying to create a new column that is a check column based on the 'signal' column. If the last five rows(including the last) are 1, it would return 1, If the last five rows(including the last) are 0, it would return 0, everything else would be the last value of check, like this:</p>
<p>I have the follow... | <p>You want to use a rolling window over your dataframe, followed by <code>fillna</code>:</p>
<pre><code>def allSame(x):
if (x == 1).all():
return 1.0
elif (x == 0).all():
return 0.0
else:
return np.nan
df['signal'] = df.rolling(5).apply(allSame, raw=False).fillna(method="ffill")
<... | python|pandas|dataframe | 3 |
8,895 | 40,456,416 | error on importing tensorflow in ubuntu | <p>i have <code>ubuntu 14.04</code> ; But a got this error when I run import tensorflow : </p>
<p>if i'am import a tensorflow </p>
<pre><code>>>> import tensorflow
</code></pre>
<p>.</p>
<pre><code>RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9
Traceback (most recent... | <p>You need to update your numpy version to 10 (your current version is 9). </p> | ubuntu|import|tensorflow | 1 |
8,896 | 40,683,200 | Group column data into Week in Python | <p>I have 4 columns which have Date , Account #, Quantity and Sale respectively. I have daily data but I want to be able to show Weekly Sales per Customer and the Quantity.
I have been able to group the column by week, but I also want to group it by OracleNumber, and <strong>Sum</strong> the Quantity and Sales columns.... | <p>IIUC, you could <code>groupby</code> w.r.t the week column and <em>OracleNumber</em> column by providing an extra key to the <code>list</code> for which the Groupby object has to use and perform <code>sum</code> operation later:</p>
<pre><code>sales.groupby([sales['Date'].dt.week, 'OracleNumber']).sum()
</code></pr... | python|python-3.x|pandas | 2 |
8,897 | 61,718,049 | Error when running (open-mmlab) C:\mmdetection>python setup.py develop - raise RuntimeError(message) | <p>I get the following error in the last stage of the mmdetection install from
<a href="https://github.com/open-mmlab/mmdetection/blob/master/docs/install.md" rel="nofollow noreferrer">https://github.com/open-mmlab/mmdetection/blob/master/docs/install.md</a></p>
<p>when running</p>
<pre><code>C:\...\mmdetection\pytho... | <p>In github <a href="https://github.com/open-mmlab/mmdetection/blob/v2.0.0/docs/install.md" rel="nofollow noreferrer">https://github.com/open-mmlab/mmdetection/blob/v2.0.0/docs/install.md</a></p>
<p>by following the instructions, but this time switching github tag to v2.0.0 and cloning it</p>
<p>typing in this </p>
... | python|python-3.x|deep-learning|pytorch|object-detection | 0 |
8,898 | 61,881,950 | Converting Spark DF too Pandas DF and other way - Performance | <p>Trying to convert Spark DF with 8m records to Pandas DF</p>
<pre><code>spark.conf.set("spark.sql.execution.arrow.enabled", "true")
sourcePandas = srcDF.select("*").toPandas()
</code></pre>
<p>Takes almost 2 minutes</p>
<p>And other way from Pandas to Spark DF </p>
<pre><code>finalDF = spark.createDataFrame(sourc... | <p>Collecting to pandas and re-parallelizing to the cluster will have a memory high water mark of approx 2 times the storage cost of the pandas DF. Ten rows of your dataframe is 3KB, so 8M will be ~2.5G. Doubling to get the high water mark takes us to ~5G. The default spark driver memory is 1G, which is too low for wha... | pandas|azure-databricks|pyspark-dataframes | 0 |
8,899 | 61,829,495 | How to check if all items in list of RGB colors is in an image without a loop? | <p>Say I have a list of RGB values as follows:</p>
<pre><code>rgbL = [[20 45 40] [30 45 60] .... [70 50 100]]
</code></pre>
<p>Then, I have an image say, <code>img = cv.imread("location")</code></p>
<p>Now, I want to change ALL RGB values of an image into (255, 0, 0) if the image RGB value is IN my list of RGB value... | <p>convert your <code>rgbL</code> and <code>img</code> into numpy arrays. one way of doing it without loop:</p>
<pre><code>sh = img.shape
img = img.reshape(-1, 3)
img[np.where(((rgbL[:,None,:]-img)==0).all(axis=2))[1]]=np.array([255,0,0])
img = img.reshape(sh)
</code></pre>
<p>which takes a difference of your image w... | python|numpy | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.