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
900
18,091,694
Monte Carlo Simulation with Python: building a histogram on the fly
<p>I have a conceptual question on building a histogram on the fly with Python. I am trying to figure out if there is a good algorithm or maybe an existing package.</p> <p>I wrote a function, which runs a Monte Carlo simulation, gets called 1,000,000,000 times, and returns a 64 bit floating number at the end of each r...
<p>Here is a possible solution, with fixed bin size, and bins of the form [k * size, (k + 1) * size[. The function finalizebins returns two lists: one with bin counts (a), and the other (b) with bin lower bounds (the upper bound is deduced by adding binsize).</p> <pre><code>import math, random def updatebins(bins, bi...
python|numpy|pandas|histogram|montecarlo
3
901
55,296,464
How can I feed a sparse placeholder in a TensorFlow model from Java
<p>I'm trying to calculate the best match for a given address with the kNN algorithm in TensorFlow, which works pretty good, but when I'm trying to export the model and use it in our Java Environment I got stuck on how to feed the sparse placholders from Java. </p> <p>Here is a pretty much stripped down version of the...
<p>I was able to get your example working. I have a couple of comments on your python code before diving in.</p> <p>You use the variable <code>output_dist</code> for 3 different value types throughout the code. I'm not a python expert, but I think it's bad practice. You also never actually use the <code>input_name</co...
java|tensorflow
1
902
55,577,551
Transform all rows of data frame into arrays and pass to function
<p>I want to transform all rows of a data frame to arrays and use the arrays in a function. The function should create a new column with the results of the function for every row.</p> <pre><code>def harmonicMean(arr): sum = 0; for item in arr: sum = sum + float(1.0/item); print "inside" + str(f...
<p>You can calculate without iterating over the rows:</p> <pre><code>df['hmean'] = df.notnull().sum(axis=1)/(1/df).sum(axis=1) a b c d e hmean 0 4 5.0 2.0 5.0 10 4.000000 1 2 8.0 1.0 8.0 6 2.608696 2 7 NaN 1.0 1.0 8 1.763780 3 7 1.0 9.0 4.0 9 3.095823 4 8 5.0 8.0 ...
python|pandas|dataframe
3
903
55,470,614
Dataframe writing to Postgresql poor performance
<p>working in postgresql I have a cartesian join producing ~4 million rows. The join takes ~5sec and the write back to the DB takes ~1min 45sec.</p> <p>The data will be required for use in python, specifically in a pandas dataframe, so I am experimenting with duplicating this same data in python. I should say here tha...
<p>Answering Q 1 myself: It seems the issue had more to do with Postgresql (or rather Databases in general). Taking into account points made in this article:<a href="https://use-the-index-luke.com/sql/dml/insert" rel="nofollow noreferrer">https://use-the-index-luke.com/sql/dml/insert</a> I found the following:</p> <p>...
python|pandas|postgresql|dataframe|sqlalchemy
1
904
10,159,178
How to create a 2D "rect" array (square block of 1's, else 0's) in numpy?
<p>What is the "correct" way of creating a 2D numpy "rect" array, like:</p> <pre><code>0000000000000000000 0000000000000000000 0000000000111110000 0000000000111110000 0000000000111110000 0000000000000000000 </code></pre> <p>i.e. an array which has a given value inside certain bounds, or zero otherwise?</p>
<p>Just create an array of zeros and set the area you want to one. </p> <p>E.g.</p> <pre><code>import numpy as np data = np.zeros((6,18)) data[2:5, 9:14] = 1 print data </code></pre> <p>This yields:</p> <pre><code>[[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 0. ...
python|arrays|numpy|rect
16
905
10,149,416
Numpy modify array in place?
<p>I have the following code which is attempting to normalize the values of an <code>m x n</code> array (It will be used as input to a neural network, where <code>m</code> is the number of training examples and <code>n</code> is the number of features).</p> <p>However, when I inspect the array in the interpreter after...
<p>If you want to apply mathematical operations to a numpy array in-place, you can simply use the standard in-place operators <code>+=</code>, <code>-=</code>, <code>/=</code>, etc. So for example:</p> <pre><code>&gt;&gt;&gt; def foo(a): ... a += 10 ... &gt;&gt;&gt; a = numpy.arange(10) &gt;&gt;&gt; a array([0, 1...
python|arrays|numpy|in-place
30
906
56,473,742
DataFrame detect when one column becomes bigger than another
<p>I am wondering about code that detect when values in one column BECOME bigger than values in another column. So in the example below in row index 1 B becomes bigger than A and in row index 3 A becomes bigger than B. I would like to get a DataFrame that highlights row 1 and 2 and also which column that became bigger ...
<p>You could check where <code>A</code> is greater than <code>B</code> cast to <code>int8</code> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.view.html" rel="nofollow noreferrer"><code>view</code></a> and take the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/...
python|pandas|dataframe
5
907
56,710,907
How to increment value of a new column when duplicate value is found in another column of a dataframe in python?
<p>I've a CSV file that looks like :</p> <pre><code>Timestamp Status 1501 Normal 1501 Normal 1502 Delay 1503 Received 1504 Normal 1504 Delay 1505 Received 1506 Received 1507 Delay 1507 Received </code></pre> <p>I want to add a new "Notif" column to datafram...
<p>Iterating over the rows with <code>df.iterrows</code> you can achieve the following:</p> <pre><code>df['Notif'] = None counter = 0 for idx, row in df.iterrows(): if df.iloc[idx, 1] == "Received": counter +=1 df.iloc[idx,-1] = "N" + str(counter) print(df) </code></pre> <p><strong>Output</strong></p...
python|pandas|dataframe|pycharm
2
908
56,810,488
Calculation of Laplacian in real pyFFTW
<p>For the forward (multidimensional) FFTW algorithm you can specify that the input <code>numpy.ndarray</code> is real, and the output should be complex. This is done when creating the byte-aligned arrays that go in the arguments of the <code>fft_object</code>:</p> <pre><code>import numpy as np import pyfftw N = 256 ...
<p>I'm not familiar with <code>pyfftw</code>, but with the <code>numpy.fft</code> module it would work just fine (assuming you use <code>rfftfreq</code> as mentioned in the comments).</p> <p>To recap: for a real array, <code>a</code>, the fourier transform, <code>b</code>, has a Hermtian-like property: <code>b(-kx,-k...
python|numpy|fft|numerical-methods|pyfftw
0
909
66,874,360
Converting nested JSON structures to Pandas DataFrames
<p>I've been struggling with the nested structure in json, how to convert to correct form</p> <pre><code>{ &quot;id&quot;: &quot;0c576f35-d704-4fa8-8cbb-311c6be36358&quot;, &quot;employee_id&quot;: null, &quot;creator_id&quot;: &quot;16ca2db9-206c-4e18-891d-a00a5252dbd3&quot;, &quot;closed_by_id&quot;: null, &quot;requ...
<p>You can do something like this.</p> <p>pass the <code>dataframe</code> and the column to the function as arguments</p> <pre><code>def explode_node(child_df, column_value): child_df = child_df.dropna(subset=[column_value]) if isinstance(child_df[str(column_value)].iloc[0], str): child_df[column_value]...
python|json|pandas|dataframe
1
910
66,777,182
find common rows based on specific columns in a dataframe
<p>I have a dataframe, I would like to find the common rows based on a specific columns.</p> <pre><code>packing_id col1 col2 col3 col4 1 1.0 2.0 2 2.0 2.0 3 1.0 1.0 4 3.0 3.0 . . . . . . </code></pre> <p>I would like to find the rows wher...
<p>I think your soluton is good, only add 2 parameters to <code>np.where</code>:</p> <pre><code>df['new'] = np.where(df.col1==df.col2, 'same', 'no same') </code></pre> <p>If need filter them:</p> <pre><code>df1 = df[df.col1==df.col2] </code></pre>
python|pandas
1
911
47,520,820
Implementing momentum weight update for neural network
<p>I'm following along mnielsen's online <a href="http://neuralnetworksanddeeplearning.com/chap1.html" rel="nofollow noreferrer">book</a>. I'm trying to implement momentum weight update as defined <a href="http://cs231n.github.io/neural-networks-3/#sgd" rel="nofollow noreferrer">here</a> to his code <a href="https://gi...
<p>As discussed in the comments, something is not a numpy array here. The error given above</p> <pre><code>TypeError: can't multiply sequence by non-int of type 'float' </code></pre> <p>is an error issued by Python for the sequence types (list, tuple, etc). The error message means that a sequence cannot be multiplied...
python|numpy|machine-learning|neural-network|mnist
0
912
47,109,980
How can i replace image masking in for-loop with logical indexing in python?
<p>I am trying to track an object in a video by its color. Can i simplify this code:</p> <pre><code>while True: ret, frame = cap.read() if not ret: break height, width, channel = frame.shape hue = cv2.cvtColor(frame, cv2.COLOR_RGB2HSV) for i in range(width): for j in range(height): ...
<p>Get rid of the two nested for-loops with <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow noreferrer"><code>masking</code></a>, like so -</p> <pre><code>hue[(hue[...,0] &lt; 110) | (hue[...,0] &gt;140)] = 0 </code></pre> <p>This works because t...
python|numpy|opencv|indexing
0
913
47,383,584
Pandas adds "\r" to csv file
<h1>This boils down to a simpler problem <a href="https://stackoverflow.com/questions/47384652/python-write-replaces-n-with-r-n-in-windows">here</a></h1> <p>I have a pandas dataframe that looks like this: </p> <pre><code>In [1]: df Out[1]: 0 1 0 a A\nB\nC 1 a D\nE\nF 2 b A\nB\nC </code></pre> <p>Whe...
<p>As some have already said in comments above and on the post you have put in reference <a href="https://stackoverflow.com/questions/47384652/python-write-replaces-n-with-r-n-in-windows">here</a>, this is a typical windows issue when serializing newlines. The issue has been reported on pandas-dev github <a href="http...
python|python-3.x|pandas|csv
9
914
68,329,805
'numpy.float64' object has no attribute 'ttest_ind'
<p>I am trying to perform a t-test with the following. It worked initially. But, now, it is showing the following error,</p> <p><strong>'numpy.float64' object has no attribute 'ttest_ind'</strong></p> <pre><code>col=list(somecolumns) for i in col: x = np.array(data1[data1.LoanOnCard == 0][i]) y = np.array(data...
<p>Add <code>from scipy import stats</code> to your code.</p> <p>If you already did it, this means you likely overwrote <code>stats</code> with another object. Then you can do <code>import scipy.stats</code> and use <code>scipy.stats.ttest_ind</code> instead of <code>stats.ttest_ind</code></p>
pandas|numpy|data-science|scipy.stats
1
915
68,138,677
How to count specific words in a list from a panda dataframe?
<p>I was wondering how I can count the number of unique words that I have in a list from a specific data frame. For example, let's say I have a list = <code>['John','Bob,'Hannah']</code> Next, I have a data frame with a column called sentences</p> <pre><code>df = ['sentences'] 0 Bob went to the shop 1 John ...
<p>You can use <code>Series.str.contains</code> and call the <code>sum</code> to get the number of occurances of a word in the given column, just iterate over the list for all the substrings and do the same for each word, store the result as dictionary.</p> <pre class="lang-py prettyprint-override"><code>list1 = ['John...
python|pandas
2
916
68,252,257
Understanding Python Numpy while performing mathematical operations
<p>I have the following Numpy array. And I write the following code :</p> <pre><code>import numpy as np np_mat = np.array([[1, 2],[3, 4],[5, 6]]) np_mat * 2 print(np_mat.shape) np_mat = np_mat + np.array([[10, 11],[-1,-2]]) print(np_mat) </code></pre> <p>Surprisingy Python throws an error sayin...
<p><a href="https://numpy.org/doc/stable/user/basics.broadcasting.html#general-broadcasting-rules" rel="nofollow noreferrer">General Broadcasting Rules</a></p> <blockquote> <p>When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. rightmost) dimensions and works its wa...
python|numpy
1
917
68,343,441
How to I change a specific range of pixels with respect to a condition given in numpy?
<p>Libraries Imported:</p> <pre><code> %matplotlib inline import numpy as np from scipy import misc import imageio import matplotlib.pyplot as plt from skimage import data </code></pre> <p>Like I created a:</p> <pre><code> low_value_filter= dogs2 &lt; 80 </code></pre> <p>and did:</p> <pre><cod...
<p>Hey I've found the solution to this problem.</p> <p><em>Create an array of zeros of the same shape as the image:</em></p> <p><code>low_value_filter = np.zeros_like(dogs)</code></p> <p><em>Select the range of the image you want to add your filter to:</em></p> <p><code>low_value_filter[upper:lower, left:right] = dogs[...
python|numpy|image-processing|imagefilter|python-imageio
0
918
59,199,502
StyleGAN image generation doesn't work, TensorFlow doesn't see GPU
<p>After reinstalling Ubuntu 18.04, I cannot generate images anymore using a StyleGAN agent. The error message I get is <code>InvalidArgumentError: Cannot assign a device for operation Gs_1/_Run/Gs/latents_in: {{node Gs_1/_Run/Gs/latents_in}}was explicitly assigned to /device:GPU:0 but available devices are [ /job:loca...
<p>Might be because TensorFlow is looking for <code>GPU:0</code> to assign a device for operation when the name of your graphical unit is actually <code>XLA_GPU:0</code>.</p> <p>What you could try to do is using soft placement when opening your session, so that TensorFlow uses any existing GPU (or any other supported ...
python|tensorflow|machine-learning|gpu
1
919
59,333,293
How to append multiple columns to the first 3 columns and repeat the index values using pandas?
<p>I have a data set in which the columns are in multiples of 3 (excluding index column[0]). I am new to python.</p> <p>Here there are 9 columns excluding index. So I want to append 4th column to the 1st,5th column to 2nd,6th to 3rd, again 7th to 1st, 8th to 2nd, 9th to 3rd, and so on for large data set. My large data...
<p>Idea is reshape by <code>stack</code> with sorting second level of <code>MultiIndex</code> and also for correct ordering create ordered <code>CategoricalIndex</code>:</p> <pre><code>a = np.arange(len(df.columns)) df.index = pd.CategoricalIndex(df.index, ordered=True, categories=df.index.unique()) df.columns = [a /...
python|pandas
3
920
59,315,132
How to get which semester a day belongs to using pandas.Period
<p>I would like to know an easy way to get which semester a day belongs to while displaying it on following format ('YYYY-SX'); 2018-01-01 -> (2018S1).</p> <p>I have a date range and is pretty easy to do it for quarters:</p> <pre><code>import pandas as pd import datetime start = datetime.datetime(2018, 1, 1) end =...
<p>You can do something like this.</p> <pre><code>df['sem']= df.date.dt.year.astype(str) + 'S'+ np.where(df.date.dt.quarter.gt(2),2,1).astype(str) </code></pre> <p>Note: the column <code>date</code> needs to be as <code>datetime</code> object</p> <p><strong>Input</strong></p> <pre><code>date 0 2019-09-30 1 2019...
python|pandas|datetime
2
921
59,404,051
Each element in list at least equal to the previous one
<p>A list of monthly sales until November, I want to know if the sales trend is upward.</p> <p>Definition of upward: each monthly sales is greater or at least equal to previous month's.</p> <p><a href="https://i.stack.imgur.com/gkKWQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gkKWQ.png" alt="e...
<p>Pandas Series has attribute <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.is_monotonic.html" rel="nofollow noreferrer"><code>is_monotonic</code></a> to check on monotonic increasing. Don't need to sort or do anything fancy.</p> <pre><code>print(df_a.Sales.is_monotonic) Out[94]...
python|pandas|list|dataframe
4
922
45,187,318
Reading data from xlsx into Pandas dataframe
<p><strong>Scenario:</strong> I put together this little Frankenstein of a code (with some awesome help from SO users) to get data from excel files and put into a pandas dataframe.</p> <p><strong>What I am trying to do:</strong> I am trying to get data from files that may contain one or more worksheets of data. After ...
<p>Separate the different things your code does in different functions.</p> <ul> <li>look for the excel-files</li> <li>read the excel-files</li> <li>convert the content to <code>datetime</code></li> <li>concatenate the DataFrames</li> </ul> <p>This way you can check and inspect each step separately instead of have it...
python|excel|pandas|dataframe
2
923
44,961,181
DRQN - Prefix tensor must be either a scalar or vector, but saw tensor
<p>In following <a href="https://github.com/awjuliani/DeepRL-Agents/blob/master/Deep-Recurrent-Q-Network.ipynb" rel="nofollow noreferrer">this tutorial</a>, I am receiving the following error: </p> <p><code>ValueError: prefix tensor must be either a scalar or vector, but saw tensor: Tensor("Placeholder_2:0", dtype=int...
<p>There is another solution to solve this problem.</p> <p>Change</p> <pre><code>self.batch_size = tf.placeholder(dtype=tf.int32) </code></pre> <p>TO</p> <pre><code>self.batch_size = tf.placeholder(dtype=tf.int32, []) </code></pre>
python|tensorflow
3
924
45,071,327
Why doesn't calling replace on a pandas dataFrame not act on the original object?
<p>If you look at the following simple example:</p> <pre><code>import pandas as pd l1 = [1,2,'?'] df = pd.DataFrame(l1) df.replace('?',3) </code></pre> <p>Why does this not replace the '?' in the dataframe df? Wouldn't the object that is referred to by df be affected when replace is called on it? </p> <p>If I write...
<p>You need <code>inplace=True</code>:</p> <pre><code>df.replace('?',3, inplace=True) print (df) 0 0 1 1 2 2 3 </code></pre>
python|pandas|object
3
925
44,948,007
TensorFlow fails to use gpu
<p>I'm getting started with TensorFlow, but I cannot make it use GPU instead of CPU with TensorFlow 1.2.1.</p> <p>I've got a laptop equipped with a NVIDIA GTX 850M which is CUDA 5.0 compatibility.</p> <p>The CUDA Toolkit is installed with the latest version available.</p> <p>cuDNN is installed with the latest versio...
<p>In the latest version of Tensorflow, you can check the GPU availability as</p> <pre><code>gpu_available = tf.test.is_gpu_available() is_cuda_gpu_available = tf.test.is_gpu_available(cuda_only=True) is_cuda_gpu_min_3 = tf.test.is_gpu_available(True, (3,0)) </code></pre> <p><code>tf.test.is_gpu_available</code> will b...
python|tensorflow|gpu
0
926
57,130,097
A fast method to add a label column to large pd dataframe based on a range of another column
<p>I'm fairly new to python and am working with large dataframes with upwards of 40 million rows. I would like to be able to add another 'label' column based on the value of another column.</p> <p>if I have a pandas dataframe (much smaller here for detailing the problem)</p> <pre class="lang-py prettyprint-override">...
<p>You can to the task in a "more pandasonic" way.</p> <p>Start from creating a <em>Series</em>, named <em>labels</em>, initially with empty strings:</p> <pre><code>labels = pd.Series([''] * 100).rename('label') </code></pre> <p>The length is 100, just as the upper limit of your values.</p> <p>Then fill it with pro...
python|pandas|dataframe|indexing
0
927
57,031,897
Assistance with comparing multiple columns in 2 different dataframes
<p>I have 2 dataframes:</p> <p><code>df1</code> has between 100-300 rows depending on the day<br> <code>df2</code> contains between 10,000-40,000 depending on the day</p> <p>The columns are as such:</p> <p>df1:</p> <pre><code>ID STATE STATUS 1 NY ACCEPTED 1 PA ACCEPTED 1 C...
<p>You could merge both dataframes and check the status with pd.merge:</p> <pre><code>pd.merge(left=df_a, right=df_b, on='id',suffixes=('_df_a','_df_b')) </code></pre> <p><a href="https://i.stack.imgur.com/HSvuB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HSvuB.png" alt="enter image description...
python|pandas
0
928
57,192,304
Numpy Python: Exception: Data must be 1-dimensional
<p>Getting exception <code>Exception: Data must be 1-dimensional</code></p> <p>using NumPy in Python 3.7</p> <p>Same code is working for others but not in my case. Bellow is my code please help</p> <blockquote> <p><a href="https://i.stack.imgur.com/6XBq8.jpg" rel="nofollow noreferrer">Working_code_in_diff_system</a></...
<p>I think you need to call <code>np.reshape</code> on the underlying numpy array rather than on the Pandas series - you can do this using <code>.values</code>:</p> <pre><code>x_train = np.reshape(x_train.values, (-1, 1)) </code></pre> <p>Repeat the same idea for the next three lines.</p> <p>Or, if you are on a rec...
python-3.x|numpy|regression|linear-regression
5
929
57,285,680
Retain few NA's and drop rest of NA's during Stack operation in Python
<p>I have a dataframe like shown below </p> <pre><code>df2 = pd.DataFrame({'person_id':[1],'H1_date' : ['2006-10-30 00:00:00'], 'H1':[2.3],'H2_date' : ['2016-10-30 00:00:00'], 'H2':[12.3],'H3_date' : ['2026-11-30 00:00:00'], 'H3':[22.3],'H4_date' : ['2106-10-30 00:00:00'], 'H4':[42.3],'H5_date' : [np.nan], 'H5':[np.na...
<p>On approach is to melt the DF, apply a key that identifies columns in the same "group" (in this case <code>H&lt;some digits&gt;</code> but you can amend that as required), then group by person and that key, filter those groups to those containing at least one non-NA value), eg:</p> <p>Starting with:</p> <pre><code...
python|pandas|dataframe
1
930
46,020,617
Best way to avoid merge nulls
<p>Let's say I have those 2 pandas dataframes.</p> <pre><code>In [3]: df1 = pd.DataFrame({'id':[None,20,None,40,50],'value':[1,2,3,4,5]}) In [4]: df2 = pd.DataFrame({'index':[None,20,None], 'value':[1,2,3]}) In [7]: df1 Out[7]: id value 0 NaN 1 1 20.0 2 2 NaN 3 ...
<p>If you dont want nan values then you can drop the nan values i.e </p> <pre><code>df3 = df1.merge(df2, left_on='id', right_on = 'index', how='inner').dropna() </code></pre> <p>or </p> <pre><code>df3 = df1.dropna().merge(df2.dropna(), left_on='id', right_on = 'index', how='inner') </code></pre> <p>Output: </p> <p...
python|pandas|merge|null
1
931
46,030,481
ImportError: No module named 'nets'
<p>I am trying to convert trained_checkpoint to final frozen model from the export_inference_graph.py script provided in tensorflow/models,but the following error results. And yes,I have already setup $PYTHONPATH to "models/slim" but still I get this error,can someone help me out?</p> <pre><code>$ echo $PYTHONPATH :/...
<p>Take a look at Protobuf Compilation at <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md" rel="noreferrer">https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md</a> and set PYTHONPATH correctly, this is how I solved t...
python|python-3.x|tensorflow
20
932
23,189,506
Maximum allowed value for a numpy data type
<p>I am working with numpy arrays of a range of data types (uint8, uint16, int16, etc.). I would like to be able to check whether a number can be represented within the limits of an array for a given datatype. I am imagining something that looks like:</p> <pre><code>&gt;&gt;&gt; im.dtype dtype('uint16') &gt;&gt;&gt; d...
<pre class="lang-py prettyprint-override"><code>min_value = np.iinfo(im.dtype).min max_value = np.iinfo(im.dtype).max </code></pre> <p>docs:<br></p> <ul> <li><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.iinfo.html#numpy-iinfo" rel="noreferrer"><code>np.iinfo</code></a> (machine limits for intege...
python|numpy
126
933
23,170,415
Self Join in Pandas: Merge all rows with the equivalent multi-index
<p>I have one dataframe in the following form: </p> <pre><code>df = pd.read_csv('data/original.csv', sep = ',', names=["Date", "Gran", "Country", "Region", "Commodity", "Type", "Price"], header=0) </code></pre> <p>I'm trying to do a self join on the index Date, Gran, Country, Region producing rows in the form of Da...
<p>What you want to do is called a reshape (specifically, from long to wide). See <a href="https://stackoverflow.com/questions/22798934/pandas-long-to-wide-reshape">this answer</a> for more information.</p> <p>Unfortunately as far as I can tell pandas doesn't have a simple way to do that. I adapted the answer in the o...
python-2.7|pandas|self-join
1
934
35,709,042
How to create a masked array using numpy.ma imported by PyCall in Julia
<p>I want to create a masked array using <code>numpy.ma</code> imported by PyCall in Julia.</p> <p>A Python example in the the help of <code>is_masked()</code> in <code>numpy.ma</code> module.</p> <pre><code>&gt;&gt;&gt; import numpy.ma as ma &gt;&gt;&gt; x = ma.masked_equal([0, 1, 0, 2, 3], 0) &gt;&gt;&gt; x masked_...
<p>I don't think there's anything wrong with your translation — this looks like a bug in PyCall. PyCall tries to map Julia and Python types back and forth so that you can seamlessly use Julia's arrays like NumPy arrays (for example). In this case, it looks like it's a bit overzealous in doing the conversion.</p> <p>...
python|arrays|numpy|julia
3
935
35,780,734
Python Pandas replace() not working
<p>I have some fields that have some junk in them from an upstream process. I'm trying to delete <strong>'\r\nName: hwowneremail, dtype: object'</strong> from a column that has this junk appended to an email address. </p> <pre><code>report_df['Owner'].replace('\r\nName: hwowneremail, dtype: object',inplace=True) repo...
<p>As far as I remember, Python Pandas was changed a little bit in replace. You should try passing over a regex keyword argument.</p> <p>Like so;</p> <pre><code>report_df['Owner'].replace({'\r\nName: hwowneremail, dtype: object':''},regex=True) </code></pre>
pandas
5
936
35,585,104
How does Pandas calculate quantiles?
<p>I have the following simple dataframe:</p> <pre><code>&gt; df = pd.DataFrame({'calc_value': [0, 0.081928, 0.94444]}) &gt; df calc_value 0 0.000000 1 0.081928 2 0.944440 </code></pre> <p>Why does <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.quantile.html" rel="nofollow...
<p>Well, step per 0.1 in the range from 0.5...1.0 is equal to (0.94444-0.081928)/5 and is equal to 0.1725024</p> <pre><code>So 50q is 0.081928 60q is 0.081928+0.1725024=0.25443 70q is 0.081928+2*0.1725024=0.426933 80q is 0.081928+3*0.1725024=0.599435 90q is 0.081928+4*0.1725024=0.771938 100q is 0.081928+5*0.1725024=0....
python|pandas
2
937
11,728,836
Efficiently applying a function to a grouped pandas DataFrame in parallel
<p>I often need to apply a function to the groups of a very large <code>DataFrame</code> (of mixed data types) and would like to take advantage of multiple cores.</p> <p>I can create an iterator from the groups and use the multiprocessing module, but it is not efficient because every group and the results of the funct...
<p>From the comments above, it seems that this is planned for <code>pandas</code> some time (there's also an interesting-looking <a href="https://pypi.python.org/pypi/rosetta/0.2.4"><code>rosetta</code> project</a> which I just noticed).</p> <p>However, until every parallel functionality is incorporated into <code>pan...
python|pandas|multiprocessing|shared-memory
12
938
28,814,490
python array indexing list in list
<p>I want to do array indexing. I would have expected the result to be [0,1,1,0], however I just get an error. How can I do this type of indexing?</p> <pre><code>a_np_array=np.array(['a','b','c','d']) print a_np_array in ['b', 'c'] Traceback (most recent call last): File "dfutmgmt_alpha_osis.py", line 130, in &lt;mod...
<p>Try this <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p> <pre><code>&gt;&gt;&gt; print [int(x in ['b', 'c']) for x in a_np_array] [0, 1, 1, 0] </code></pre> <p>Utilizing the fact that <code>int(True) == 1</code> and <code>int(False) ==...
python|arrays|numpy|indexing
2
939
20,415,414
python pandas 3 smallest & 3 largest values
<p>How can I find the index of the 3 smallest and 3 largest values in a column in my pandas dataframe? I saw ways to find max and min, but none to get the 3.</p>
<p>What have you tried? You could sort with <code>s.sort()</code> and then call <code>s.head(3).index</code> and <code>s.tail(3).index</code>.</p>
python|pandas|dataframe
5
940
33,508,110
Subtracting two timestamp arrays
<p>I have two numpy arrays I created which hold a number of timestamps. The timestamps are in month,day,year,hour,sec format (eg. 12/8/2009 10:00) and I hope to use them to calculate speed. I have the speed function almost finished, I just cannot figure out how to be able to subtract the two arrays to find the differen...
<p>Just use <code>delta = time1 - time2</code> if they are in most datetime formats.</p> <p>Use <code>dateutil.parser</code> to parse to <code>datetime.datetime</code> objects.</p> <p><strong>EDIT</strong>: Subtracting datetimes gives you a timedelta. Youll need to convert this to seconds so use <code>delta.totalseco...
python|arrays|numpy
-1
941
66,471,820
Pandas:Unique values of a column based on a condition
<p>I have two columns in a dataframe:fueltype and number of doors.Fueltype has 3 categories:Petrol,Diesel and CNG.How do I find the unique values of number of doors in petrol fueltype?</p>
<p>Say that your dataframe looks like this:</p> <pre><code> fueltype number of doors 0 Petrol 2 1 Petrol 4 2 Petrol 4 3 Petrol 4 4 Diesel 2 5 Diesel 2 6 Diesel 4 7 Diesel ...
python|pandas
0
942
66,640,612
Calculate intersecting sums from flat DataFrame for a heatmap
<p>I'm trying to wrangle some data to show how many items a range of people have in common. The goal is to show this data in a heatmap format via Seaborn to understand these overlaps visually.</p> <p>Here's some sample data:</p> <pre><code>demo_df = pd.DataFrame([ (&quot;Get Back&quot;, 1,0,2), (&quot;Help&quot...
<p>We may do <code>dot</code> then fill diag</p> <pre><code>out = df.T.dot(df.ne(0)) + df.T.ne(0).dot(df) np.fill_diagonal(out.values, 0) out Out[176]: John Paul Ringo John 0 7 3 Paul 7 0 4 Ringo 3 4 0 </code></pre>
pandas|seaborn
3
943
66,677,756
Pandas update column value based on values of groupby having multiple if else
<p>I have a pandas data frame, where 3 columns X, Y, and Z are used for grouping. I want to update column B (or store it in a separate column) for each group based on the conditions shown in the code. But all I'm getting is nulls as the final outcome. I'm not sure what am I doing incorrectly</p> <p>Below is the sample ...
<p>The main flaw in your code is that you set some value in the <strong>whole</strong> <em>colB</em> column, whereas it should be set only in rows from the current group.</p> <p>To do your task the right way, define a function to be applied to each group:</p> <pre><code>def myFun(b): if (b.colA == 2).all(): ...
python|pandas|if-statement|group-by
0
944
66,677,482
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 136: invalid start byte
<p>Hello I am trying to read a csv file. This was my code:</p> <pre><code>df = pd.read_csv(&quot;2021VAERSDATA.csv&quot;) df.head() </code></pre> <p>and this was the error I received:</p> <pre><code>--------------------------------------------------------------------------- UnicodeDecodeError Tr...
<p>I accidentally faced the same issue while trying to load the same dataset. The code below should solve your problem.</p> <pre><code>df = pd.read_csv(&quot;2021VAERSDATA.csv&quot;, encoding_errors='ignore', low_memory=False) df.head() </code></pre>
python|pandas|csv
0
945
66,654,591
Throw an error in read_csv if the number of rows does not match the number of headers
<p>I have a large number of <code>csv</code> files, where I am trying to identify if the records in the files are consistent with a predefined schema. For example, given a csv :</p> <pre><code>col1,co2,col3,col4,col5,col6 A,B,,C,D,E M,N,O,,, U,V,W, </code></pre> <p>The first row is consistent as it has as many entries ...
<p>Well <code>error_bad_lines</code> will make sure there are no extra columns. As for missing columns, there is unfortunately no way to check for these without iterating over the data. You can do this with <code>assert(not df.isnull().values.any())</code>.</p>
python|pandas|csv
0
946
66,753,095
Insert into phpmyadmin with python sql fails
<p>i have the following notebook, where im trying to insert the data of a dataframe into my phpmyadmin sql database to replicate run the following:</p> <p>first i create the Database with the schema</p> <pre><code>CREATE SCHEMA IF NOT EXISTS `proyecto` DEFAULT CHARACTER SET utf8 ; USE `proyecto`; CREATE TABLE IF NOT EX...
<p>To solve the insertion we had to create an engine like this</p> <pre><code>from sqlalchemy import create_engine engine = create_engine(&quot;mysql://user:password@localhost/database_name&quot;) con = engine.connect() df.to_sql(name='table you are inserting into',con=con,if_exists='append') con.close() </code></pre>...
python|mysql|pandas
0
947
57,355,309
Compare value of rows in Dataframe
<p>I want to know if the values in two different rows of a Dataframe are the same. My df looks something like this:</p> <pre><code>df['Name1']: Alex, Peter, Herbert, Seppi, Huaba df['Name2']: Alexander, peter, herbert, Sepp, huaba </code></pre> <p>First I want to Apply .rstrip() and .toLower(), but these methods see...
<pre><code>print (df) Name1 Name2 0 Alex Alexander 1 Peter peter 2 Herbert herbert 3 Seppi Sepp 4 Huaba huaba </code></pre> <p>If need compare each row:</p> <pre><code>out1 = df["Name1"].str.lower().eq(df["Name2"].str.lower()).sum() </code></pre> <p>If need compare all val...
python|pandas|dataframe
1
948
57,357,342
How to deal with "numpy.float64' object cannot be interpreted as an integer" when I'm trying to use np.nanmean for finding mean of two array elements?
<p>I'm trying to assign mean of specific elements inside two arrays without considering NAs in the operation:</p> <pre><code>C [i] = nanmean(A[a, b, c, d], B[aa, bb, cc, dd]) </code></pre> <p>The value of <code>A[a, b, c, d]</code> is equal to <code>0.053</code>, and the value of <code>B[aa, bb, cc, dd]</code> is equ...
<p>The second argument to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.nanmean.html" rel="nofollow noreferrer"><code>np.nanmean</code></a> is the axis alongside the mean is calculated. The axis cannot be a <code>float</code>, it has to be and <code>int</code>.</p> <p>If you want the (nan)mean of...
python|numpy|mean
1
949
24,410,243
pandas convert_to_r_dataframe does not work with numpy.bool_
<p>I have a pandas data frame that I would like to convert to an R data frame to use via <code>rpy2</code>. The data types of pandas data frame are booleans, specifically <code>numpy.bool_</code>. I get a <code>KeyError</code> when trying to use <code>convert_to_r_dataframe</code>. I am using pandas 0.13.1.</p> <p>I a...
<p>I think this may be a bug, what is used to be <code>np.bool</code> now is called <code>np.bool_</code> and the key is missing for two dictionary in the source file, so modify the source (line 261 in <strong>.../site-packages/pandas/rpy/common.py</strong>) to the following will do the trick:</p> <pre><code>VECTOR_TY...
python|r|pandas|rpy2
1
950
43,830,545
pandas rolling max with groupby
<p>I have a problem getting the <code>rolling</code> function of Pandas to do what I wish. I want for each frow to calculate the maximum so far within the group. Here is an example:</p> <pre><code>df = pd.DataFrame([[1,3], [1,6], [1,3], [2,2], [2,1]], columns=['id', 'value']) </code></pre> <p>looks like</p> <pre><co...
<p>It looks like you need <code>cummax()</code> instead of <code>.rolling(N).max()</code></p> <pre><code>In [29]: df['new'] = df.groupby('id').value.cummax() In [30]: df Out[30]: id value new 0 1 3 3 1 1 6 6 2 1 3 6 3 2 2 2 4 2 1 2 </code></pre> <p><strong>Timin...
python|python-3.x|pandas|dataframe|group-by
11
951
70,620,304
Pandas upsample rows with a start and end time
<p>I have a data frame of the form:</p> <pre><code>In [5]: df = pd.DataFrame({ ...: 'start_time': ['2022-01-01 01:15', '2022-01-01 13:00'], ...: 'end_time': ['2022-01-01 03:45', '2022-01-01 15:00'], ...: 'values': [1000, 750]}) In [6]: df Out[6]: start_time end_time values 0 2...
<p>Use:</p> <pre><code>#get differencies between start and end in minutes df['diff'] = pd.to_datetime(df['end_time']).sub(pd.to_datetime(df['start_time'])).dt.total_seconds().div(60) #create DataFrame with repeat values by minutes s = pd.concat([pd.Series(r.Index,pd.date_range(r.start_time, r.end_time, freq='Min', clo...
python|pandas|time-series
1
952
70,642,281
convert tf keras model to scikit MLP NN
<p>I am experimenting with training NLTK classifier model with tensorflow and keras, would anyone know if this could be recreated with sklearn neural work MLP classifier? For what I am using ML for I don't think I need tensorflow but something simplier and easier to install/deploy.</p> <p>Not a lot of wisdom on machine...
<p>Just google converting a keras model to pytorch, there is quite a bit of tutorials out there for that... It doesnt look easy but maybe worth the effort for what ever you need it for...</p> <p>Going down this road just using sklearn MLP neural network <em><strong>I can get good enough results with sklearn...</strong>...
python|tensorflow|machine-learning|keras|scikit-learn
0
953
70,584,240
How to use tf.gather_nd for multi-dimensional tensor
<p>I don't fully understand how I should use tf.gather_nd() to pick up elements along some axis if I have multi-dimensional tensor. Let's take a small example (if I get answer for this simple example, it solves also my more complex original problem). Let's say that I have rgb image and I am trying to pick the smallest ...
<p>You will have to use <code>tf.meshgrid</code>, which will create a rectangular grid of two one-dimensional arrays representing the tensor indexing of the first and second dimension, since <code>tf.gather_nd</code> needs to know exactly where to extract values across the dimensions. Here is a simplified example:</p> ...
python|tensorflow|tensorflow2.0
1
954
70,657,015
Joining two DataFrames with Pandas, one with 1 row per key, and the other with several rows per key
<p>First, I want to point out that I didn't found the answer for my question here in stackoverflow nor in pandas documentation, so, if the question had been asked before, I'd appreciate a link for that thread.</p> <p>I want to join two DataFrames as follows.</p> <p>df1 =</p> <pre><code>key x y z 0 x0 y0 z0 1...
<p>It seems <code>df2</code> has duplicates values, so if you drop them using <code>drop_duplicates</code> method and merge with <code>df1</code> from the right side, you get the desired outcome.</p> <pre><code>out = df1.merge(df2.drop_duplicates(), on='key') </code></pre> <p>Output:</p> <pre><code> key x y z...
pandas|join|concatenation
0
955
70,557,439
Pandas Function does not reduce
<p>I try to aggregate column contains numpy arrays unfortunately, I have a error message <strong>Function does not reduce</strong></p> <pre><code>results = pd.DataFrame([['p1', 'v1', 1, 0 ,np.array([1,3, 4])], ['p1', 'v1', 2, 0 ,np.array([1,3, 4])],['p1', 'v1', 1, 1 ,np.array([1,3, 4])], ['p1', 'v1', 2, 1 ,np.array([1,...
<p>So I read up on the query() method and there is an alternative method. This is what I did:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>import pandas as pd import numpy...
python|arrays|pandas|numpy
0
956
70,480,290
Not able to install packages that rely on Tensorflow on Mac M1
<p>I successfully installed Tensorflow 2.7.0 on my MacBook with an M1 chip following this guide by Apple: <a href="https://developer.apple.com/metal/tensorflow-plugin/" rel="nofollow noreferrer">https://developer.apple.com/metal/tensorflow-plugin/</a></p> <p>I now want to install a package (ethnicolr) in a project that...
<p>So I got it to run. I'm not sure if this is ideal but I'm sharing my solution to maybe help anyone running into the same issue. I installed tensorflow <code>2.6.0</code> in a virtual environment using conda / mambaforge. I opted for <code>2.6.0</code> because <code>2.5.2</code> is not available for M1 and <code>2.5....
python|tensorflow|pip|apple-m1
0
957
70,655,943
pandas - expand array to columns
<p>I have a column in my pandas dataframe that contains array of numbers:</p> <pre><code>index | col 0 | [106.43477116337492, 6.762679391732501, 0.0, 9... 1 | [106.43477116337492, 6.58742122158056, 0.0, 9.... 2 | [106.22211427793361, 7.303693743071101, 0.0, 9... 3 | [106.43477116337492, 7.955196940...
<p>You can 'spread' the column with arrays values using <code>to_list</code>, then rebuild a dataframe, with if needed a prefix. And (eventually) get rid of the original column.</p> <p>Assuming your dataframe column with arrays values is named <code>'array'</code>:</p> <pre><code>dfs = (df.join(pd.DataFrame(df['array']...
python|arrays|pandas
2
958
70,693,018
Getting the rolling.sum of row values with irregular time intervals
<p>I am trying to get the rolling.sum of my time series. However, the rows have varying time intervals (see below my df_water_level_US1 dataframe):</p> <pre><code> DATE TIMEREAD WATERLEVEL(M) DateAndTime 0 01/01/2016 0:00:15 0.65 01/01/2016 0:00:15 1 01/01/2016 0:10:14 0.65 01/01/2016 0:10:14 2 ...
<p>Try:</p> <pre><code>df_water_level_US1['DateAndTime'] = pd.to_datetime(df_water_level_US1['DateAndTime']) final_1D = df_water_level_US1.resample('D', on='DateAndTime')['WATERLEVEL(M)'].sum() print(final_1D.reset_index()) # Output DateAndTime WATERLEVEL(M) 0 2016-01-01 3.24 </code></pre> <p>The first ...
python|pandas|datetimeindex|rolling-sum
2
959
42,948,748
How to "iron out" a column of numbers with duplicates in it
<p>If one has the following column:</p> <pre><code>df = pd.DataFrame({"numbers":[1,2,3,4,4,5,1,2,2,3,4,5,6,7,7,8,1,1,2,2,3,4,5,6,6,7]}) </code></pre> <p>How can one "iron" it out so that the duplicates become part of the series of numbers:</p> <pre><code>numbers new_numbers 1 1 2 2 3 3 4 ...
<p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a> by <code>Series</code> created with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow nor...
python|pandas|dataframe
1
960
42,600,915
Create a new DataFrame adding each key from a column dict as header
<p>I have a DataFrame which contains a certain column with Dictionaries.</p> <p>I want to add a new header in the DataFrame for each key found on each element in the column that contains dicts, each new value assigned to those new cells should correspond to <code>None</code> if that element doesn't contain that header...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with <code>DataFrame</code> constructor for replace <code>dict</code> to columns:</p> <pre><code>print (pd.DataFrame(df.dict_info.values.tolist())) elm1 elm2 el...
python|pandas|dictionary|dataframe|multiple-columns
1
961
42,913,138
Avoid collision in importing data in R
<p>I faced an error trying to import a CSV into R which had multiple duplicate columns, is there a way I can ignore those columns? It's easy to do that in case of small files and small number of columns but mine is a big one ~3k columns and 10M rows.</p>
<p>Alternatively, set the check.names arg to FALSE. </p>
r|rstudio|h2o|import-from-csv|sklearn-pandas
2
962
42,678,993
Merging only certain columns in Python
<p>I have two data frames I would like to merge. The Main Data Frame is Population</p> <pre><code>Pop: Country Name Country Code Year Population CountryYear 0 Aruba ABW 1960 54208.0 ABW-1960 1 Andorra AND 1960 13414.0 AND-1960 </code...
<p>A solution is to use the Country Code as index and then use pandas concat function (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html</a>):</p> <pre><code>Pop = Pop.set_index('Country ...
python|pandas|merge
1
963
42,759,401
Numpy horizontal concat with failure
<p>I want to concatenate two numpy arrays with the shape <code>(100,3) and (100,7)</code> to get a <code>(100,10)</code> matrix.</p> <p>I've tried it using <code>hstack, concatenate</code> but only receives a <code>ValueError: all the int arrays must have same number of dimensions</code></p> <p>In a dummy example lik...
<p>If you want to concatenate it vertically <code>axis</code> must beequal to 0. This is explained in <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer">the doc for concatenate</a>.</p> <p>In this link we have this example:</p> <blockquote> <blockquote> ...
python|arrays|numpy|concatenation
0
964
30,735,728
How to multiply 3 matrices using shared memory in Python?
<p>I want to multiply 3 matrices (like E = AxBxC) using shared memory in multiprocessing method. I can do it with 2 matrices but when I want to repeat the same procedure for the third matrix, I got stuck and don't know how to handle the shared array. I know I must use the multiprocessing array but don't know how to man...
<p>Just use <code>numpy</code> with an optimized BLAS (e.g. OpenBLAS, BLAS ATLAS, MKL) that supports multi-threading. </p> <p>Matrix multiplication will be parallelized, and because it includes extensive architecture dependent optimizations, this approach will be faster than explicitly managing shared memory in Pytho...
python|numpy|matrix|multiprocessing
0
965
30,559,552
Comparison between one element and all the others of a DataFrame column
<p>I have a list of tuples which I turned into a DataFrame with thousands of rows, like this:</p> <pre><code> frag mass prot_position 0 TFDEHNAPNSNSNK 1573.675712 2 1 EPGANAIGMVAFK 1303.659458 ...
<p>If I'm understanding correctly (not sure if I am), you can accomplish quite a bit by just sorting. First though, let me adjust the data to have a mix of close and far values for mass:</p> <pre><code> Unnamed: 0 frag mass prot_position 0 0 TFDEHNAPNSNSNK 1573.675712 ...
python|pandas
2
966
30,410,821
Save vars pr iteration to df and when done save df to csv
<p>I need to make a DataFrame (df_max_res) with the 15 best performances from my stock strategies combined with company tickers (AAPL for Apple Computers etc.). I have a list of more than 500 stock tickers that I fetch and on which I analyze using four of my own strategies.</p> <p>In the <code>for eachP in perf_array<...
<p>Finally I managed to come up with the right answer to my worries.</p> <p>I solved it this way:</p> <p>Before the for loops:</p> <pre><code># Creating the df that will save my results in the backtest iterations cols = ('Strategy','Ticker','ROI') # ,'Sharpe R','VaR','Strat' df_res = pd.DataFrame(columns = cols) </...
python|csv|pandas|dataframe
0
967
26,805,434
Saving numpy array into dictionary using loop
<p>Below is my loop to loop through a bigger array (sortdata), pull out individual columns, and save those into a dictionary based on its iteration in the loop. My problem is that this loop is only looping through and saving just one column. It saves the variabledict[1] array and nothing else. The sortdata array con...
<p>Place <code>variabledict = {}</code> outside loop. It is clearing <strong>dictionary</strong> values to <strong>Null</strong> on every iteration leaving only values of the last iteration.</p>
python|arrays|for-loop|numpy|dictionary
1
968
19,386,437
Python - create mask of unique values in array
<p>I have two numpy arrays, <code>x</code> and <code>y</code> (the length are around 2M). The <code>x</code> are ordered, but some of the values are identical.</p> <p>The task is to remove values for both <code>x</code> and <code>y</code> when the values in <code>x</code> are identical. My idea is to create a mask. He...
<p>I believe the fastest method is to compare <code>x</code> using numpy's <code>==</code> array operator:</p> <pre><code>idx = x[:-1] == x[1:] </code></pre> <p>On my machine, using <code>x</code> with a million random integers in [0, 100],</p> <pre><code>In[15]: timeit idx = x[:-1] == x[1:] 1000 loops, best of 3: 1...
python|performance|optimization|numpy|mask
3
969
19,394,328
Installing Numpy and matplotlib on OS X 10.8.5
<p>So I've been trying to install matplotlib and numpy on my Mac OS X 10.8 for two days straight now. Just can't seem to get them up and running. I get all sorts of errors. I finally managed to install numpy 1.5 then when I install matplotlib with "pip install matplotlib==1.0.1", I get an error after some progress thro...
<p>Another (even simpler) option than Canopy and Anaconda, is just to download Spyder's <a href="http://spyderlib.googlecode.com/files/spyder-2.2.5.dmg" rel="nofollow">dmg</a>, which comes with the latest versions of Numpy, SciPy, matplotlib, Pandas, Sympy and the sci-kits. This is a pure drag and drop installer (like ...
python|macos|numpy|matplotlib
0
970
29,028,213
Coincidence matrix from array with clusters assignments
<p>I have an array containing the cluster assigned to every point.</p> <pre><code>import numpy as np cluster_labels = np.array([1,1,2,3,4]) </code></pre> <p>How can I get a matrix like:</p> <pre><code>1 1 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 </code></pre> <p>I'm sure there is something clever than:</p>...
<p>It's difficult to say whether what your doing is the best way to tackle the problem without knowing more about the problem itself.</p> <p>However, it is possible to get the matrix your looking for in far less code:</p> <pre><code>x = np.array([1,1,2,3,4]) (x[None,:] == x[:,None]).astype(int) </code></pre> <p>Conc...
python|numpy
1
971
23,705,107
Cython 1D normalized slidding cross correlation Optimization
<p>I have the following code which does a normalized cross correlation looking for similarities in two signals in python:</p> <pre><code>def normcorr(template,srchspace): template=(template-np.mean(template))/(np.std(template)*len(template)) # Normalize template CCnorm=srchspace.copy() CCnorm=CCnorm[np.shape(template)...
<p>Because you call numpy functions in a cython loop, there will be no speed improvement.</p> <p>If you use pandas, you can use <code>roll_mean()</code> and <code>roll_std()</code> and <code>convolve()</code> in numpy to do the calculation very fast, here is the code:</p> <pre><code>import numpy as np import pandas a...
numpy|cython
3
972
15,419,914
Downsampling irregular time series in pandas
<p>I have a time series in pandas that looks like this:</p> <pre> <code> 2012-01-01 00:00:00.250000 12 2012-01-01 00:00:00.257000 34 2012-01-01 00:00:00.258000 45 2012-01-01 00:00:01.350000 56 2012-01-01 00:00:02.300000 78 2012-01-01 00:00:03.200000 89 2012-01-01 00:00:03.500000 90 2012-01-01 00:0...
<p>Create a DateTimeIndex a frequency of 1 second and an offset of a quarter-second like so.</p> <pre><code>index = pd.date_range('2012-01-01 00:00:00.25', '2012-01-01 00:00:04.25', freq='S') </code></pre> <p>Conform your data to this index, and "fill forward" to downsample the way you show in ...
python|pandas
5
973
29,533,268
Find density of points from their scatter plot in python
<p>Can I go through equal boxed areas in the scatter plot, so I can calculate how many there are on average on each box? Or, is there a specific function in python to calculate this? I don't want a colored density plot, but a number that represents the density of these points in the scatter plot.</p> <p>Here is for exa...
<pre><code>from scipy import linalg as la e = la.eigvals(my_matrix) hist,xedges,yedges = np.histogram2d(e.real,e.imag,bins=40,normed=False) </code></pre> <p>So in this case, 'hist' would be a 40x40 array (since bins=40). Its elements are the number of eigenvalues for each bin.</p> <p>Thanks to @jepio and @plonser for...
python|python-2.7|numpy|matplotlib
1
974
29,442,370
How to correctly read csv in Pandas while changing the names of the columns
<p>An absolute basic read_csv question. </p> <h2>I have data that looks like the following in a csv file -</h2> <pre><code>Date,Open Price,High Price,Low Price,Close Price,WAP,No.of Shares,No. of Trades,Total Turnover (Rs.),Deliverable Quantity,% Deli. Qty to Traded Qty,Spread High-Low,Spread Close-Open 28-February-2...
<p>You are right, something is odd with the <code>name</code> attributes. Seems to me that you can not use both in the same time. Either you set the name for every columns of the CSV file or you don't set the name at all. So it seems that you can't set the name when you are not taking all the colums (<code>usecols</co...
python|csv|pandas
26
975
62,398,372
create unique identifier in dataframe based on combination of columns, but only for duplicated rows
<p>A corollary of the question here: <a href="https://stackoverflow.com/questions/62396518/create-unique-identifier-in-dataframe-based-on-combination-of-columns">create unique identifier in dataframe based on combination of columns</a></p> <p>In the foll. dataframe, </p> <pre><code> id Lat Lon Yea...
<p>You can use an <code>np.where</code>:</p> <pre><code>df['unique_id'] = np.where(df.duplicated(['Lat','Lon'], keep=False), df.groupby(['Lat','Lon'], sort=False).ngroup().astype('str') + '_' + df['State'], df['State']) </code></pre> <p>Or similar idea with <cod...
python|pandas
1
976
62,441,827
Imputation conditional on other column values - Titanic dataset Age imputation conditional on Class and Sex
<p>I am working on the Titanic dataset and want to impute for missing age values. I want to impute based on the Pclass and Sex - taking the average of all females in first class for missing female first class ages for example (obviously doing this for each class and both male and female).</p> <p>I feel like something ...
<p>check this source for learning imputation of values </p> <p>this article has helped me a lot</p> <p><a href="https://machinelearningmastery.com/handle-missing-data-python" rel="nofollow noreferrer">https://machinelearningmastery.com/handle-missing-data-python</a></p>
python|pandas|scikit-learn|sklearn-pandas
0
977
62,416,511
Preprocess text to feed in model trained on imdb dataset
<p>I've trained this model:</p> <pre><code>(training_eins,training_zwei),(test_eins,test_zwei) = tf.keras.datasets.imdb.load_data(num_words=10_000) training_eins = tf.keras.preprocessing.sequence.pad_sequences(training_eins,maxlen=200) test_eins = tf.keras.preprocessing.sequence.pad_sequences(test_eins,maxlen=200) mo...
<p>Figured it out:</p> <pre><code>buch = tf.keras.datasets.imdb.get_word_index() buch = {k:(v+3) for k,v in buch.items()} buch["&lt;PAD&gt;"] = 0 buch["&lt;START&gt;"] = 1 buch["&lt;UNK&gt;"] = 2 buch["&lt;UNUSED&gt;"] = 3 eingabe = re.sub(r"[^a-zA-Z0-9 ]", "", "very bad, I am truly disappointed") munition = [[((buch[...
python|tensorflow|text
0
978
62,166,591
unable to update the column to the excel file which is checkout from perforce
<p>i have a code where i was reading the Excel file from Perforce and storing it to the local.<br> then doing some other work like:<br> -- read all sheets <br> -- search for particular columns and extract that column data.<br> -- and from that data extract the other info from JIRA.<br> Till here its working fine so onc...
<p>Three things:</p> <ol> <li>When you get the file from Perforce, use <code>p4 sync</code> instead of <code>p4 sync -f</code>.</li> <li>After you <code>p4 sync</code> the file, <code>p4 edit</code> it. That makes it writable so that you can <em>edit</em> it.</li> <li>After you save your edits to the file, <code>p4 s...
python|pandas|openpyxl|perforce|python-jira
0
979
62,422,653
How can I use integer division (//) to access the middle rows and columns in numpy python
<p>Print "+" Description Given a single positive odd integer 'n' greater than 2, create a NumPy array of size (n x n) with all zeros and ones such that the ones make a shape like '+'. The lines of the plus must be present at the middle row and column.</p> <p>Hint: Start by creating a (n x n) array with all zeroes usin...
<p>index for middle row: n//2 index for middle column: n//2</p> <pre class="lang-py prettyprint-override"><code>import numpy as np def f(n): if n&lt;3: print('Argument must greater or equal 3 !') return middle = n//2 array = np.zeros((n, n), dtype=np.uint) array[middle] = 1 array[...
python|numpy
0
980
62,046,027
Creating arrays with a loop (Python)
<p>I am trying to create several arrays from a big array that I have. What I mean is: </p> <pre><code>data = [[0, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [0, 0, 1, 1, 0, 0, 0, 0, 0,1], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0...
<p>Use numpy array index:</p> <pre><code>data = [[0, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [0, 0, 1, 1, 0, 0, 0, 0, 0,1], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, ...
python|numpy
1
981
62,193,877
Keras .fit giving better performance than manual Tensorflow
<p>I'm new to Tensorflow and Keras. To get started, I followed the <a href="https://www.tensorflow.org/tutorials/quickstart/advanced" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/quickstart/advanced</a> tutorial. I'm now adapting it to train on CIFAR10 instead of MNIST dataset. I recreated this model ...
<p>Mentioning the solution here (Answer Section) even though it is present in the Comments, for the <strong>benefit of the Community</strong>.</p> <p>On the same <code>Dataset</code>, the Accuracy can differ when using <code>Keras Model.fit</code> with that of the <code>Model</code> built using <code>Tensorflow</code>...
python|tensorflow|keras|deep-learning
0
982
51,152,108
Pandas add a series to dataframe column
<p>I'm trying to add a series as a new column in another data frame. But only 'NaN' is being added.</p> <p>Series:</p> <pre><code>a_attack = df.merge(df_2,left_on = ['team_A','year'],right_on =['countries','year_list'],how = 'left')['attack'] type(a_attack) Out[4]: pandas.core.series.Series a_attack.tail(5) Out[5]:...
<p>Try this:</p> <pre><code>df['A_attack'] = a_attack.values </code></pre>
python|python-3.x|pandas
0
983
48,215,207
OpenCV 3.4.0.12 with Python3.5 AttributeError: 'cv2.VideoCapture' object has no attribute 'imread'
<p>I'm trying out facial recognition for the first time with python 3.5 and OpenCV 3.4.0.12 and I get this error when I run my code.</p> <pre><code> File "/Users/connorwoodford/anaconda3/envs/chatbot/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile exec(compile(f.read(), file...
<p>Your eye_cascade is referring to wrong cascade file, it should end with .xml extension. You can download it from here <a href="https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_eye.xml" rel="nofollow noreferrer">haarcascade_eye.xml</a>.</p> <p>Also note that your call to cv2.rectangle is no...
python|numpy|opencv|face-recognition
0
984
48,108,909
How to create array with initial value and 'decay function'?
<p>I'm looking for a more efficient way to compute this (searched for something similar to numpy's arange):</p> <pre><code>R = 0 l1 = [] gamma = 0.99 x = 12 for i in range(0, 1000): R = x - (1-gamma) * R l1.append(R) </code></pre> <p>the iteration and appending are too slow </p>
<p>You can get an easy factor of 3 if you JIT the function using <a href="http://numba.pydata.org" rel="nofollow noreferrer">Numba</a>:</p> <p><a href="https://i.stack.imgur.com/NuPpT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NuPpT.png" alt="Numba JIT"></a></p> <p>You should also explore Nump...
python|numpy
1
985
48,390,671
SyntaxError: (unicode error) while using pd.read_table for a txt file
<p>I am reading a txt file with a pattern into Pandas:</p> <pre><code>Alabama[edit] Auburn (Auburn University)[1] Florence (University of North Alabama) Jacksonville (Jacksonville State University)[2] Livingston (University of West Alabama)[2] Montevallo (University of Montevallo)[2] Troy (Troy University)[2] Tuscaloo...
<p>It seems you need to set correct encoding to load the file.</p> <p>Try </p> <pre><code>df = pd.read_table('file path', sep='\n', header=None, encoding='utf-8') </code></pre> <p>or </p> <pre><code>df = pd.read_table('file path', sep='\n', header=None, encoding='WINDOWS-1252') </code></pre> <p>If it still doesn'...
python|pandas|unicode
0
986
48,443,203
Tensorflow GetNext() failed because the iterator has not been initialized
<p>tensorflow recommends the tf.data.Dataset for importing data. Is it possible to use it for validation and training, if the validation size of the images is different to the training images?</p> <pre><code>import tensorflow as tf import generator import glob import cv2 BATCH_SIZE = 4 filenames_train = glob.glob("/h...
<p>You've just forgot to initialize the <code>validation_iterator</code>.</p> <p>Just add <code>sess.run(validation_iterator.initializer)</code> before running the for-loop. </p>
python|tensorflow
15
987
48,593,065
TensorFlow - Dynamic Input Batch Size?
<p>In my case, I need to dynamically change the batch_size during training. For example, I need to double the batch_size for every 10 epochs. However, the problem is that, although I know how to make it dynamic, in <strong><em>input pipeline</em></strong> I have to determine the batch size, as the following code shows....
<p>I believe what you want to do is the following (I haven't tried this, so correct me if I make a mistake).</p> <p>Create a placeholder for your batch size:</p> <pre><code>batch_size_placeholder = tf.placeholder(tf.int64) </code></pre> <p>Create your shuffle batch using the placeholder:</p> <pre><code>images = tf....
python|tensorflow
0
988
70,778,928
Get value from previous column for each group in groupby
<p>This is my <code>df</code> -</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Site</th> <th>Product</th> <th>Period</th> <th>Inflow</th> <th>Outflow</th> <th>Production</th> <th>Opening Inventory</th> <th>New Opening Inventory</th> <th>Closing Inventory</th> <th>Production Needed</th> </t...
<p>Your New Opening Inventory is always previous Closing Inventory.</p> <p>So I can modify this formula</p> <blockquote> <p>Closing Inventory = Production + Inflow + New Opening Inventory - Outflow</p> </blockquote> <p>to</p> <blockquote> <p>Closing Inventory = Production + Inflow + Previous Closing Inventory - Outflow...
python|pandas|dataframe|pandas-groupby
1
989
70,831,040
pandas retain values on different index dataframes
<p>I need to merge two dataframes with different frequencies (daily to weekly). However, would like to retain the weekly values when merging to the daily dataframe.</p> <p>There is a grouping variable in the data, <code>group</code>.</p> <pre><code>import pandas as pd import datetime from dateutil.relativedelta import...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a> with sorting values by datetimes, last sorting like original by both columns:</p> <pre><code>daily_data['date'] = pd.to_datetime(daily_data['date']) weekly_data['date']...
pandas|pandas-groupby
2
990
71,075,202
Read spark csv dataframe as pandas
<p>After processing a big data on pyspark, I saved it on csv using the following command:</p> <pre><code>df.repartition(1).write.option(&quot;header&quot;, &quot;true&quot;).option(&quot;delimeter&quot;, &quot;\t&quot;).csv(&quot;csv_data&quot;, mode=&quot;overwrite&quot;) </code></pre> <p>Now, I want use <code>pd.read...
<p>The csv format writer method <strong>DOESN'T</strong> have the <code>delimeter</code> option, guess what you need is the <code>sep</code> option.</p> <p>Please refer to <a href="https://spark.apache.org/docs/latest/sql-data-sources-csv.html#data-source-option" rel="nofollow noreferrer">here</a></p>
python|pandas|dataframe|pyspark
0
991
51,664,482
Python Pandas Create unique dataframe out of many lists
<p>Hi I want to create a dataframe that stores a unique variable and its average in every column. Currently I have a dataframe that has 2 columns. One has a list of names while the other has a single value. I want to associate that value with all of the names in the list and eventually find the average value for all th...
<p>IIUC flatten your list (unnest)</p> <pre><code>pd.DataFrame(data=df.cost_col.repeat(df.names_col.str.len()).values,index=np.concatenate(df.names_col.values)).mean(level=0) Out[221]: 0 milk 4 eggs 3 cookies 5 water 5 yogurt 6 diaper 7 </code></pre>
python|pandas|dataframe
1
992
51,835,891
Correlation of Groups and joining to DataFrame
<pre><code>import pandas as pd d = {'Val1': ['A','A','A','B','B','B','C','C','C','D','D','D'], 'Val2': [5,4,6,4,8,7,4,5,2,1,1,9] , 'Val3': [4, 5,6,1,2,9,8,5,1,5,9,5]} df = pd.DataFrame(data=d) df </code></pre> <h3>Output</h3> <pre><code>Val1 Val2 Val3 Val4+++ 0 A 5 4 1 A 4 5 2 A 6 6 3 B 4 1 4...
<p>You can shorten the correlation code a bit by doing the correlation on the series:</p> <pre><code>df.groupby("Val1")["Val2"].corr(df["Val3"]) </code></pre>
python|pandas|group-by|correlation
0
993
51,617,211
Numpy Standard Deviation AttributeError: 'Float' object has no attribute 'sqrt'
<p>I know this was asked many times, but, I am still having trouble with the following problem. I defined my own functions for mean and stdev, but stdev takes too long to calculate std(Wapproxlist). So, I need a solution for the issue.</p> <pre><code>import numpy as np def Taylor_Integration(a, b, mu): import symp...
<p><code>numpy</code> doesn't know how to handle <code>sympy</code>'s <code>Float</code> type.</p> <pre><code>(Pdb) type(Wapproxlist[0]) &lt;class 'sympy.core.numbers.Float'&gt; </code></pre> <p>Convert it to a numpy array before calling <code>np.mean</code> and <code>np.std</code>.</p> <pre><code>Wapproxlist = np.a...
python|python-2.7|numpy
12
994
42,086,185
How to differenciate columns which are same in all rows from pandas dataframe?
<p>I have one dataframe like below - </p> <pre><code>df1_data = {'sym' :{0:'AAA',1:'BBB',2:'CCC',3:'DDD',4:'DDD',5:'CCC'}, 'id' :{0:'101',1:'102',2:'103',3:'104',4:'105',5:'106'}, 'sal':{0:'1000',1:'1000',2:'1000',3:'1000',4:'1000',5:'1000'}, 'loc':{0:'zzz',1:'zzz',2:'zzz',3:'zzz',4:'zzz',5:'zz...
<p>You can compare <code>df</code> with first row by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>eq</code></a> and then check all <code>True</code> values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.h...
python|pandas
3
995
41,724,432
ML - Getting feature names after feature selection - SelectPercentile, python
<p>I have been struggling with this one for a while. My goal is to take a text feature that I have, and find the best 5-10 words in it to help me classify. Hence, I am running a TfIdfVectorizer, and choosing ~90 best for now. however, after I downsize the feature amount, I am unable to see which features were actually ...
<ul> <li>selector.get_support() to get you a boolean array of columns that were within the percentile range you specified</li> <li>train.columns.values should get you the complete list of column names for the original dataframe</li> <li>filtering the latter with the former should give you the names of columns that make...
python|numpy|machine-learning|scikit-learn|feature-extraction
1
996
64,265,621
How to do slicing in pandas Series through elements instead of indices in case they are similar
<p>I have pandas Series like:</p> <pre><code>s = pd.Series([1,9,3,4,5], index = [1,2,5,3,9]) </code></pre> <p>How can I obtain, say, element <code>'3'</code>? Given that I do not know exact elements in advance. I need to write a function that gets, say, first element of the Series.</p> <p>series[2] understands it like...
<p>Like this, using boolean indexing:</p> <pre><code>s[s==3] </code></pre> <p>Given:</p> <pre><code>s = pd.Series([1,9,3,4,5], index = [1,2,5,3,9]) </code></pre> <p>Let's find elements 3 and 9, use:</p> <pre><code>s[s.isin([9,3])] </code></pre> <p>Output:</p> <pre><code>2 9 5 3 dtype: int64 </code></pre> <h1>Upda...
python|pandas
0
997
64,263,685
replace dataframe column values with values from an other dataframe column
<p>Let me explain my problem a bit more. I have a dataframe with ID, name and surname, let's call him df_src ex :<br /></p> <pre><code>ID Name Surname 177015H LAURE Thomas 198786X ANGEARD Audrey 136235G EYSSERIC Laurent 198786X ANGEARD Audrey </code></pre> <p>In this dataframe i have m...
<p>I would merge both and then rename the columns:</p> <pre><code>df = df_src.merge(df_tem, on=[&quot;ID&quot;, &quot;Name&quot;, &quot;Surname&quot;], how=&quot;left&quot; ).drop(columns=[&quot;ID&quot;, &quot;Name&quot;, &quot;Surname&quot;] ).rename(columns={&quot;FakeID&quot;: &quot;ID&quot;, &quot;FakeName...
python|pandas
0
998
64,574,222
Accuracy and loss does not change with RMSprop optimizer
<p>The dataset is CIFAR10. I've created a VGG-like network:</p> <pre><code>class FirstModel(nn.Module): def __init__(self): super(FirstModel, self).__init__() self.vgg1 = nn.Sequential( nn.Conv2d(3, 16, 3, padding=1), nn.BatchNorm2d(16), nn.ReLU(), nn....
<p>try to decrease the learning rate more .....if then also there is no affect on the accuracy and loss then change the optimizer to adams or something else and play with different learning rates.</p>
python|pytorch|vgg-net|rms|sgd
1
999
64,229,511
How to write tensorflow events to google cloud storage from Docker container inside VM instance
<p>I've created a VM instance on Google Compute Engine. After uploading my project and building my image, I ran into my container and authorized access to Google Cloud Platform with my service account:</p> <pre><code>gcloud auth activate-service-account test@xxx.iam.gserviceaccount.com --key-file=mykey.json </code></pr...
<p>Authenticating <code>gcloud</code> just ensures that future <code>gcloud</code> commands are authenticated. Your script (likely) doesn't use <code>gcloud</code> and thus isn't authenticated.</p> <p>Instead, if you have service account credentials in a JSON file, you can specify it via the <code>GOOGLE_APPLICATION_CR...
python|authentication|google-cloud-platform|google-cloud-storage|tensorflow2.0
1