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
356,400
66,265,345
Interaction between numpy arrays of pyOpenCL vector types and numpy arrays of floats
<p>I find it quite convenient to use both structs and np.ndarrays using dtypes like pyopencl.cltypes.float2. This is a clear and self documenting way to pass structured data to my kernels, as opposed to just a bunch of floats.</p> <p>However I find certain behavior inconvenient. For example given:</p> <pre><code>import...
<pre><code>In [99]: a=np.array([[(0., 0.), (0., 0.), (0., 0.), (0., 0.), (0., 0.)], ...: [(0., 0.), (0., 0.), (0., 0.), (0., 0.), (0., 0.)], ...: [(0., 0.), (0., 0.), (0., 0.), (0., 0.), (0., 0.)]], ...: dtype=[(('x', 's0'), '&lt;f4'), (('y', 's1'), '&lt;f4')]) In [100]: a.dtype Out[100...
numpy|pyopencl
0
356,401
65,923,114
Find duplicate values in two arrays, Python
<p>I have two arrays (A and B) with about 50 000 values in each. Every value represents an ID. I want to create a pandas dataframe with three columns, col1: values from array A, col2: values from array B, col3: a string with the labels &quot;unique&quot; or &quot;duplicate&quot;. In each array the ID:s are unique.</p> ...
<p>For finding duplicate elements in two arrays, use <code>numpy.intersect1d</code>:</p> <pre><code>In [458]: a = np.array([1, 2, 3, 4, 5]) In [459]: b = np.array([5, 6, 7, 8, 9, 10]) In [462]: np.intersect1d(a,b) Out[462]: array([5]) </code></pre>
python|pandas|numpy
2
356,402
66,239,065
How to improve the model's accuracy?
<p>I am definitely a new beginner of tensorflow, I tried to create a simple model, but the accuracy is super low, can someone help to figure out what is wrong?</p> <pre><code>from tensorflow.keras.layers import Dense from tensorflow.keras.models import Sequential train_x = [[i, j] for i in range(1000) for j in range(1...
<p>There are few ways to improve your model's accuracy</p> <ul> <li>Reduce the batch size (You are using whole dataset)</li> <li>Increase the number of layers, units.</li> <li>Increase the number of epochs.</li> <li>Use unseen data to evaluate the model. (You are using 60 elements of training data)</li> </ul> <p>I sugg...
tensorflow|machine-learning|keras|deep-learning
1
356,403
66,014,520
How to iterate and change all elements of a numpy array?
<p>I am working on a machine learning task and trying to convert all strings in a set of data to floats using <code>hash()</code> to do this I need to iterate over all the elements of a numpy array whilst not knowing if it is a 2D 3D or 4D array and then change each element. Is there any way to do this without using ne...
<p>You can try <code>numpu.vectorize</code>, already mentioned <a href="https://stackoverflow.com/questions/43024745/applying-a-function-along-a-numpy-array">here</a></p> <p>Note: <code>The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.</code...
python|arrays|numpy
0
356,404
66,318,181
AttributeError: 'numpy.ndarray' object has no attribute 'score' error
<p>I have tried to look for a problem but there is nothing Im seeing wrong here. What could it be? This is for trying binary classification in SVM for the fashion MNIST data set but only classifying 5 and 7.</p> <pre><code>import pandas as pd import numpy as np import seaborn as sns from sklearn.linear_model import Log...
<p>ypred is an array of predicted class labels, so the exception makes sense.</p> <p>What you should do is use the classifier’s score method:</p> <pre><code>svclassifier = SVC(kernel='rbf', C=1) svclassifier.fit(xtrain, ytrain) # ypred = svclassifier.predict(xtest) # We don’t actually use this. print(svclassifier.sco...
python|pandas|scikit-learn
2
356,405
66,029,426
Anaconda showing this error , can't train model properly
<pre><code>2021-02-03 19:46:53.571084: W tensorflow/stream_executor/gpu/redzone_allocator.cc:314] Internal: Invoking GPU asm compilation is supported on Cuda non-Windows platforms only Relying on driver to perform ptx compilation. Modify $PATH to customize ptxas location. This message will be only logged once. </code><...
<p>I met the same problem, my TensorFlow version is 2.4.1. with Python 3.9, and cuda 10.1. Luckily, I found a solution by installing the following package,</p> <pre><code>conda install -c conda-forge cudatoolkit-dev </code></pre> <p>The original link is <a href="https://github.com/tensorflow/tensorflow/issues/40036" re...
python|tensorflow
2
356,406
66,073,142
Bazel targets built against TensorFlow C++ API don't execute factory registration functions
<p>I am encountering an issue that seems to be identical to the one described here: <a href="https://chromium.googlesource.com/external/github.com/tensorflow/tensorflow/+/v1.4.0/tensorflow/docs_src/mobile/linking_libs.md#global-constructor-magic" rel="nofollow noreferrer">https://chromium.googlesource.com/external/gith...
<p><code>--whole-archive</code> does not work in this case. Whole purpose of this flag is to link everything from a <strong>static</strong> library (<code>*.a</code> in linux). Shared library by default contains all of the compiled code, so you do not that trick, because you are using <code>*.so</code> file.</p> <p>Per...
c++|tensorflow|linker|bazel
1
356,407
66,138,100
Pandas resample by day without filling missing dates
<p>I have a dataset with several date fields including hours. I want to use one of them as my df index, and count the number of entries which where created each day. In other words, if I have:</p> <pre><code>Date | Several features 2020-02-08 10h00 | ... 2020-02-08 11h00 | ... 2020-02-10 10h00 | ... 2020-02-10 11h00 | ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>Series.dt.date</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code><...
python|pandas
2
356,408
66,283,443
How to merge ReLU after quantization aware training
<p>I have a network which contains Conv2D layers followed by ReLU activations, declared as such:</p> <pre><code>x = layers.Conv2D(self.hparams['channels_count'], kernel_size=(4,1))(x) x = layers.ReLU()(x) </code></pre> <p>And it is ported to TFLite with the following representaiton:</p> <p><a href="https://i.stack.imgu...
<p>I have found a workaround which works by instantiating a non-trained version of the model, then copying over the weights from the quantization aware trained model before converting to TFLite.</p> <p>This seems like quite a hack, so I'm still on the lookout for a cleaner solution.</p> <p>Code for the workaround:</p> ...
tensorflow|tensorflow-lite|quantization-aware-training
1
356,409
66,130,970
In python pandas, how do i merge two dataframes while spreading values in one using weights of another?
<pre class="lang-py prettyprint-override"><code>import pandas as pd df1 = pd.DataFrame({'animal': {0: 'bird', 1: 'bird', 2: 'bird', 3: 'bird', 4: 'bird', 5: 'bird', 6: 'dog', 7: 'dog', 8: 'dog', 9: 'dog', 10: 'dog', 11: 'dog'}, 'cat1': {...
<p>You can use <code>groupby().transform()</code> in this case:</p> <pre><code>out = m.groupby(['animal', 'cat1', 'cat2']).sum() out['val3'] = out['val2']*out['val1'] / out.groupby(['animal','cat1'])['val1'].transform('sum') </code></pre> <p>Output:</p> <pre><code> val1 val2 val3 animal cat1 cat2...
python|pandas|merge
2
356,410
65,997,350
how to make a group from different columns based on a condition?
<p>I have a dataframe which looks like this :</p> <pre><code> Air-line City Time ID 0 easyJet London 20:40 1 1 airberlin Berlin 10:30 2 2 Emarite Dubai 21:45 3 3 Qatar Airways Newyork 10:30 4 4 easyJet London ...
<p>You can categorize the <code>time</code> column with a 6 min step as shown below. I use here <code>pandas.cut</code> function. As <code>bins</code> I pass a range of datetime objects retrieved from <code>pd.date_range</code>. In <code>pd.cut</code> I use <code>right=False</code> to include points on the left side on...
python|pandas|conditional-statements|pandas-groupby
0
356,411
66,337,474
How to subtract two date columns and the result being a positive integer only
<pre><code> Employee ID Name Leave From Leave To Leave Days 10107 Habib 2020-10-31 2020-01-11 -293 days +00:00:00 </code></pre> <p>I want to extract the total no. of leave days for every employee by subtracting Leave To column from Leave From column. This works well for most of the cases and r...
<p>Try <code>clip</code>:</p> <pre><code>df['Leave Day'] = df['Leave To'].sub(df['Leave From']).clip(0) </code></pre>
python|pandas|dataframe|datetime|timedelta
0
356,412
65,930,594
pandas first_valid_index() as integer key
<p>I have a pandas dataframe with an index as a date string like so: '2015-07-15'</p> <p>and another column along side it with a value associated with the dates.</p> <p>When I use to find out when the column first time equals 5:</p> <pre><code>df[df['Column'] == 5].first_valid_index() </code></pre> <p>it gives me back<...
<p>You need to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer">reset_index</a> before so that you can get your integer index.</p> <pre><code>df.reset_index(inplace=True) df[df['Column'] == 5].first_valid_index() </code></pre> <p>Alternate ...
python-3.x|pandas
0
356,413
66,034,617
Calculate cumprod based on condition pandas dataframe python
<p>Sample dataframe is as follows:-</p> <pre><code>import pandas as pd import numpy as np from datetime import datetime start = datetime(2011, 1, 1) end = datetime(2012, 1, 1) index = pd.date_range(start, end) df = pd.DataFrame(np.random.randn(366, 1), index=index, columns=[&quot;Returns&quot;]) </code></pre> <p>I kno...
<p>Use your original formula, but only for rows with <em>bool == 1</em>. To do it, instead of <em>df</em> use <em>df[df['bool'] == 1]</em>. So the whole instruction can be:</p> <pre><code>df['CumProd2'] = start * (1 + df[df['bool'] == 1].Returns).cumprod() </code></pre> <p>Values for <em>bool == 0</em> are left as <em>...
python|pandas|dataframe
1
356,414
66,300,658
Read first data of a row and add manually a tag in another column and continue
<p>I have a data frame like below in python, I want to read each row and at the same time write a tag for it in the in another column, for example I read the first text and manually I write neg in the col tag and so on. can any one help me?</p> <pre><code> text tag 1 &quot;bad&quot; neg 2 &quo...
<p>Firstly you need to create the &quot;tag&quot; column, if it doesn't already exist:</p> <p><code>df[&quot;tag&quot;] = &quot;&quot;</code></p> <p>Then go through the lines, print &quot;text&quot; and enter the corresponding tag:</p> <pre><code>for i, row in df.iterrows(): print(row['text']) tag = input(&quot...
python|pandas
1
356,415
66,308,158
Iterating through a numpy array /matrix and storing it in a seperate array
<p>I have a matrix/numpy array A and need to carry out a function f to all elements and then store the result in a matrix B. How would I do this, I'm thinking of appending an empty array of B as I go on but is this the best way of doing it?</p>
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html" rel="nofollow noreferrer"><code>numpy.vectorize</code></a>:</p> <pre><code>A = np.arange(9).reshape((3,3)) #array([[0, 1, 2], # [3, 4, 5], # [6, 7, 8]]) my_func = lambda x: x + 1 #Example function vect_func = np....
python|numpy|for-loop
0
356,416
66,245,636
How to create a ones of specific shape in tensorflow?
<p>I need to create a ones of shape (200,240,2). For an example, in numpy I can do:</p> <pre><code>r = numpy.ones_like(x) # x shape is (200,240,2) r[...,0] = 0 r[...,1] = 1.57 </code></pre> <p>How can I do it in tensorflow?</p> <p>Could anyone help me with this?</p>
<p>You can't do indexing and assignment at the same time in tensorflow, but otherwise, you can do the same things than in numpy. Here's one way to replicate your numpy code:</p> <pre><code>x_shape = x.shape r0 = tf.zeros(x_shape[:-1]) r1 = tf.ones(x_shape[:-1]) + 0.57 r = tf.stack([r0,r1],axis=-1) </code></pre> <p>If y...
python|tensorflow
2
356,417
65,912,247
How can I optimize this majority vote
<p>I have the following code to do a majority vote for data in a dataframe:</p> <pre><code>def vote(df, systems): test = df.drop_duplicates(subset=['begin', 'end', 'case', 'system']) n = int(len(systems)/2) data = [] for row in test.itertuples(): # get all matches fx = test.loc[...
<p>moving this to codereview... (don't want to delete it and lose reputation points!)</p>
python|pandas|optimization|iterable
0
356,418
66,217,586
Letter number combo to float in python
<pre><code>def computefeatures(node_id): return [ord(node_id), len(node_id)] </code></pre> <p>I am computing features for my node ids which are a combo of a letter and a number. ord will not work, is there another work around for this.</p> <p>my list is:</p> <pre><code>ln0 Out[88]: 0 C1 1 C2 2 C3 3 ...
<p>If your node consist of a single letter followed by an integer, and all you want to do is map them to floats, this can be done in various ways.</p> <p>One way is to convert your node_id into a hex string of the sort that is returned by the float method <code>hex</code> (for example, <code>(3.14).hex() = '0x1.91eb851...
python|pandas|networkx|stellargraph
0
356,419
66,086,553
Speed up the calculation of a new feature (a cycle about rows for a time and object)
<p>I have a dataframe with cars and their prices, where each row contains the price for which it was sold and the time of sale. I want to create a new feature that for each row will show the amount of sales for this car for the last 2 hours, multiplied by 0.2.</p> <pre><code>res = pd.DataFrame() for car in pd.unique(df...
<p>There is a very useful construct in <code>pandas</code> called &quot;Rolling GroupBy&quot; (<code>pandas.core.window.rolling.RollingGroupby</code>, obtained by <code>df.groupby(...).rolling(...)</code>).</p> <p>With some synthetic data containing 500K rows, I see execution times of about 135ms (a speedup of over 13,...
python|python-3.x|pandas|optimization|pandas-groupby
1
356,420
66,099,716
Create new Pandas Dataframe from observations which meets specific criteria
<p>I have two original dataframes. One contains limits: <code>df_limits</code></p> <pre><code> feat_1 feat_2 feat_3 target 12 9 90 UL 15 10 120 LL 9 8 60 </code></pre> <p>where target is ideal value, UL - upper limit, LL - lower limit</...
<p>Approach</p> <ul> <li>reshape</li> <li>merge</li> <li>calculate</li> </ul> <pre><code>new_df = (df_to_check.set_index(&quot;ID&quot;).unstack().reset_index() .rename(columns={&quot;level_0&quot;:&quot;column&quot;,0:&quot;value&quot;}) .merge(df_limits.T, left_on=&quot;column&quot;, right_index=True) .assign(devi...
python|pandas
1
356,421
66,214,951
How to deal with warning : "Workbook contains no default style, apply openpyxl's default "
<p>I have the -current- latest version of pandas, openpyxl, xlrd.</p> <p>openpyxl : 3.0.6.<br /> pandas : 1.2.2.<br /> xlrd : 2.0.1.</p> <p>I have a generated excel xlsx- file (export from a webapplication).<br /> I read it in pandas:</p> <pre><code>myexcelfile = pd.read_excel(easy_payfile, engine=&quot;openpyxl&quot;)...
<p>I don't think the library offers you a way to disable this thus you are going to need to use the warnings package directly.</p> <p>A simple and punctual solution to the problem would be doing:</p> <pre class="lang-py prettyprint-override"><code>import warnings with warnings.catch_warnings(record=True): warnings...
python|pandas|openpyxl
18
356,422
52,712,847
Plot large dataset with time
<p>I have a dataset with over 100k entries as per below:</p> <pre><code> score time 0 19 18 days 02:55:00 1 2949 1 day 01:20:11 2 42211 5 days 00:00:00 .... 100000 22 100 days 01:11:03 </code></pre> <p>I am trying to plot time on the x axis and score on the y axis as per below:</p...
<p>Have you tried looking at the following? <a href="https://stackoverflow.com/questions/29672375/histogram-in-matplotlib-time-on-x-axis">Histogram in matplotlib, time on x-Axis</a></p> <p>As indicated in the above link:</p> <p>Matplotlib uses its own format for dates/times, but also provides simple functions to conv...
python|pandas|matplotlib|large-data
0
356,423
52,812,815
What does keras normalize axis argument does?
<p>I am a beginner in deep learning and I am working upon the mnist dataset in keras.</p> <p>I used normalization as</p> <pre><code>tf.keras.utils.normalize(x_train, axis = 1) </code></pre> <p>I don't understand what does the axis argument means. Can you help me out with this?</p>
<p>The normalize function just performs a regular normalization to improve performance:</p> <blockquote> <p>Normalization is a rescaling of the data from the original range so that all values are within the range of 0 and 1.</p> </blockquote> <p>There is a nice explanation of the axis argument in another post:</p> <blo...
python|tensorflow|keras|deep-learning|mnist
6
356,424
52,761,376
How to map key to multiple values to dataframe column?
<p>I have a df column that looks like this: </p> <pre><code>col1 Non Profit Other-501c3 501c3 Sole Proprietor </code></pre> <p>How can I create a dictionary object or mapping layer(open to all suggestions) where I can pass any value if it matches criteria and changes to the key value? </p> <p>For example if the valu...
<p>Create dictionaries from <code>key</code>s, merge them and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="noreferrer"><code>map</code></a>:</p> <pre><code>L1 = ['Non Profit', 'Other-501c3', '501c3','NON-Profit', 'Not-for-profit'] d1 = dict.fromkeys(L1, 'non-profit') L2 ...
python|python-3.x|pandas|dictionary|series
13
356,425
52,658,915
How to split multi labelled dataset into many rows with each row having a single label?
<p>I have a Pandas DataFrame which looks like this?</p> <pre><code>Feature Class text1 [label1, label2] text2 [label2, label3] </code></pre> <p>What is the best way to do this?</p> <pre><code>Feature Class text1 label1 text1 label2 text2 label2 text2 label3 </code>...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow noreferrer"><code>numpy.repeat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.len.html" rel="nofollow noreferrer"><code>Series.str.len</code></a> and flatten li...
python|pandas|dataframe
1
356,426
52,689,905
Running standard deviation on multiindexed dataframe
<p>Is it possible to compute a running standard deviation (SD) on a multiindexed dataframe like this?</p> <pre><code> Value SD Symbol Date ABC 19APR2017 35.43 0.00 20APR2017 28.41 4.96 21APR2017 33.8 3.67 DEF 19APR2017 10 0.00 20APR2017 ...
<p>You can try of grouping the df with the index level 0 and use <code>pd.rolling</code> calculate standard deviation with specified length of rolling window</p> <pre><code>df.groupby(df.index.get_level_levels(0))['Value'].rolling(2).std() </code></pre> <p><strong>or</strong></p> <p>from @ayhan inputs</p> <pre><cod...
python|pandas|dataframe
2
356,427
52,591,265
plotting a pdf together with a histogram using plotnine in python
<p>I have the following data: </p> <pre><code>import pandas as pd from plotnine import * </code></pre> <p>gd_sp_tmp = pd.DataFrame({ 'variable': {0: 'var1', 1: 'var1', 2: 'var1', 3: 'var1', 4: 'var1', 5: 'var1', 6: 'var1', 7: 'var1', 8: 'var1', 9: 'var1', 10: 'var1', 11: 'var1', 12: 'var1...
<p>Use <code>stat_function</code>. For example, given your prior code, try this</p> <pre><code>import scipy.stats as stats (ggplot(data=gd_sp_tmp) + geom_histogram(aes(x='value')) + stat_function(fun=stats.lognorm.pdf, args=dict(s=.95, loc=0.8, scale=-0.5)) + facet_wrap('~variable') ) </code></pre> <p>It is up to...
python|python-3.x|pandas|plotnine
1
356,428
52,572,197
How do you stack pandas series 2D graphs into a 3D structure?
<p>I have some longitudinal data of 1 the weights of 115 patients structured in a dataframe. When I try to plot this however will, as suspected, all graphs be superpositioned on each other making it hardly comprehensible. </p> <p>Now i would like to graph the individual graphs for each patient NEXT to each other inste...
<p>Without seeing your data, I can't test this solution, but try switching what you're passing in as <code>y</code> and <code>z</code>. Something like:</p> <pre><code>ax.plot(xs=x, ys=i, zs=dfm.WOMEN.interpolate(method='linear', limit_area='inside').loc[:, i], zdir='z') </code></pre> <p>Also...
python|pandas|plot|3d|2d
1
356,429
52,794,819
Pandas excel to python for long column
<p>So I'm very new to python and I'm using Pandas to read an excel file, my file column is having 197 values to it, so when I read them with Pandas, I don't get all of the values " as shown in the picture"</p> <p>not the full excel sheet is appearing</p> <p><img src="https://i.stack.imgur.com/fIyEi.png" alt=""></p> ...
<p>Is your question to show those values? What you see is normal behavior. If you want see specific rows, try loc or iloc. </p>
python|excel|pandas
0
356,430
52,729,459
matplotlib stack bar grouped by date (month and year)
<p>Consider the over simplified data frame that has 2 columns: Dates and Values. </p> <pre><code>dates = pd.DatetimeIndex(['2017-01-01 00:00:00', '2017-01-05 02:00:00','2017-03-01 02:00:00', '2018-01-01 03:00:00', '2018-01-21 04:00:00','2018-03-01 03:00:00', '2018-03-22 04:00:00'], dtype='datetime64[ns]') my_df = pd.D...
<p>You need to first create the <code>pivot</code> table , then <code>plot</code> stack bar </p> <pre><code>my_df.Date=my_df.Date.dt.strftime('%Y-%m') my_df['col']=my_df.groupby('Date').cumcount() my_df.pivot(index='Date',columns='col',values='Values').plot(kind='bar',stacked=True) </code></pre> <p><a href="https://i...
python|pandas|matplotlib|plot|seaborn
1
356,431
52,743,613
Tensorflow data : apply function TO batch
<p>I'm using tf.data to iterate batch from large text corpus.</p> <p>I want to apply a function to only subset of data(or to subset of batch), not one by one element. Specifically, my data iterator yields <code>query, reply</code> with batch. They are all positive pairs, so I just want to shuffle only subset of next b...
<p>Assuming you have <code>queries</code> and <code>replies</code> as two Tensors. What you need is I think something like below what you can concatenate then with the original batch.</p> <pre><code>batch_size = 10 def reply_shuffle(queries, replies): shuffled_indices = tf.random_uniform(minval=0, maxval=batch_size...
python|tensorflow|tensorflow-datasets
0
356,432
52,533,345
Tensorflow - When using tf.contrib.layers.conv2d, can I set the name of the weights and biases?
<p>Tensorflow version: 1.10.1</p> <p>I want to transfer my learned weights and biases of the convolution layers in my pretrained network to a new network.</p> <p>However, because I used <code>conv2d</code> api, the weights and biases in the checkpoint file are automatically named as <code>Conv/weights</code>,<code>Co...
<p>For <a href="https://www.tensorflow.org/api_docs/python/tf/layers/Conv2D" rel="nofollow noreferrer">tf.layers.conv2d</a> and <a href="https://www.tensorflow.org/api_docs/python/tf/nn/conv2d" rel="nofollow noreferrer">tf.nn.conv2d</a> you can pass an additional parameter called <code>name</code>. </p> <p><strong>Exa...
python|tensorflow
2
356,433
52,625,998
Get beginning and end of range in array
<p>Suppose I have a signal, say, a sine wave:</p> <pre><code>x = np.arange(100) y = np.sin(x/10) </code></pre> <p>When I plot this, I want to highlight in red the regions where the value of <code>y</code> is above a certain threshold, e.g. 0.7. I thought of doing something like this</p> <pre><code>region = [i for i,...
<p>One way would be to apply a mask to <code>y</code> to find where the values are above your threshold. You then need to find the first and last occurrence where the values of the mask are <code>True</code>. This can be done by finding <code>True-False</code> and <code>False-True</code> transitions by using the answer...
python|arrays|numpy|matplotlib
1
356,434
52,669,277
Concatenate np.arrays python
<p>How can I do if:</p> <pre><code>a = np.array([[1,2,3],[5,6,7]]) b = np.array([0,1]) </code></pre> <p>I search to concatenate <code>a</code> and <code>b</code> so as the result would be:</p> <pre><code>np.array([1,2,3,0],[5,6,7,1]) </code></pre> <p>Thanks a lot</p>
<p>The problem is to concatenate <code>a</code> horizontally with <code>b</code> as a column vector.</p> <pre><code>&lt;concat&gt;( |1 2 3|, |0| ) |5 6 7| |1| </code></pre> <p>The concatentation can be done using <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.hstack.html" rel="n...
python|numpy
3
356,435
52,634,225
Specific interpolation method in Pandas/Scipy
<p>first create the data:</p> <pre><code>import pandas as pd import numpy as np %matplotlib inline data = pd.DataFrame({'time':np.arange(10)}) data['sin_of_the_times']= np.sin(data.time) newdata = pd.DataFrame({'time': np.linspace(0,10,15)}) newdata['sin_of_the_times'] = np.NAN data['interpolated']=False newdata['inte...
<p>You still want to do a linear interpolation; you just want to specify that the distance between the points depends on <code>time</code> instead of assuming they are evenly spaced. So first set the index to <code>time</code> then use <code>interpolate</code></p> <pre><code>df = df.set_index('time') df.sin_of_the_tim...
python|pandas|numpy|scipy
3
356,436
52,816,323
ModuleNotFoundError: No module named 'panda' though panda is installed on my mac os
<p>I have installed anaconda on my mac os. But when I am trying to import panda library, It is throwing error as panda module not found.</p> <p>So when I again try to install panda. It says panda already installed on machine</p> <pre><code>C27:python-programming jyoti.aditya$ pip install pandas Requirement already sa...
<p>The module name is <code>pandas</code>, not <code>panda</code>. Customarily it is imported like this:</p> <pre><code>import pandas as pd </code></pre> <p>See the <a href="https://pandas.pydata.org/pandas-docs/stable/10min.html" rel="noreferrer">10 Minutes to pandas</a> page for a quick introduction to the library....
python|pandas
6
356,437
52,477,839
printing float precision precision in numpy jupyter notebook
<p>I want to print floats with precision 4. I use numpy , jupyter notebook I tried:</p> <pre><code>%precision %.4g %precision 2 np.set_printoptions(precision=2) print(0.6776776) </code></pre> <p>the output:</p> <pre><code>0.6776776 </code></pre> <p>Any Ideas what is wrong ?</p> <pre><code># Name ...
<p>Print does not care about numpy or IPython formatters. It calls str() in the Background, any formatting has to be done using Standard print formatters (%.2f and the like). Look at the different Output for:</p> <pre><code>%precision 3 a = 0.6776776 print(a) a </code></pre> <p>The result will be:</p> <pre><code>0.6...
python|numpy|jupyter-notebook|precision
2
356,438
52,805,218
Create column based on multiple column conditions from another dataframe
<p>Suppose I have two dataframes - conditions and data.</p> <pre><code>import pandas as pd conditions = pd.DataFrame({'class': [1,2,3,4,4,5,5,4,4,5,5,5], 'primary_lower': [0,0,0,160,160,160,160,160,160,160,160,800], 'primary_upper':[9999,9999,9999,480,480,480,480,...
<p>You can iterate a <code>GroupBy</code> object and take the union of the masks within each group:</p> <pre><code>for key, grp in conditions.groupby('group'): cols = ['class', 'primary_lower', 'primary_upper', 'secondary_lower', 'secondary_upper'] masks = (data['class'].eq(cls) &amp; \ ...
python|pandas|numpy|pandas-groupby|multiple-conditions
1
356,439
52,705,656
How to use lists of strings as a conditional in a pandas dataframe
<p>If I have a dataframe (df) that looks like this:</p> <pre><code>Date Temperature Climate 4/1 50 Sunny 4/2 55 Cloudy 4/3 48 Rainy 4/4 53 Windy 4/5 33 Snowy ... </code></pre> <p>and I want to pick out the days with the climate I'm interested in.</p> <pre><code>clima...
<p>Here are two options among many.</p> <h3><code>isin</code></h3> <pre><code>df[df.Climate.isin(climate_of_interest)] Date Temperature Climate 0 4/1 50 Sunny 2 4/3 48 Rainy 4 4/5 33 Snowy </code></pre> <hr> <h3><code>query</code></h3> <pre><code>df.query('Climate in @cli...
python|pandas|conditional
1
356,440
52,509,491
Duplicating rows sequentially based on sum of multiple columns
<p>Let's say I have the the following dataframe (although the one I'm actually working with is over 100 rows):</p> <pre><code>&gt;&gt; df a b c d e title0 1 0 0 string title1 0 1 1 string </code></pre> <p>For each row, I want to:</p> <ul> <li>In col= ['b','c','d'], find rows where...
<p>you can try of imputing the rows wherever the duplication of 1 is there w.r.t axis 1, Then replace duplicated 1's with <code>identity matrix</code> <code>np.identity(len(df))</code>based on their length </p> <pre><code>df a b c d e 0 title0 1 0 0 string1 1 title1 0 1 1 string2 2 title2 ...
python|pandas|duplicates
1
356,441
52,595,477
Why is this Keras Conv2D layer not compatible with the input?
<p>I am having trouble understanding what input shapes my first convolutional neural network expects. </p> <p>My training set is 500 grayscale images of 50x50 pixels. </p> <p><a href="https://i.stack.imgur.com/nvMSN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nvMSN.png" alt="enter image descrip...
<p>Specify that you are not using the default data format by passing <code>data_format='channels_first'</code> to Conv2D.</p> <pre><code>model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(filters=64, kernel_size=(3,3), input_shape=X.shape[1:], ...
python|tensorflow|machine-learning|keras|tensor
2
356,442
52,885,649
Highlight panda df errors based on conditions
<p>Good day SO community,</p> <p>I have been having an issue with trying to highlight errors in my df, row by row.</p> <pre><code>reference_dict = {'jobclass' : ['A','B'], 'Jobs' : ['Teacher','Plumber']} dict = {'jobclass': ['A','C','A'], 'Jobs': ['Teacher', 'Plumber','Policeman']} df = pd.DataFrame(data=dict) def ...
<p>Good day to you as well!</p> <pre><code>What i hope to get is my df with values not found in my reference_dict being highlighted. </code></pre> <p>If you're looking for values <em>not</em> found in reference_dict to be highlighted, do you mean for the function to be the following?</p> <pre><code>def highlight_row...
python|pandas|dataframe|highlight
1
356,443
52,545,774
function to extract integer with regex returns nonetype
<p>I wrote a function to extract integer from strings. The strings example is below and it is a column in my dataframe. The output I got is in square bracket, with a lot of numbers inside. I want to use those numbers to compute further, but when I check what it is, instead of integer, it is a Nonetype. Why is that? and...
<p>If your problem is getting the sum of the integers, then you can simply:</p> <pre><code>sum(int(x) for x in ...) </code></pre> <p><br> However, if your problem is with the regex, then you should consider improving your filter mechanism (what should go in). You may also consider filtering manually (though not ideal...
python|regex|pandas|extract
0
356,444
52,450,778
How to perform Mann-Whitney U test in python with cycle?
<p>I have a loop that gives new values k1 and k2 each time, but the problem is that in my dataset there are cases where all values are zero in both k1 and k2. When the program comes to them, it just throws an error and does not complete the loop, and there is still a lot of calculations. How can I make such cases just ...
<p>You can continue with loop if 2 arrays are equal. For instance, if:</p> <pre><code>k1 = [0,0,0,0,0]; k2 = [0,0,0,0,0]; </code></pre> <p>then you can check whether <code>k1 == k2</code>. If it is true, just use continue for your loop. Like this:</p> <pre><code>if ( k1 == k2 ) == True: continue </code></pre> <p>ju...
python|pandas|loops|scipy|statistics
2
356,445
52,753,413
Incrementing a numpy 3-D array with repeating 2-D positions
<p>I have a 2-D numpy array as follows,</p> <pre><code>vol_coords = np.array([[ 2, 68], [ 79, 30], [ 2, 68], [ 79, 30], [ 79, 30],]) </code></pre> <p>I would like to increment the positions given in the above array in a...
<p>Two approaches with <code>np.add.at</code> and <code>np.bincount</code> could be proposed -</p> <pre><code>def addtoarray_addat(voxel_space, vol_coords, z_index=0): shp = voxel_space.shape idx = vol_coords[:,0]*shp[2] + vol_coords[:,1] + z_index*shp[2]*shp[1] np.add.at(voxel_space.ravel(),idx,1) re...
python-3.x|numpy
1
356,446
52,799,001
Having trouble with averageifs exception on a dataframe
<p>I have the dataframe successfully performing the equivalent of an averageifs statement in excel, but I don't know how to add this "exclude" syntax. I want the average of all Units_Ordered for that Customer_Number and Product, except on that Order_Number row. I'm thinking it would be something like a <code>Where Not<...
<p>How about subsetting the dataframe before you perform the average operation?</p> <p>Something like</p> <p><code>df[df.Order_Create_Date &lt; Today]</code> and then performing the mean and group by calculations?</p>
python|python-3.x|pandas|dataframe|average
1
356,447
52,500,185
Is it possible to keep all the images in one folder for tensorflow object detection API
<p>I am new to tensorflow and it’s object detection API. In its tutorial, it’s said that the images must be separated into train/ and test/ folders. Actually I am working on a server where my entire data is kept in a folder called ‘images’ and I don’t want to either change it’s structure or create another copy of it. ...
<p>In case you already have separate record files for train and eval (validation/test), then it's okay. You simply put the pathes of the corresponding records in </p> <p><code>tf_record_input_reader { input_path: "/path/to/record/record_name.record" }</code></p> <p>once for <code>train_input_reader</code> and...
python|tensorflow
0
356,448
52,837,152
Appending df lines into another df based on its index value
<p>I have the following <code>df1</code>:</p> <pre><code> col1 col2 col3 col4 col5 A 3 4 1 2 1 B 2 1 2 3 1 C 2 3 4 2 1 </code></pre> <p>On the other hand I have the <code>df2</code>:</p> <pre><code> ...
<p>It seems you need <code>MultiIndex</code> here. You should <em>not</em> use <code>NaN</code> indices as shown in your desired result: the label lacks meaning. One idea is to use a non-letter indicator such as <code>0</code>:</p> <pre><code># set index as (type, current_index) for df2 df2 = df2.reset_index().set_ind...
python|pandas
2
356,449
52,864,814
Aggregate multiple groupbys with a column of lists in Pandas
<p>I have a DataFrame that has a subset that looks like the following:</p> <pre><code>{u'snId': {3: u'396321357429208', 695: u'606426623024865', 703: u'606426623024865', 914: u'606426623024865', 5097: u'606426623024865', 6865: u'396321357429208', 26884: u'606426623024865', 30538: u'396321357429208', 32...
<p>IIUC, you first need to expand your <code>tagIds</code> column of lists into separate rows, then you can perform your <code>groupby()</code> and <code>agg()</code>, where <code>my_dict</code> is your input <code>dict</code>:</p> <pre><code>df = pd.DataFrame(my_dict) s = df.apply(lambda x: pd.Series(x['tagIds']), a...
python|pandas
0
356,450
52,774,566
Heterogenize numpy array such that no two adjacent cellls are equal
<p>I have a large numpy array which I would like to populate using the following criteria:</p> <ul> <li>use numbers only from a set range (0 to 9) example</li> <li>populate such that no adjacent cells are equal. This means that each cell would be surrounded by values which would be different from it. No exceptions can...
<p>As Paul Panzer commented, a regular checkerboard-like pattern can be constructed: </p> <pre><code>def uniq(shape): f = lambda *idx: np.mod(np.sum(idx, axis=0), 10) return np.fromfunction(f, shape) </code></pre> <p>For example, <code>uniq((5, 17))</code> is </p> <pre><code>[[ 0. 1. 2. 3. 4. 5. 6. 7....
python-3.x|numpy
1
356,451
52,591,372
pandas apply when cells contain lists
<p>I have a <code>DataFrame</code> where one column contains lists as cell contents, something like following:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'col_lists': [[1, 2, 3], [5]], 'col_normal': [8, 9] }) &gt;&gt;&gt; df col_lists col_normal 0 [1, 2, 3] 8 1 [5] ...
<p>First I think working with <code>list</code>s in pandas is not <a href="https://stackoverflow.com/a/52563718/2901002">good idea</a>.</p> <p>But if really need it, try upgrade pandas, because for me it working nice in <code>pandas 0.23.4</code>:</p> <pre><code>df2['col_lists'] = df2.apply( lambda row: [ None if...
python|pandas|pandas-apply
3
356,452
52,783,615
Tensorflow Image Classifier Accuracy Fails to Change
<p>I am new to tensorflow. I'm creating a simple fully connected neural network for image classification. The image is (-1, 224, 224, 3), and label is (-1, 2). However, the result of my code is that the accuracy does not improve at all; it stays at 47% and does not change - even if changed learning rate, optimizer, and...
<p>I've made a few observations, firstly your code is a bit outdated, you don't have to manually set up fully connected layers, there is something for that:<a href="https://www.tensorflow.org/api_docs/python/tf/layers/dense" rel="nofollow noreferrer">dense layers</a>. If you load in images, why don't you use convolutio...
python|tensorflow|machine-learning|computer-vision
0
356,453
52,798,070
Rentry to numpy function returns Error: float object has no attribute exp
<p>I finally figured out why I was getting a "weird" error in a function call. But I do not understand WHY I got the error or how to avoid it in the future.</p> <p>The error was:</p> <pre><code>rates = Qi*np.exp(-Di*(days-T0)) </code></pre> <p>AttributeError: 'float' object has no attribute 'exp'</p> <p>This ques...
<p>The underlying type of a numpy array can not be devised. </p> <p>Python is only <strong>dynamically strongly typed</strong> (<a href="https://stackoverflow.com/questions/11328920/is-python-strongly-typed">Is Python strongly typed?</a> )</p> <p><strong>That's it's main strength and one of it's main frustrating wea...
python|pandas|numpy
-2
356,454
52,632,687
How to trasfer NaN to 'N/A' in pandas?
<p>How should I transfer NaN to N/A in pandas?</p> <p>Any thoughts and suggestions are appreciated!</p> <p>Thanks!</p>
<p>You should clarify why you want to convert NaN to 'N/A'. NaN is a special internal representation of missing data. Sure 'N/A' represents missing data, but to python, this will just be another string, and will be decidedly different from a None/null/missing value.</p> <p>Without clarification, I am assuming that you...
python|pandas|missing-data
4
356,455
52,853,025
Pandas dataframe multiply entire column by single cell in another column controlling for group identifier
<p>Hi I am trying and failing to replicate a fairly simple excel formula in python. This is a screenshot of my dataframe and the caluclation in column F I am trying to perform:</p> <p><a href="https://i.stack.imgur.com/RC0y5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RC0y5.png" alt="datafram"><...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.div.html" rel="nofollow noreferrer"><code>div</code></a> by new <code>Series</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</co...
python|pandas|dataframe
0
356,456
52,807,427
Pandas matplotlib boxplot with mean trendline
<p>I'd like to add a trendline to my boxplot showing the mean values. Anyone figured it out using pandas?</p> <p>My code goes like that:</p> <pre><code>fig, ax = plt.subplots(figsize=(10,5)) ax1 = df.boxplot(column='val', by='DATE',ax=ax) </code></pre> <p>And I get a nice boxplot as a result.</p> <p><a href="https:...
<p>Do you mean you want to plot the means? If so you can pass <code>showmeans = True</code> to the boxplot, and it will use a marker to show the (arithmetic) mean. My personal opinion is that this will look better than a line superimposed on the boxplot (which is also possible to do):</p> <pre><code>import pandas as p...
python|pandas|matplotlib|boxplot
2
356,457
52,544,340
In Python DataFrame how to find out number of rows that have valid values of columns
<p>I want to find the number of rows that have certain values such as <code>None</code> or <code>""</code> or <code>NaN</code> (basically empty values) in all columns of a DataFrame object. How can I do this? </p>
<p>Use pandas dataframe.isin to create a boolean array. Sum by row, then find the number of rows with a result > 0.</p> <p>Place one or more values in the search_values list to look for within the rows of the dataframe.</p> <pre><code>search_values = ['', np.nan, None] (df.isin(search_values).sum(axis=1) &gt; 0).sum...
python|pandas|dataframe|sklearn-pandas
3
356,458
52,503,620
dev_appserver.py app.yaml produces: ImportError: Importing the multiarray numpy extension module failed
<p>I run this command: </p> <pre><code>dev_appserver.py app.yaml </code></pre> <p>and I get an error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\sehrlich\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 240, in Handle handle...
<p>As Dan Cornilescu said, GAE Standard can't use libraries with code compiled in C <a href="https://cloud.google.com/appengine/docs/standard/python/tools/using-libraries-python-27" rel="nofollow noreferrer">[1]</a> <a href="https://cloud.google.com/appengine/docs/standard/#standard_environment_languages_and_runtimes" ...
python|numpy|google-app-engine
2
356,459
52,616,845
How to use decile cut from one data to cut another data?
<p>I know we can use the following code to create a decile column for based on a column of given data set considering there are tie in the data (see <a href="https://stackoverflow.com/questions/20158597/how-to-qcut-with-non-unique-bin-edges">How to qcut with non unique bin edges?</a>):</p> <pre><code>import numpy as n...
<p>You can using <code>.left</code> get all <code>bins</code> </p> <pre><code>s1=pd.Series([1,2,3,4,5,6,7,8,9]) s2=pd.Series([2,3,4,6,1]) a=pd.qcut(s1,10).unique() bins=[x.left for x in a ] + [np.inf] pd.cut(s2,bins=bins) </code></pre>
python|pandas
1
356,460
52,841,906
Pandas - convert header name in tuple format to a string
<p>After computing percentiles within group, the header names is in tuple format like <code>[('A', 0.5), ('A',0.9)...('Z',0.9)]</code>.</p> <p>The desired output should be:</p> <pre><code>['P50 A', 'P90 A', ...'P90 Z'] </code></pre> <p>Basically, I want to multiply the decimal by 100 to get percentage and move it up...
<p>This works also:</p> <pre><code>original_names = [('A', 0.5), ('A',0.9),('Z',0.9)] new_names = ['P'+str(int(100*y)) + ' ' + x for x,y in original_names] </code></pre> <p>Result: ['P50 A', 'P90 A', 'P90 Z']</p>
python|pandas
2
356,461
52,562,451
Reasons for using null vs empty in pandas
<p>I wish to read a csv into a data frame: </p> <p>e.g. </p> <pre><code>name, age, city Dave, , London Bob, 24, Melbourne Joe, 38, Boston </code></pre> <p>I wish to keep rows where there is no age listed.</p> <p>If I read empty csv values into the dataframe as NaN I can filter with is <code>df[‘age’].isnull()</code...
<p>The biggest difference in my mind is how the dataframe handles each value. If you read in as <code>NaN</code>, you can use built-in methods like <code>isna()</code> and <code>df.info</code> to find null values, where you can't necessarily if you just initialize with an empty string</p>
python|pandas|null
0
356,462
52,755,438
How to convert a list to array when the list has blank array
<p>I have a list</p> <pre><code>A = [np.array([-25.2]), np.array([20.2]), np.array([15.3]), np.array([]), np.array([]), np.array([-17.5]), np.array([19.3])] </code></pre> <p>As you can see the list has blank arrays. When I use:</p> <pre><code>A1 = np.array(A) </code></pre> <p>it makes it an object which I can...
<p>It depends what you want to have in place of the blank arrays. A numpy array must have the same type, so you can't just have blank. You could fill with NaNs, or zeros etc.</p> <p>Also, you have no option but to loop through the array.</p> <pre><code>k = [None] * len(a) for i,x in enumerate(a): if len(x) == 0: ...
python|arrays|numpy
0
356,463
52,505,501
Python – Pandas: Get max value of last 5 days
<p>I have a csv file with two columns, date and price. I want to create a 3rd column with the max value of "Price" for the last 5 days. Not the last 5 rows or index, but 5 days.</p> <p>Content of "example.csv"</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div cl...
<p>You are looking for rolling </p> <pre><code>df=df.set_index('Date') df.index=pd.to_datetime(df.index) df.rolling('5 D').max() #df=df.rolling('5 D').max().reset_index() Out[62]: Price Date 2018-07-23 124.44 2018-07-24 125.49 2018-07-25 125.49 2018-07-31 124.08 2018-08-01 125.10 2018-...
python|pandas|numpy
5
356,464
52,749,143
Matplotlib plus NetworkX producing overlaying graphs when looping over multiple files
<p>I have a script that should loop over series of csv files to create different directed graphs. When saving with matplotlib (plt.savefig()) then graphs seems to get saved on top of one another as the loop goes on. If I use plt.show() which requires me to manually close the file for each loop, this does not happen. Th...
<p>The problem is that you were not clearing <code>fig</code> which is a global object created by <code>pyplot</code>. This means every time around your loop more data is added ("graphs seems to get saved on top of one another").</p> <p>To avoid this, you can either call <code>plt.clf()</code> or <code>plt.close()</co...
python|pandas|matplotlib|networkx
2
356,465
52,626,698
Python heatmap and colorbar colors are different
<p>I'm using matplotlib and seaborn to create a heatmap of my correlation matrix with specific colors representing dataranges. I am facing an issue where my colorbar does not represent the full spectrum of colors in the heatmap. edit: The issue lies with the colorbar in the range -0.5 to -0.3. The color here should be ...
<p>It looks like a seaborn issue. When using pure matplotlib, </p> <pre><code>im = ax.imshow(np.ma.masked_array(corr_matrix, mask), cmap=cmap, norm=norm) fig.colorbar(im, ticks=[-1, -0.5, -0.3, -0.1, +0.1, +0.3, +0.5, +1]) </code></pre> <p>the result is as expected.</p> <p><a href="https://i.stack.imgur.com/P48Ut.pn...
python|pandas|numpy|matplotlib|seaborn
2
356,466
52,664,730
Python+Pandas+Dataframe+CSV : Code removes all rows from a dataframe instead of specified ones
<p>I have written a code to remove all the rows which have NaNs in category_id column which successfully removed the rows with NaNs in category_id column:</p> <pre><code> #removal of rows in dataframe that have NaN values in 'category_id' column #data = data[np.isfinite(data['category_id'])] data = data[data[...
<p>Problem is your data are strings, not integers in column <code>category_id</code>.</p> <pre><code>print (data.category_id.dtype) object </code></pre> <p>So need convert values in list to strings:</p> <pre><code>category_ids = ['19', '22', '2', '30', '23'] data = data[data.category_id.isin(category_ids)] </code></...
python|pandas|csv|dataframe
3
356,467
52,509,972
deleting row from Dataframe results in distribute dataframe in Python
<p>I have below dataframe nbr2:</p> <pre><code> Postal_Code Borough Neighborhood 0 M1B Scarborough Rouge, Malvern 1 M4C East York Woodbine Heights 2 M4E East Toronto The Beaches 3 M4L East Toronto The Beaches West, India Bazaar 4 M4M East Toronto Studio District ...
<p>use</p> <pre><code>pd.set_option('display.expand_frame_repr', False) </code></pre>
python|pandas|dataframe
1
356,468
52,829,781
Comparison two values from two different classes "<class 'pydicom.valuerep.DSfloat'>" and <class 'numpy.ndarray'> in Python
<p>I want to compare some values using "if" in the code below, but it doesn't work:</p> <pre><code>if Slice_num[person][i, [1]] == Z_pos: # Slice_num[0][15, [1]] is ['-10.000000'] and Z_pos = -10.000000 absname = os.path.join(root, dcmfile) </code></pre> <hr> <p>Example: Values in the above variables are equa...
<p>The values are actually not the same. <code>Slice_num[person][i, [1]]</code> is a numpy.ndarray containing one item, namely the value you want to compare. Try<br> <code>Slice_num[person][i, [1]][0] == Z_pos</code></p>
arrays|python-3.x|numpy|pydicom
0
356,469
46,485,247
How to process rows of a pandas DataFrame in parallel in Python
<h1>Exemplary dummy example:</h1> <p>I have a DataFrame <code>df</code>:</p> <pre><code>&gt; df para0 para1 para2 0 17.439020 True high 1 19.757758 True high 2 12.434424 True medium 3 14.789654 True low 4 14.131464 False high 5 9.900233 True high 6 10.977869 False low...
<p>I don't know if it helps, but try to use <code>list</code> instead of <code>itertuples</code>.</p> <p>I mean something like this:</p> <pre><code>df_list = [[x[0], x[1],x[2]] for x in df.itertuples()] for r in df_list: results += [pool.apply_async(wrapper, r, df)] </code></pre>
python|pandas|multiprocessing
2
356,470
46,247,622
Python pandas plotting
<p>There is my code (example code from book about machine learning), but it doesn't appear pd.plotting.scatter_matrix in the end. </p> <pre><code>import sys import mglearn as mglearn import pandas as pd from pandas.plotting import scatter_matrix import tkinter import matplotlib import numpy as np import scipy as sp im...
<p>It is best to use <code>matplotlib.pyplot</code> for plots</p> <p>add this to the imports</p> <pre><code>import matplotlib.pyplot as plt </code></pre> <p>Then at the very bottom of the file</p> <pre><code>plt.show() </code></pre> <p>You can force <code>pandas</code> to do it without importing <code>matplotlib</...
python|pandas|plot
2
356,471
46,595,537
one code segment error that might be related to python 2.7 vs python 3.x
<p>I am trying to re-use the following code segment. The specific line of code <code>gt_bg = gt_bg.reshape(*gt_bg.shape, 1)</code> gives me the error messages such as </p> <pre><code>gt_bg = gt_bg.reshape(*gt_bg.shape, 1) SyntaxError: only named arguments may follow *expression </code></pre> <p>I am using <code>Pytho...
<p>This is not really related to the Python 2 / Python 3 difference, that's a red herring. </p> <p>numpy array's reshape method expects to receive the new shape directly, as a tuple, not unpacked into dimensions. So, instead of this:</p> <pre><code>gt_bg = gt_bg.reshape(*gt_bg.shape, 1) </code></pre> <p>It's expec...
python-2.7|python-3.x|numpy|scipy
1
356,472
46,188,107
Calculations on several dataframes in pandas
<p>I have several dataframes. Below is an example of each of them.</p> <pre><code> df_min scale code R1 R2 ... 1 121 50 30 2 121 35 45 3 121 40 50 4 121 20 30 5 121 20 35 1 313 10 7 2 313 13 10 3 313 10 12 4 ...
<p>using pandas <code>index</code> and <code>MultiIndex</code> is very useful for comparing the correct rows with eachother.</p> <p>Here is how you would use it:</p> <pre><code># set the index to 'code' to subtract df_rate from df_stock df_stock = df_stock.set_index('code') df_rate = df_rate.set_index('code') df_new ...
python|pandas
1
356,473
46,174,347
Python - Filter DataFrame by Sub DataFrame
<p>I got a DataFrame like this:</p> <pre><code> A B C 1 1 2 3 2 4 5 6 3 7 8 9 </code></pre> <p>And I want to filter it by a sub set of DataFrame:</p> <pre><code> A C 1 4 6 2 7 9 </code></pre> <p>Finally, I can get this output:</p> <pre><code> A B C 2 4 5 6 3 ...
<pre><code>In [92]: d1.merge(d2) Out[92]: A B C 0 4 5 6 1 7 8 9 </code></pre>
python|pandas|dataframe|filter
2
356,474
46,456,610
using pandas dataframe transpose headers into a single column?
<p>I have a dataframe for which i need to convert the headers related to date into a column. <a href="https://i.stack.imgur.com/XNzo5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XNzo5.png" alt="df"></a></p> <p>I tried to use</p> <pre><code>df.set_index('id') df.unstack() </code></pre> <p>but i...
<p><code>set_index</code> doesn't operate in place by default. You need to either assign the output or chain your operations. </p> <pre><code>df.set_index('id').stack().reset_index(name='value') </code></pre>
pandas|dataframe|transpose
1
356,475
46,481,313
Speed up the computation for numpy.asarray
<p>I am given the following code which generates random integers and convert them into their binary repsentation:</p> <pre><code>import sys import random import numpy num = 500000 M = list(set([random.randint(0, 2 ** 64) for i in range(num)])) M = [('{0:016b}').format(i) for i in M] M = numpy.asarray([list(map(int, l...
<p>With <code>num=5</code>, your code produces</p> <pre><code>In [62]: M Out[62]: array([ list([1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0]), list([1, 0, 1, 1, 0, ...
python-2.7|numpy
0
356,476
46,288,161
nested json file with dictionary into a dataframe
<p>I have a json file as</p> <pre><code>{ "Date": 2017, "count": 88, "demographics": [ { "key": "age", "value": "20-30" }, { "key": "education", "value": 'bachelor' }, { "key": "income", ...
<p>By using <code>apply</code> with <code>pd.Serise</code>:</p> <pre><code>d={ "Date": 2017, "count": 88, "demographics": [ { "key": "age", "value": "20-30" }, { "key": "education", "value": 'bachelor' }...
python|json|pandas|dictionary
0
356,477
46,565,367
Is it allowed to assign a value to a variable before it enter a computational graph?
<p>I define a simple computational graph involving a variable. When I change a value of the variable it has an expected influence on the output of the computational graph (so, everything works fine, as expected): </p> <pre><code>s = tf.Session() x = tf.placeholder(tf.float32) c = tf.Variable([1.0, 1.0, 1.0], tf.float...
<p>With TensorFlow, always keep in mind that you're building a <a href="https://www.tensorflow.org/versions/r0.12/get_started/basic_usage#the_computation_graph" rel="nofollow noreferrer">computation graph</a>. In your first code snippet, you basically define <code>y = tf.placeholder(tf.float32) + tf.Variable([1.0, 1.0,...
python|tensorflow
2
356,478
46,246,595
Pandas dropping columns and rows from a dataframe that came from Excel
<p>I am trying to drop some useless columns in a dataframe but I am getting the error: "too many indices for array"</p> <p>Here is my code :</p> <pre><code>import pandas as pd def answer_one(): energy = pd.read_excel("Energy Indicators.xls") energy.drop(energy.index[0,1], axis = 1) answer_one() </code></pre>
<p><strong>Option 1</strong><br> Your syntax is wrong when slicing the index and it should be the columns</p> <pre><code>import pandas as pd energy = pd.read_excel("Energy Indicators.xls") energy.drop(energy.columns[[0,1]], axis=1) </code></pre> <hr> <p><strong>Option 2</strong><br> I'd do it like this</p> <pre><c...
python|pandas
5
356,479
46,433,596
tf.nn.embedding_lookup - row or column?
<p>This is a very simple question. I'm learning tensorflow and converting my numpy-written code using Tensorflow.</p> <p>I have word embedding matrix defined <code>U = [embedding_size, vocab_size]</code> therefore each column is the embedding vector of each word.</p> <p>I converted <code>U</code> into TF like below:...
<p>U should be vocab_size x embedding_size, the transpose of what you have now.</p>
tensorflow|deep-learning
1
356,480
46,328,618
Store multidimensional numpy array slice with newaxis to object
<p>I have some code where I repeatedly need to repeatedly broadcast arrays in complex ways, for example:</p> <pre><code>a = b[np.newaxis, ..., :, np.newaxis] * c[..., np.newaxis, np.newaxis, :] </code></pre> <p>Is there an object to which I can store these slicing specifications?</p> <p>i.e. (but obviously this does...
<p>You can construct the index tuple manually, but NumPy includes a <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.s_.html#numpy.s_" rel="nofollow noreferrer">helper</a> for it:</p> <pre><code>slice_tuple = np.s_[np.newaxis, ..., :, np.newaxis] </code></pre> <p>Then <code>b[np.newaxis, ......
python|arrays|numpy|slice
5
356,481
46,604,371
Produce a dataset of stridded slices from a tfrecords dataset
<p>Continuing from <a href="https://stackoverflow.com/a/46557087/281545">this</a> question and the discussion <a href="https://github.com/tensorflow/tensorflow/issues/13101#issuecomment-334609033" rel="nofollow noreferrer">here</a> - I am trying to use the Dataset API to take a dataset of variable length tensors and cu...
<p>The easiest way to build a <code>Dataset</code> from a nested <code>Dataset</code> is to use the <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/data/Dataset#flat_map" rel="nofollow noreferrer"><code>Dataset.flat_map()</code></a> transformation. This transformation applies a function to each element o...
python|tensorflow|tensorflow-datasets
1
356,482
46,281,301
Python for loop over matrix
<p>I have a problem with a small python program to cross-match two arrays. As a side note, I'm learning to code in Python in these days, so I assume I'm making some incredibly trivial mistake here. Basically, I want to open two .txt files, create a 2D array from each of them, and compare them to see if they have common...
<p>Any for loop should end with a colon (:). </p> <p>The colon is required primarily to enhance readability. Python docs explicitly mention <a href="https://docs.python.org/3/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements" rel="nofollow noreferrer">here</a></p> <pre><code>#creating arra...
python|numpy
2
356,483
46,594,532
np.loadtxt() How to load every other line from txt file? Python
<p>I have a txt file of data that I only want to load in the even lines from.</p> <p>Is there a way to do this in python without using loops?</p> <p>Here are the first 10 lines of my data file:</p> <pre><code>1 25544U 98067A 98324.28472222 -.00003657 11563-4 00000+0 0 10 2 25544 51.5908 168.3788 0125362 86....
<p>One way to do it is to use a counter and modulo operator:</p> <pre><code>fname = 'load_even.txt' data = []; cnt = 1; with open(fname, 'r') as infile: for line in infile: if cnt%2 == 0: data.append(line) cnt+=1 </code></pre> <p>This reads the file line by line, increasing the counte...
python|python-2.7|numpy|data-files
2
356,484
46,385,187
Converting datetimeindex to timestamp for pd.date_range
<p>I have two lists:</p> <p>"max_" consists of datetime types: </p> <pre><code>2012-04-20 00:00:00 2012-11-29 00:00:00 2013-11-22 00:00:00 </code></pre> <p>"min_" , consists of datetimeindex: </p> <pre><code>DatetimeIndex(['2012-07-11'], dtype='datetime64[ns]', name=u'Date', freq=None) DatetimeIndex(['2013-02-05', ...
<p>I think you need to just specify items in your lists that you want to create the range on:</p> <pre><code>pd.date_range(min_[0],max_[0]) </code></pre> <p>If you are trying to print the ranges:</p> <pre><code>for date in max_: print (pd.date_range(min_[0],max_[date]) </code></pre>
python|pandas|timestamp
0
356,485
46,423,156
What is this feature column and how does it affect the training?
<p>I'm relatively new to Tensor Flow. What is this feature column and how does it affect the training? </p> <p>When I implement a code like below, this numeric column is created as a feature column. I would like to understand the use.</p> <pre><code>feature_columns = [tf.feature_column.numeric_column("x", shape=[1])]...
<p>Based on what I can glean from the <a href="https://www.tensorflow.org/api_docs/python/tf/feature_column" rel="noreferrer">documentation on feature columns</a>, it seems they are used to convert some sort of input data feature into continuous variables that can be used by a regression or neural network model.</p> <...
python|machine-learning|tensorflow
9
356,486
46,555,274
Library not loaded: @rpath/libopenblasp-r0.2.19.dylib multiarray.cpython-36m-darwin.so Reason: image not found
<p>I updated my Python through Conda and now I get this error. I had no problem before with Anaconda Python. What are some quick/easy fixes?</p> <pre><code>Monas-MacBook-Pro:P3 mona$ python k_means_clustering.py Traceback (most recent call last): File "/Users/mona/anaconda/lib/python3.6/site-packages/numpy/core/__i...
<p>Not sure why would that have happened after updating to Python 3.6.2 from Python 3.5.4 but this solved the issue for me.</p> <pre><code>Monas-MacBook-Pro:P3 mona$ conda install -c conda-forge openblas=0.2.19 Fetching package metadata ............. Solving package specifications: . Package plan for installation in ...
python|macos|numpy|anaconda|conda
4
356,487
46,327,624
Cannot find -ltensorflow
<p>I'm trying to make work <code>TF</code> on <code>Mac OS X</code>. I ran the tutorial <a href="https://www.tensorflow.org/install/install_go" rel="nofollow noreferrer">how to install it.</a> All went well, the tensorflow library is install in my <code>GOPATH</code> but I keep getting this error.</p> <pre><code>/usr/...
<p><code>$DYLD_LIBRARY_PATH</code> and <code>$LIBRARY_PATH</code> need to include the directory in which the C library (<code>libtensorflow.so</code>) is installed, not the Go libraries.</p> <p>I suspect this is not the case for you (<code>ls ${DYLD_LIBRARY_PATH}/libtensorflow.so</code>). (See Step 2 and 3 in <a href=...
macos|go|tensorflow|clang
4
356,488
46,397,811
pandas:groupby('date_x')['outcome'].mean()
<p><a href="https://www.kaggle.com/anokas/time-travel-eda" rel="nofollow noreferrer">https://www.kaggle.com/anokas/time-travel-eda</a></p> <p>what is these code mean exactly?<code>groupby('date_x')['outcome'].mean()</code>,I could not find this in sklearn doc.</p> <pre><code>date_x['Class probability'] = df_train.gro...
<p>I think better is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.agg</code></a> for aggregate by <code>size</code> for length of groups and <code>mean</code> per groups which are grouping by column <co...
pandas|pandas-groupby
1
356,489
46,473,261
Create a data frame in Python containing a combination of all values from three lists
<p>So I have two lists: <code>gender = ['Male', 'Female']</code> and <code>subject = ['Math3_Exam_Mark', 'Math6_Exam_Mark', 'Math9_Exam_Mark', 'ELA3_Exam_Mark', 'ELA6_Exam_Mark', 'ELA9_Exam_Mark']</code>, plus an ndarray <code>birthMonthYear</code> containing a list of dates extracted from a CSV file.</p> <p>I'd like ...
<p><strong>Setup</strong> </p> <pre><code>gender = ['Male', 'Female'] subject = ['Math3_Exam_Mark', 'Math6_Exam_Mark', 'Math9_Exam_Mark', 'ELA3_Exam_Mark', 'ELA6_Exam_Mark', 'ELA9_Exam_Mark'] birthMonthYear = pd.date_range('2010-01-31', periods=2, freq='M') </code></pre> <p><strong>Option 1</strong><br> <...
python|pandas|dataframe
1
356,490
46,612,532
How can I ignore quotechar inside field in pandas read_csv?
<p>I use pandas read_csv:</p> <pre><code>pd.read_csv(filepath_or_buffer, sep=None, error_bad_lines=False, skipinitialspace=True) </code></pre> <p>and I've got error line:</p> <pre><code>Skipping line 818: ',' expected after '"' </code></pre> <p>One of the lines that causes an error, where quotechar inside field, bu...
<p>I created a file like this:</p> <pre><code>"Valid value","Another valid value","A third valid value" "Valid value","Another valid value","A third valid value" "Valid value", "Invalid " value","Invalid line" "Valid value","Another valid value","A third valid value" </code></pre> <p>And opened it with</p> <p><code>...
python|pandas
0
356,491
46,608,223
Sorting and loading data from Pandas to Redshift using to_sql
<p>I've built some tools that create front-end list boxes for users that reference dynamic Redshift tables. New items in the table, they appear automatically in the list.</p> <p>I want to put the list in alphabetical order in the database so the dynamic list boxes will show the data in that order. </p> <p>After downl...
<p>While ingesting data into redshift, data gets distributed between slices on each node in your redshift cluster. <br> My suggestion would be to create a sort key on a column which you need to be sorted. Once you have sort key on that column, you can run Vacuum command to get your data sorted.<br> Sorry! I cannot be o...
python|sorting|amazon-redshift|pandas-to-sql
0
356,492
46,607,306
Python: Numpy and Pandas Transforming timestamp/data into one-hot-encoding
<p>I have a column of a dataframe that is like this</p> <pre><code> time 0 2017-03-01 15:30:00 1 2017-03-01 16:00:00 2 2017-03-01 16:30:00 3 2017-03-01 17:00:00 4 2017-03-01 17:30:00 5 2017-03-01 18:00:00 6 2017-03-01 18:30:00 7 2017-03-01 19:00:00 8 2...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow noreferrer"><code>get_dummies</code></a>.</p> <p>Also it s...
python|pandas|date|numpy|encoding
3
356,493
46,321,237
Pandas dataframe left align data
<p>How do I set the data within a dataframe to be left-aligned?</p> <p>I'm using python 2.7.13.</p> <p>This question has been asked before but the accepted answer didn't even work. The answer given was:</p> <pre><code>df.style.set_properties(**{'text-align': 'left'}) </code></pre> <p>It doesn't work, my data is sti...
<h3>Case 1: Styling to print as html</h3> <p><code>df.style.set_properties</code> returns an object of type <code>pandas.io.formats.style.Styler</code></p> <pre><code>type(df.style.set_properties(**{'text-align': 'left'})) Out[37]: pandas.io.formats.style.Styler </code></pre> <p>Which is meant to be rendered as an html...
python-2.7|pandas
-1
356,494
46,533,538
Calculating the Haversine distance between two dataframes
<p>I have two dataframes, <code>df1</code> and <code>df2</code>, each containing latitude and longitude data. For each observation in <code>df1</code>, I would like to use the <code>haversine</code> function to calculate the distance between each point in <code>df2</code>. I have tried two approaches, but performance b...
<p>If you're looking for a more performant merge, you can do a cross join on a surrogate column:</p> <pre><code>temp = df1.assign(A=1).merge(df2.assign(A=1), on='A').drop('A', 1) temp lat_long_x lat_long_y 0 (25.99550273, 179.18526021) (22.89956242, 107.04009984) 1 ...
python|pandas|dataframe|haversine
3
356,495
46,499,918
Plot the element-wise product of two numpy arrays
<p>I'm very new to python, I wanted to write a program that multiplies elements present inside two arrays and plots a graph How should I correct the code?</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x=(np.double[0.1,0.001,0.0001,0.0001,0.00001]) y=(np.double[0.1,0.001,0.0001,0.0001,0.00001]) m=le...
<pre><code>x = np.array([0.1, 0.001, 0.0001, 0.0001, 0.00001] ) plt.plot(x ** 2) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/n1HpU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n1HpU.png" alt="enter image description here"></a></p> <hr> <p>If <code>x</code> and <code>y</code> ...
python|arrays|numpy|matplotlib|plot
1
356,496
46,310,197
Retrieving a slice from a multiindexed DataFrame
<p>I have a Pandas DataFrame with MultiIndex such as follow:</p> <p><a href="https://i.stack.imgur.com/RADrQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RADrQ.jpg" alt="enter image description here"></a></p> <p>I am trying to retrieve few rows using a IndexSlice:</p> <pre><code>idx=pd.IndexSli...
<p>You should be able to do this by passing tuple of <code>(idx[...], your_value)</code> as the first argument to <code>loc</code>.</p> <pre><code>prices.loc[(idx["2016-09-19 13:30:00":"2016-09-19 14:30:00"], xxx), :] </code></pre> <hr> <p>Example:</p> <pre><code>prices.loc[(idx["2016-09-19 13:30:00":"2016-09-19 1...
python|pandas|dataframe|indexing|multi-index
1
356,497
46,451,284
Groupby and perform row-wise calculation using a custom function
<p>Following on from this question: <a href="https://stackoverflow.com/questions/46446863/python-group-by-and-add-new-row-which-is-calculation-of-other-rows/46447447#">python - Group by and add new row which is calculation of other rows</a></p> <p>I have a pandas dataframe as follows:</p> <pre><code>col_1 col_2 c...
<p>I'm not sure if this is what you're looking for, but here goes:</p> <pre><code>def f(x): y = x.values return y[0] / y[1] # replace with your function </code></pre> <p>And, the change to <code>new</code> is:</p> <pre><code>new = ( df[df.col_2.isin(['X', 'Z'])] .groupby(['col_1'], as_index=False)[...
python|pandas|dataframe|group-by|pandas-groupby
4
356,498
58,581,014
Compute logarithm of nonzero values in a tensor with keras
<p>I am trying to implement a custom loss function and it requires taking logarithm of values in the output tensor from the model. The tensor may contain zeros as well and so I want to take only non-zero values and compute logarithm. </p> <p>The output tensor is of shape (20,224,224). I could get the number of nonzer...
<p>A possible approach might leverage: </p> <pre><code>tf.where( condition, x=None, y=None, name=None ) </code></pre> <p>and related functions listed: <a href="https://www.tensorflow.org/api_docs/python/tf" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf</a> that are similar ...
python|python-3.x|tensorflow|keras|deep-learning
0
356,499
58,574,246
Creating summary from stock transactions table - current code execution SLOW
<p>I have a table of stock transactions that looks like this...</p> <p>The account number may be duplicated many times, also that account may have also ordered the same product multiple times.</p> <pre><code>+------------+------------+------------+--------+---------+--------------+ | SA_ACCOUNT | SA_TRDATE | SA_TRVA...
<p>Looks like what you're looking for is </p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html" rel="nofollow noreferrer">pandas.pivot_table</a></p> <p>function with parameter <code>aggfunc=np.sum</code></p>
python|pandas
1