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
370,700
51,731,319
InvalidArgumentError: input_1_1:0 is both fed and fetched
<p>I am using the visualize_activation function in keras-vis:</p> <pre><code>from vis.visualization import visualize_activation, visualize_cam from vis.utils import utils from keras import activations from matplotlib import pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (18, 6) # Utility to search...
<p><code>keras-vis</code> on pip seems broken, try installing directly on the GitHub master branch:</p> <pre><code>pip uninstall vis pip install git+https://github.com/raghakot/keras-vis.git -U </code></pre> <p>Using the version on pip, both the MNIST and ResNet example outputs the error: <code>InvalidArgumentError: ...
python|tensorflow|neural-network|keras
3
370,701
51,720,151
I cannot make my ideal DataFrame
<p>There is a csv data like</p> <pre><code>No,User,A,B,C,D 1 Tom 100 120 110 90 1 Juddy 89 90 100 110 1 Bob 99 80 90 100 2 Tom 80 100 100 70 2 Juddy 79 90 80 70 2 Bob 88 90 95 90 ・ ・ ・ </code></pre> <p>I want to transform this csv data into this DataFrame like </p> <pre><code> Tom_A Tom_B Tom_C Tom_D Juddy_A Jud...
<p><strong><em>Setup</em></strong></p> <pre><code>df = pd.DataFrame({'No': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2}, 'User': {0: 'Tom', 1: 'Juddy', 2: 'Bob', 3: 'Tom', 4: 'Juddy', 5: 'Bob'}, 'A': {0: 100, 1: 89, 2: 99, 3: 80, 4: 79, 5: 88}, 'B': {0: 120, 1: 90, 2: 80, 3: 100, 4: 90, 5: 90}, 'C': {0: 110, 1: 100, 2: 90, 3:...
python|pandas
3
370,702
51,589,573
Pandas filter data frame rows by function
<p>I want to filter a data frame by more complex function based on different values in the row.</p> <p>Is there a possibility to filter DF rows by a boolean function like you can do it e.g. in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="noreferrer">ES6 f...
<p>I think using functions here is unnecessary. It is better and mainly faster to use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="noreferrer">boolean indexing</a>:</p> <pre><code>m = (df['Name'] == 'Alisa') &amp; (df['Age'] &gt; 24) print(m) 0 True 1 False 2 Fa...
python-3.x|pandas|filter
46
370,703
51,563,175
Using Bivariate spline with scipy.ndimage.geometric_transform to register images
<p>I am trying to align arrays (images). The arrays do not share homogeneous coordinates due to non-linear distortions and as such an <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.affine_transform.html" rel="nofollow noreferrer">affine transformation</a> is not sufficient.</p> <p>Fortunat...
<p>So, there's two solutions for your problem, though potentially only one feasible one:</p> <h2>1. Use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html" rel="nofollow noreferrer"><code>ndimage.map_coordinates</code></a></h2> <p>Since <code>interpolate.SmoothBivariateSp...
python|numpy|image-processing|scipy|scikit-image
4
370,704
51,676,783
Get the mean of two DataFrames with missing values
<p>I have two DataFrames, which I am trying to make a single containing the mean of the two. Each has missing values.</p> <p>If there were not missing values I could use (df1 + df2)/2.</p> <p>I would like to take the mean of those that have both data points, while returning 'NaN' as the 'mean' for the points that are...
<p>You can do exactly that, <code>(df1 + df2) / 2</code>. </p> <p>Your real problem here is that the NaN-containing columns in your DataFrames are of <code>object</code> dtype, not floating datatypes. Fix that, and the above method works. Ideally fix that by having <code>np.nan</code> in your inputs, or alternatively ...
python|pandas
5
370,705
51,912,608
Pandas MultiIndex dataframe replace min and max with 0
<p>I have a dataframe with multiindex and trying to find a way to replace values that are equal to min or max with 0 within each <code>level = 0</code>. For example:</p> <pre><code>import pandas as pd import numpy as np d = {'index0': ['p1', 'p1', 'p1', 'p2', 'p2', 'p2', 'p2', 'p2', 'p3', 'p3', 'p3', 'p3', 'p3'], 'in...
<p>Both of these solutions <em>do not</em> use your <code>set_index</code> line, so make sure you avoid that.</p> <h3>Using <code>groupby</code>, <code>agg</code> and <code>join</code></h3> <pre><code>s = df.groupby('index0').data.agg(['min', 'max']).add_prefix('data_') out = df.set_index('index0').join(s) out.loc[ou...
python|python-3.x|pandas|multi-index
0
370,706
51,612,718
Wrong x axis on TensorBoard graphics
<p>I'm new to TensorFlow and discouraged a bit by TensorBoard summaries. Here's a simple example (from Jupyter notebook cell):</p> <pre><code>import tensorflow as tf import numpy as np !rm ./test/* tf.reset_default_graph() x = tf.get_variable('gs', initializer=tf.zeros_initializer, shape=(), trainable=False) inc_x ...
<p>I found an answer. It isn't a displaying issue.</p> <p>The <code>FileWriter</code> just should be closed manually here. Then it will dump all the rest events into the file. It isn't closed automatically because it's a plain code inside Jupyter Notebook and reference to <code>FileWriter</code> still exists.</p>
python|tensorflow|tensorboard
0
370,707
51,787,441
resample a MultiIndex
<p>I have a <code>DataFrame</code> with a <code>MultiIndex</code>. The first level is a <code>DatetimeIndex</code> with weekly frequency. The second level is <strong>NOT</strong> consistent across groupings by the first level.</p> <p>I want to group the first level by month and take the first weeks rows.</p> <h2>Se...
<p>You could do</p> <pre><code>In [384]: date = df.index.get_level_values('Date') In [385]: firstweek = date.to_frame().groupby(date.strftime('%Y-%m')).min()['Date'] In [386]: df[date.isin(firstweek)] Out[386]: Col Date Thing 2018-01-07 A 10 B 11 2018-02-04 I 18 ...
python|pandas|dataframe|multi-index
1
370,708
51,882,778
Tensorflow: Initializing dependent variables
<p>I am trying to initialize some variables based on value of other variables. Here is a minimal script:</p> <pre><code>a = tf.Variable(1, name='a') b = a + 2 c = tf.Variable(b, name='c') d = c + 3 e = tf.Variable(d, name='e') with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.ru...
<p>If the intention is just to execute the code as it is then this does it. </p> <pre><code>with tf.Session() as sess: a = tf.Variable(1, name='a') a.initializer.run() b = a + 2 c = tf.Variable(b, name='c') d = c + 3 e = tf.Variable(d, name='e') sess.run(tf.global_variables_initializer()) ...
variables|tensorflow|initialization
0
370,709
51,942,957
Setting dataframe by using both iloc and a boolean mask (mask at multiple different index (row) values in the dataframe)
<p>I want to change the values to Nan in a pandas dataframe based on the location of Nan values in a different pandas dataframe. I want to do this at multiple locations in the array. So it works if it is at the beginning of the array where the index (row) values are the same. How do I do this if I want to set it offset...
<p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>DataFrame.iloc</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>DataFrame.mask</code></a>,...
python|pandas|dataframe|pandas-groupby|array-broadcasting
2
370,710
51,966,969
TensorFlow Dataset `.map` - Is it possible to ignore errors?
<h3>Short version:</h3> <p>When using Dataset <code>map</code> operations, is it possible to specify that any 'rows' where the <code>map</code> invocation results in an error are quietly filtered out rather than having the error bubble up and kill the whole session?</p> <h3>Specifics:</h3> <p>I have an input pipelin...
<p>For Tensorflow 2</p> <pre><code>dataset = dataset.apply(tf.data.experimental.ignore_errors()) </code></pre>
tensorflow|tensorflow-datasets
6
370,711
51,690,754
Confused by random.randn()
<p>I am a bit confused by the numpy function random.randn() which returns random values from the standard normal distribution in an array in the size of your choosing.</p> <p>My question is that I have no idea when this would ever be useful in applied practices.</p> <p>For reference about me I am a complete programmi...
<p>The Python function randn is incredibly useful for adding in a random noise element into a dataset that you create for initial testing of a machine learning model. Say for example that you want to create a million point dataset that is roughly linear for testing a regression algorithm. You create a million data po...
numpy|statistics|normal-distribution
1
370,712
51,992,344
Efficient pairwise calculations with pandas
<p>Given some rows of categorical data, I want to calculate a pairwise matrix with the number of differences between those rows. </p> <p>For example, comparing a row with the values <code>[1, 0, 0, 1]</code> to a row with values <code>[0, 0, 1, 1]</code> would give a resulting value of 2, because indices 0 and 2 diffe...
<p>Use broadcasted XOR.</p> <pre><code>(shortened.values ^ shortened.values[:, None]).sum(2) array([[0, 1, 2], [1, 0, 3], [2, 3, 0]]) </code></pre> <p>XOR is the easiest (and fastest) way of checking whether two bits are the same. This should work as long as your input is binary.</p> <p>Note that this...
python|pandas|loops|dataframe|iteration
2
370,713
51,826,272
Pandas Top n % of grouped sum
<p>I work for a company and am trying to calculate witch products produced the top 80% of Gross Revenue in different years.</p> <p>Here is a short example of my data:</p> <pre><code>Part_no Revision Gross_Revenue Year 1 a 1 2014 2 a 2 2014 3 ...
<p>You can using <code>cumsum</code> </p> <pre><code>df[df.groupby('Year').Gross_Revenue.cumsum().div(df.groupby('Year').Gross_Revenue.transform('sum'),axis=0)&lt;0.8] Out[589]: Part_no Revision Gross_Revenue Year 1 2 a 2 2014 2 3 c 2 2014 3 4 ...
python-3.x|pandas|pandas-groupby|percentile
1
370,714
51,663,930
Convert and order timestamps
<p>I have a pandas df column of timestamps that contain HH:MM before midnight and HH:MM:SS after midnight. Eventually I want to sort these values.</p> <pre><code>import pandas as pd d = ({ 'A' : ['08:00','12:00','24:00:00','20:00','16:00','26:00:00'], }) df = pd.DataFrame(data=d) </code></pre> <p>I can't ad...
<p>Using string slicing:</p> <pre><code>df['A'] = df['A'].str[:5] + ':00' print(df) A 0 08:00:00 1 12:00:00 2 24:00:00 3 20:00:00 4 16:00:00 5 26:00:00 </code></pre>
python|pandas|sorting|time
1
370,715
51,845,703
Apply different variables across different date range in Pandas
<p>I have a dataframe with dates and values from column A to H. Also, I have some fixed variables X1=5, X2=6, Y1=7,Y2=8, Z1=9</p> <pre><code>Date A B C D E F G H 0 2018-01-02 00:00:00 7161 7205 -44 54920 73 7 5 47073 1 2018-01-03 00:00:00 7101 7147 -...
<p>You can use <code>np.select</code> to define a value based on a condition:</p> <pre><code>cond = [df.Date.between('2018-01-01','2018-01-10'), df.Date.between('2018-01-11','2018-01-25')] values = [(df['A']+df['B']+df['C'])*X1*Y1+Z1, (df['A']+df['B']+df['C'])*X2*Y2+Z1] # select values depending on the condition df['...
python|python-3.x|pandas|dataframe
0
370,716
51,814,299
Indexing on sampled Pandas DataFrame
<p>I've been puzzled again by pandas dataframe indexing under Python context . I tried to get the first element of a column, by calling <code>df[colname][0]</code>. However, it worked for a dataframe directly read from file but did not work for a sampled/sliced dataframe with reporting the error `KeyError 0'. May I ask...
<p>It is never a good idea to have a ][ in your code. That returns unexpected results sometimes because you wouldn't be working on the actual copy frame but on an internal copy. So use this instead</p> <pre><code>df.iloc[0, x] # if the column you need is the xth one, then it is x, you can know by calling df.columns an...
python|pandas
0
370,717
51,878,141
Faster alternative than a loop to create a numpy array
<p>I have an array which contains point clouds (about 100 ladar points). I need to create a set of numpy arrays as quickly as possible.</p> <pre><code>sweep = np.empty( shape=(len(sweep.points),), dtype=[ ('point', np.float64, 3), ('intensity', np.float32), ## ..... more fields .... ...
<p>It's slightly faster to use a list comprehension to format the data and pass it directly to a numpy array:</p> <pre><code>np.array([((point.x, point.y, point.z), point.intensity) for point in points], dtype=[('point', np.float64, 3), ('intensity', np.float32)]) </code></pre>
numpy
2
370,718
51,889,394
Python Numpy: Confusion about parameterization of `random.random_sample` function
<p>What is the difference between the two different parameterizations of:</p> <p><code>np.random.random_sample((1, 2))</code> </p> <p>vs </p> <p><code>np.random.random_sample((2, 1))</code> </p> <p>in Python numpy? I don't understand how these do work and I am having a little confusion about the arguments.</p>
<p>Have you tried just typing these 2 lines of code and printing them out?</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.random.random_sample((1, 2)) &gt;&gt;&gt; b = np.random.random_sample((2, 1)) &gt;&gt;&gt; a array([[ 0.15947501, 0.18197477]]) &gt;&gt;&gt; b array([[ 0.3507456 ], [ 0.0699...
python|numpy|matrix|optional-parameters
1
370,719
51,719,099
tf.placeholder(tf.random_normal([3,1]), name='weight') -> error
<pre><code>(tensorflow / python3.6) tf.placeholder(tf.random_normal([3,1]), name='weight') -&gt; error </code></pre> <p>As it's written on the title, I got an error from</p> <pre><code>W = tf.placeholder(tf.random_normal([3,1]), name='weight') </code></pre> <p>When I input it, I got an error message which is</p> <p...
<p>You can set a placeholder's shape and type, but you can't set its initial content. If you want W to contain a 3-by-1 tensor of floats, you can use this code:</p> <pre><code>W = tf.placeholder(tf.float32, shape=(3, 1), name='weight') </code></pre> <p>To set a placeholder's value, you need to use the <code>feed_dict...
python|python-3.x|tensorflow
1
370,720
51,594,431
In pandas / numpy, how to make a PivotTable with count of string items?
<p>In python3 and pandas I have this dataframe:</p> <pre><code>df_selecao_atual.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 63 entries, 2 to 72 Data columns (total 24 columns): nome 63 non-null object nome_completo 63 non-null object partido 63 non-nul...
<p>You can use:</p> <pre><code>df_selecao_atual.pivot_table(index=['tipo','nome'],aggfunc='size') </code></pre> <p>Or:</p> <pre><code>df_selecao_atual.groupby(['tipo','nome']).size() </code></pre>
python|pandas|numpy|pivot-table
1
370,721
51,904,101
Converting str to datetime makes all the values go to NaTType
<p>I have a Pandas dataframe with dates for the last two property purchases. I have subtracted one from another, labelled that column Sale Date Diff and saved to a csv file. Now, I am trying to convert the data back to datetime, but its problematic. </p> <p>Here's the data</p> <pre><code>Area Sale Dat...
<p>I'm not entirely convinced you're reading your <code>csv</code> correctly, it looks like you are splitting things into columns that shouldn't be split up. However, you don't want to cast to <code>datetime</code>, you want to cast to <code>timedelta</code>:</p> <pre><code>pd.to_timedelta(df['Sale Date Diff']) 10 ...
python|pandas|datetime
3
370,722
51,567,801
TensorFlow object detection module import issue
<p>I started to learn object detection with TensorFlow from this <a href="https://www.youtube.com/watch?v=rWFg6R5ccOc&amp;t=3s" rel="nofollow noreferrer">tutorial</a> but have some problems with <code>trainer</code> import module.</p> <p>I've downloaded Tensorflow <a href="https://github.com/tensorflow/models" rel="no...
<p>I think you have to clone the github repo for tensorflow object detection models. <a href="https://github.com/tensorflow/models" rel="nofollow noreferrer">https://github.com/tensorflow/models</a>. 3_train.py needs object_detection/trainer.py.</p> <p>Best regards.</p>
python|python-3.x|tensorflow|object-detection
-1
370,723
51,894,611
Fit data into machine learning keras model when data is huge
<p>In machine learning tutorials using keras, the code to train the machine learning model is this typical one-liner.</p> <pre><code>model.fit(X_train, Y_train, nb_epoch=5, batch_size = 128, verbose=1, validation_split=0.1) </code></pre> <p>This seems easy when t...
<p>There is a simple solution for that in Keras. You can simply use python generators, where your data is lazy loaded. If you have Images you can also use the ImageDataGenerator.</p> <pre><code>def generate_data(x, y, batch_size): while True: batch = [] for b in range(batch_size): ba...
python-3.x|numpy|machine-learning|keras|numpy-ndarray
5
370,724
51,764,437
Dex: Error converting bytecode to dex: Cause: Dex cannot parse version 52 byte code in unity andorid build
<p>I have implement Tensorflow Android as a unity plugin. After building aar and integrate to Unity project, i get error:</p> <pre><code>CommandInvokationFailure: Gradle build failed. /Library/Java/JavaVirtualMachines/jdk1.8.0_162.jdk/Contents/Home/bin/java -classpath "/Applications/Unity/PlaybackEngines/AndroidPlaye...
<p>Downgrade tensorflow to 1.4 it works for me. Another solution is using Tensorflow sharp unity</p>
android|unity3d|tensorflow
0
370,725
51,579,340
keras(-gpu) + tensorflow-gpu + anaconda on Kubuntu
<p>I have Kubuntu 18.04 and Anaconda 5.2 64. I installed the CUDA drivers and keras-gpu and tensorflow-gpu (automatically also installed tensorflow).</p> <p>The following code</p> <pre><code>from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) import keras from keras.datasets import...
<p>While you have your code running check <code>system-monitor</code> to see if GPU is involved or not. Check specifically for Gpu's memory usage</p>
python|tensorflow|keras|anaconda
1
370,726
51,685,701
Tensor must be from the same graph as Tensor
<p>I was doing some regression and then I tried to add L2 regularization into it. But it showing me following error:</p> <blockquote> <p>ValueError: Tensor("Placeholder:0", dtype=float32) must be from the same graph as Tensor("w_hidden:0", shape=(10, 36), dtype=float32_ref).</p> </blockquote> <p>The code looks li...
<p>The error message explains that your placeholder for <code>x</code> is not in the same graph as the <code>w_hidden</code> tensor - this means that we cannot complete an operation using these two tensors (presumably this is thrown when running <code>tf.matmul(weights['hidden'], x)</code>)</p> <p>The reason this has ...
python|tensorflow
1
370,727
51,983,258
python numpy (v1.15.0) fails to fit parabola
<p>I'm having trouble understanding why is numpy having such a hard time fitting parabola to this data ?</p> <pre><code>def make_poly(x, coefs): # generate a polynomial from an array of coefficients f = numpy.zeros(len(x)) for i in range(len(coefs)): f = f + coefs[-1-i]*x**i return(f) xx = [1...
<p>Searching for <code>init_dgelsd</code> on Google turns up this bug report: <a href="https://trac.macports.org/ticket/56954" rel="nofollow noreferrer">py-numpy: numpy.polyfit broken with +gfortran variant on High Sierra</a>.</p> <p>You can run</p> <pre><code>import numpy numpy.test('full') </code></pre> <p>... to run...
python|numpy|polynomial-approximations
1
370,728
51,732,586
Set maximum value to one and the rest to zero along an axis in a 3D NumPy array
<p>I have a 3D array:</p> <pre><code>volts = np.random.random((3,3,3)).round(decimals=5) &gt;&gt;&gt; volts array([[[0.94785, 0.43955, 0.74527], [0.82098, 0.52509, 0.67954], [0.72355, 0.16252, 0.03184]], [[0.25782, 0.04191, 0.6689 ], [0.18215, 0.63108, 0.52052], [0.81992, 0.36301, 0.66629]], [[...
<p>Using <strong><code>np.eye</code></strong>. In the case of multiple maxima, this will choose the first.</p> <pre><code>np.eye(volts.shape[1])[volts.argmax(2)] array([[[1., 0., 0.], [1., 0., 0.], [1., 0., 0.]], [[0., 0., 1.], [0., 1., 0.], [1., 0., 0.]], [[1., 0., 0....
python|numpy
3
370,729
51,701,334
Python: vectorizing a function call which uses an array of objects
<p>I have an array of objects. I also have a function that requires information from 2 of the objects at a time. I would like to vectorize the call to the function so that it calculates all calls at once, rather than using a loop to go through the necessary pair of objects.</p> <p>I have gotten this to work if I inste...
<p>I can't comment, sorry for misusing the answer section... </p> <p>If the data type of a numpy array is python object, the memory of the numpy array is not contiguous. Vectorization of the operation may not improve the performance much if any. Perhaps you might want to try numpy structured array instead. </p> <p>as...
python|arrays|python-3.x|numpy|vectorization
3
370,730
51,876,693
You must feed value for placeholder *_sample_weights while training UNET from VGG16
<p>I am trying to create a UNET using VGG16 as first layers.</p> <pre><code>def BuildUNet2(): keras.backend.set_learning_phase(1) inputs = keras.layers.Input(shape=(PATCH_SIZE, PATCH_SIZE, 3), name="inputs") vggModel=keras.applications.VGG16(include_top=False, input_tensor=inputs) layers = dict([(laye...
<p>The problem was with DataGenerator.<strong>getitem</strong>(): resize does not return a new numpy array. It changes the original array and returns nothing. Therefore the <strong>getitem</strong> method returned None, None. The keras error messages is misleading.</p>
tensorflow|keras
0
370,731
51,686,929
How to remove rows based on a column value where some row's column value are subset of another?
<p>Suppose I have a <code>dataframe</code> df as:-</p> <pre><code>index company url address 0 A . www.abc.contact.com 16D Bayberry Rd, New Bedford, MA, 02740, USA 1 A . www.abc.contact.com . MA, USA 2 A . www.abc.about.com . USA 3 B . www...
<p>Perhaps it is not an optimal solution, but it does the work on this small dataframe:</p> <p><strong>EDIT</strong> added checking for company names, assuming that we removed punctuation</p> <pre><code>df = pd.DataFrame({"company": ['A', 'A', 'A', 'B', 'B'], "address": ['16D Bayberry Rd, New Bedfo...
python|python-3.x|pandas
3
370,732
51,832,918
How MatMul op works in tensorflow?
<p>I notice MatMul op defined in tensorflow:</p> <p>the Shape function:</p> <pre><code>Status MatMulShape(shape_inference::InferenceContext* c) { ShapeHandle a; TF_RETURN_IF_ERROR(c-&gt;WithRank(c-&gt;input(0), 2, &amp;a)); ShapeHandle b; TF_RETURN_IF_ERROR(c-&gt;WithRank(c-&gt;input(1), 2, &amp;b)); </co...
<p>I check the code and found the batch work should be done additionally. matmul function in python/ops/math_ops.py:</p> <pre><code>def matmul (a, b, .... ... if (not a_is_sparse and not b_is_sparse) and ((a_shape is None or len(a_shape) &gt; 2) and (b_shape is None or len(b_shape) &gt; 2)): ... ...
c++|tensorflow
0
370,733
51,584,049
Anyone know why I am getting this error when trying to load dataframe to sybase table? [sql alchemy]
<p>I am trying to send append a pandas dataframe to an already created table, and I keep getting an error.</p> <p>I connected correctly to the server. Within the server, there are many databases, and then this table is within the <code>db_STAFF</code> database. Initially, I was doing <code>df.to_sql(db_STAFF.dbo.JUNES...
<p>NOTE: I'm a Sybase ASE DBA; I don't work with python/pandas/sqlalchemy/etc; so while I can tell you why ASE is generating an error, and even show you one way to correctly format the <code>create table</code> command ... I have no idea how to go about telling your application how to (re)code the <code>create table</c...
python|pandas|sqlalchemy|sybase|sap-ase
4
370,734
51,852,514
Comparing two excel file with pandas
<p>I have two excel file, A and B. A is Master copy where updated record of employee Name and Organization Name (<code>Name</code> and <code>Org</code>) is available. File B contains <code>Name</code> and <code>Org</code> columns with bit older record and many other columns which we are not interested in. </p> <pre><c...
<p>If names are unique, just concatenate A and B, and drop duplicates. Assuming <code>A</code> and <code>B</code> are your DataFrames,</p> <pre><code>df = pd.concat([A, B]).drop_duplicates(subset=['Name'], keep='first') </code></pre> <p>Or,</p> <pre><code>A = A.set_index('Name') B = B.set_index('Name') idx = B.inde...
python|excel|pandas
1
370,735
51,675,067
Pandas dataframe operations too slow on dataset with a lot of columns
<p>I have a similarity matrix (pandas Dataframe) and I want to go through each product and get the <strong>most 5 similar products</strong>, then put them in a final Dataframe called <code>itemAffinity</code> but as the similarity matrix has 31878 items(products)=> means 31878 columns and 31878 rows . Executing the bel...
<p>Let <code>df</code> be your similarity matrix (I assume the main diagonal has been already nullifed to avoid hight self-similarities). Find separately the largest column element and its row index and combine the two pieces into a new dataframe:</p> <pre><code># Toy matrix df = pd.DataFrame({'a':[0,0.1,0.2], ...
python|python-2.7|pandas
1
370,736
51,743,488
How to run tensorflow-gpu on Nvidia Quadro GV100?
<p>I am currently working as a working student and now I have trouble installing Tensorflow-gpu on a machine using a Nvidia Quadro GV100 GPU.</p> <p>On the Tensorflow homepage I found out that I need to install CUDA 9.0 and Cudnn 7.x in order to run Tensorflow-gpu 1.9. The problem is that I can't find a suitable CUDA ...
<blockquote> <p>On the Tensorflow homepage I found out that I need to install CUDA 9.0 and Cudnn 7.x in order to run Tensorflow-gpu 1.9.</p> </blockquote> <p>That is if you want to install a pre-built Tensorflow binary distribution. In that case you need to use the version of CUDA which the Tensorflow binaries were ...
tensorflow|cuda
4
370,737
51,680,450
Install PANDAS on Mac, big issue
<p>I lot of people had asked this question, but I can't find an answer that can help me overcome my problems installing PANDAS on my Mac. </p> <p>I've tried several procedures previously suggested, but they don't work. This is the error I'm getting. </p> <pre><code>Pablos-MacBook-Pro:pastudilloe$ sudo pip install pan...
<p>uninstall numpy and then try again:</p> <pre><code>pip uninstall numpy pip install pandas </code></pre>
macos|python-2.7|pandas|pip
1
370,738
51,749,364
Slicing key words to become a new category column in python
<pre><code>data = pd.Series(['ABC Company, UK', 'CDE Company, US', 'CN DEF Company']) data </code></pre> <p>[out]</p> <pre><code>0 ABC Company, UK 1 CDE Company, US 2 CN DEF Company dtype: object </code></pre> <p>How to add another column to become a dataframe that is named 'Region' to convert from UK to U...
<p>If you split the code out of your column first, you can map using a dictionary:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'country_code':['UK','US','CN']}) &gt;&gt;&gt; countries = {'UK':'United Kingdom', 'US':'United States', 'CN':'China'} &gt;&gt;&gt; df['country_name'] = ...
python|pandas
1
370,739
51,906,709
TensorFlow InvalidArgumentError/Value error occurs with small change of code
<p>The code:</p> <pre><code>import numpy as np import tensorflow as tf import pandas as pd from sklearn.model_selection import train_test_split x_data = np.linspace(0, 1000000, 1000) y_true = np.sin(x_data) y_true += np.random.randn(len(x_data)) feature_columns = [tf.feature_column.numeric_column('x', shape=[1])]...
<p>There are two distinct issues here:</p> <p>#1, don't mix numpy and tensorflow operations together. Unless you're evaluating your graph in eager execution mode, they almost always never go together.</p> <p>#2, when your network produces NaNs after a few iterations, that's usually a good sign you're running into num...
python|tensorflow|neural-network|deep-learning
1
370,740
35,797,112
Creating a panda's dataframe out of a single variable that contains a dict
<p>I am trying to get dataFrame from this function :</p> <pre><code>def total_sum(self): c = defaultdict(int) for slot in self.data: c[slot['accountLabelType']] += slot['totalPrice'] return(c) </code></pre> <p>it returns a variable that contains a whole dict with a key:value structure. </p> <p>W...
<p>Ok first, the values should be lists: let's say your dictionary is <code>dico</code>, first convert values to lists:</p> <pre><code>dico = { x:[y] for x,y in dico.iteritems() } </code></pre> <p>Then build your dataframe:</p> <pre><code>df = pandas.DataFrame.from_dict(dico) </code></pre>
python|dictionary|pandas
2
370,741
35,887,218
Python - Downloading with a List of Items
<p>I want to use the Python notebook to download several PDF files from a server. The only difference between all URLs is that they differ in one value. The URL scheme looks like:</p> <pre><code>http://file.server.com/content.asp?H=cat1&amp;NR=123456&amp;T=abc </code></pre> <p>The only value that changes is <code>NR=...
<p>You can add a <code>url</code> column with the variable value substituted:</p> <pre><code>In [254]: url = r'http://file.server.com/content.asp?H=cat1&amp;NR=123456&amp;T=abc' url Out[254]: 'http://file.server.com/content.asp?H=cat1&amp;NR=123456&amp;T=abc' In [256]: df['url'] = url.split(r'&amp;NR=')[0] + r'&amp;...
python|pandas|download|urllib2
2
370,742
36,107,946
Elegant way to get all categorical columns in pandas?
<p>Is there a way to get all categorical variables in Pandas? The best way I know is to iterate through all columns and check whether the <code>dtype</code> is categorical.</p> <p>Ultimately, I'd like a one-liner to plot all bar charts of all categorical variables.</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="noreferrer"><code>select_dtypes</code></a> and pass the <code>'category'</code> as the type to filter the df by, this will return all columns where the <code>dtype</code> matches this:</p> <pre><code>In [9]:...
numpy|pandas|scipy
7
370,743
35,909,427
TensorFlow Distributed Runtime Model Parallel CIFAR-10
<p>I have tried to modify the CIFAR-10 example to run on the new TensorFlow distributed runtime. However, I get the following error when trying to run the program:</p> <pre><code>InvalidArgumentError: Cannot assign a device to node 'softmax_linear/biases/ExponentialMovingAverage': Could not satisfy explicit device sp...
<p>I can't tell from your program, but my guess is that you also have to modify the <a href="https://github.com/tensorflow/tensorflow/blob/263d00d2710779d5c4ac66e335b2ba07d8385b6b/tensorflow/models/image/cifar10/cifar10_multi_gpu_train.py#L234" rel="nofollow">line that creates the session</a> to specify the address of ...
python|runtime|distributed|tensorflow
1
370,744
35,994,450
How to change the column order in a pandas dataframe when there are too many columns?
<p>I have a large pandas dataframe that contains many columns.</p> <p>I would like to change the order of the columns so that only a subset of them appears first. I dont care about the ordering of the rest (and there are too many variables to list them all)</p> <p>For instance, if my dataframe is like this</p> <pre>...
<p>You could use a column mask:</p> <pre><code>&gt;&gt;&gt; mysubset = ["d","f"] &gt;&gt;&gt; mask = df.columns.isin(mysubset) &gt;&gt;&gt; pd.concat([df.loc[:,mask], df.loc[:,~mask]], axis=1) d f a b c e g h i 0 2 4 5 8 7 1 1 2 3 1 2 4 1 4 2 3 1 5 3 </code></pre> <p>or use <code>sorted</...
python|pandas|dataframe
7
370,745
36,041,991
Is there a library that does array equivalency for numpy.ma?
<p>There is a numpy.testing package for comparing numpy arrays, but there doesn't appear to be an equivalent for masked arrays. Is there a library out there that does this already? </p> <p>I notice that numpy.ma itself has some comparison functions like numpy.ma.allequal, but this function doesn't seem to check that b...
<p><code>ma.masked_array.__eq__</code> is actually implemented in numpy, but maybe it does not have the semantics you are looking for? You can get to the documentation with <code>help(ma.masked_array.__eq__)</code> with a python interpreter, it states:</p> <blockquote> <p>Check whether other equals self elementwise<...
python|numpy|masking
1
370,746
36,179,760
How to get top 2 per multi index in Pandas dataframe (generated by pivot_table)
<p>I would like to show the top 2 results per the first 2 levels of a 3 level indexed dataframe (coming through pivot_table)</p> <pre><code>import pandas as pd df = pd.DataFrame([[2015,1,'A','R1',70], [2015,2,'B','R2',40], [2015,3,'C','R3',20], [2015,1,'D','R2',90], ...
<p><strong>UPDATE:</strong></p> <p>without pivoting:</p> <pre><code>In [120]: srt = df.sort_values(['year','month','profile']) In [123]: srt[srt.groupby(['year','month'])['profile'].rank(method='min') &lt;= 2] Out[123]: year month profile ranking sales 0 2015 1 A R1 70 6 2015 1 ...
python|pandas
0
370,747
36,142,156
How to maintain lexsort status when adding to a multi-indexed DataFrame?
<p>Say I construct a dataframe with pandas, having multi-indexed columns:</p> <pre><code>mi = pd.MultiIndex.from_product([['trial_1', 'trial_2', 'trial_3'], ['motor_neuron','afferent_neuron','interneuron'], ['time','voltage','calcium']]) ind = np.arange(1,11) df = pd.DataFrame(np.random.randn(10,27),inde...
<p>One approach would be to use <code>filter</code> which does a text filter on the column names:</p> <pre><code>In [117]: df['trial_1'].filter(like='voltage') Out[117]: motor_neuron afferent_neuron interneuron voltage voltage voltage 1 -0.548699 0.986121 -1.339783 2 -1.320589 ...
python|numpy|pandas|functional-programming
1
370,748
36,203,597
Remove margins from a matplotlib figure
<p>I'd like to plot a NumPy array using <code>imshow</code> in <code>matplotlib</code> and save it as a JPEG image. However, I can't manage to remove margins/paddings/borders from the image.</p> <p>My code:</p> <pre><code>plt.imshow(np.arange(20).reshape(5,4)) ; plt.axis('off') plt.savefig('test.jpg', bbox_inches='ti...
<p>As it was described in this answer: <a href="https://stackoverflow.com/a/26610602/265289">https://stackoverflow.com/a/26610602/265289</a>, it's important to also call:</p> <pre><code>fig.axes.get_xaxis().set_visible(False) fig.axes.get_yaxis().set_visible(False) </code></pre> <p>alongside <code>pad_inches=0</code>...
numpy|matplotlib
0
370,749
35,996,257
Speeding up vectorized eye-tracking algorithm in numpy
<p>I'm trying to implement Fabian Timm's eye-tracking algorithm [<a href="http://www.inb.uni-luebeck.de/publikationen/pdfs/TiBa11b.pdf]" rel="nofollow">http://www.inb.uni-luebeck.de/publikationen/pdfs/TiBa11b.pdf]</a> (found here: [<a href="http://thume.ca/projects/2012/11/04/simple-accurate-eye-center-tracking-in-open...
<p>You can perform many of those operations that save replicated elements and then perform some mathematical opertaions by directly performing the mathematical operatrions after creating singleton dimensions that would allow <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html" rel="nofollow"><...
algorithm|performance|opencv|numpy|eye-tracking
2
370,750
37,418,470
Python: Multidimensional dictionary to array
<p>I would like to convert a dictionary of the form:</p> <p><code>1: [' Ma','Ant','Man','io'] 2: [' Sc','Alb','Man'] 3: [' Sc','Alb','Sch','bre']</code></p> <p>to a matrix where all the possible values are the columns and keys are indices. Each cell of the matrix should contain 1 if the corresponding value ( col...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.html" rel="nofollow"><code>pd.DataFrame.from_dict</code></a> to load the dictionary, then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>pd.get_dummi...
python|dictionary|pandas|dataframe
4
370,751
37,294,201
How does distributed tensorflow work ? (Issue with tf.train.Server)
<p>I have some troubles with the new option of tensorflow that allows us to run distributed tensorflow.</p> <p>I just would like to run 2 tf.constant with 2 tasks but my code never ends. it looks like that :</p> <pre><code>import tensorflow as tf cluster = tf.train.ClusterSpec({"local": ["localhost:2222", "localhost...
<p>Latest version of Tensorflow provides <code>distribution strategy</code> to work multiple system.</p> <p>With example distribution strategy is explained.Take a look at this <a href="https://www.tensorflow.org/api_docs/python/tf/distribute/Strategy?version=nightly" rel="nofollow noreferrer">link</a>.</p>
python|server|cluster-computing|tensorflow|distributed
0
370,752
37,159,279
list of lists of dicts to pandas DataFrame
<p>I have a large list of a list of dicts, that I would like to transform into a pandas DataFrame. Below I have made a small example of my variable, but in reallity the outer list is much larger and each of the inner lists has more dictionaries.</p> <pre><code>all_meta = [[{"Person":1}, {"trial":2}, {"b-setting":"Off"...
<p>try this:</p> <pre><code>def merge_dicst(dlist): d = {} for x in dlist: d.update(x) return d In [97]: pd.DataFrame([merge_dicst(x) for x in all_meta]) Out[97]: ERROR Person b-setting trial 0 NaN 1 Off 2 1 NaN 2 Off 5 2 NaN 2 Off ...
python|python-3.x|pandas
0
370,753
37,436,657
Iterating pandas dataframe, checking values and creating some of them
<p>Ok, I have a (big) dataframe, something like this:</p> <pre><code> date time value 0 20100201 0 1 1 20100201 6 2 2 20100201 12 3 3 20100201 18 4 4 20100202 0 5 5 20100202 6 6 6 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a> for reshaping - you get <code>NaN</code> in missing values by column <code>time</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.D...
python|numpy|pandas
1
370,754
37,395,745
Python: using variable as function name
<p>I aim to create a function wrapper across this statement:</p> <pre><code>import pandas as pd import numpy as np MonthNumber = np.array([1,1,2,4,5,6,5]) Data = np.array([1.1,3,.52,34,15,45,34]) Data2 = Data * 1.1 Data3 = Data * 2 df = pd.DataFrame({'Month':MonthNumber, 'Data':Data}) Summary = pd.pivot_table(df,inde...
<p>It's unclear what is your input, but in Python functions are <a href="https://stackoverflow.com/questions/245192/what-are-first-class-objects">first-class objects</a> and may be passed as function argument.</p> <p>Sample implementation using *args may look like: </p> <pre><code>def summarywrapper(MonthNumber, Data...
python|numpy|pandas
2
370,755
37,462,906
Selecting rows in a DataFrame that are not in a Series
<p>So I have a DataFrame called <code>trips</code> containing the following information:</p> <pre><code>route_id service_id shape_id trip_id 0 BX12 GH_B6-Weekday BX120805 GH_B6-Weekday-004000_BX12_1 1 BX12 GH_B6-Weekday BX120809 GH_B6-Weekday-009000_BX12_1 2 BX12 GH_B6-Week...
<p><strong>UPDATE:</strong></p> <p>try <code>isin()</code> function and <code>~</code> operator</p> <p>as per @EdChum's correction in the comment - if <code>invalid_trips</code> is of Series type:</p> <pre><code>trips[~trips.trip_id.isin(invalidTrips.index)] </code></pre> <p><strong>TEST:</strong></p> <pre><code>I...
python|pandas|dataframe|series
3
370,756
37,189,241
Ignore substring in the end of string using python
<p>I Have data </p> <pre><code>213.87.137.33 - - [14/Apr/2016:17:23:36],"CONNECT api-glb-ams.smoot.apple.com:443",200 0,"SafariShared/601.1.46.42 (iPhone4,1; iPhone OS 13C75) Safari/601.1",9443 api-glb-ams.smoot.apple.com 443 1856 213.87.137.33 - - [14/Apr/2016:17:23:36],"CONNECT init.itunes.apple.com:443",200 0,"Mobi...
<h2>Change</h2> <pre><code>elif url.endswith(word for word in ignore): </code></pre> <h2>to</h2> <pre><code>elif any(url.endswith(word) for word in ignore) </code></pre> <p>It reads quite nicely: <strong>if any url ends with word from ignore, then do something.</strong></p>
python|string|pandas
0
370,757
37,470,503
How to make "value is in dateframe column" quicker
<p>I have code which has <code>userID</code>, <code>categoryID</code> and <code>date</code> as input values. I want to check if the entries are valid, e.g. if the <code>userID</code> does even exist in my dataset. It works the way I do it, but I have to wait a few seconds(!) until the main programm is executed.</p> <...
<p>Consider creating lookup indexes, then you get log-speed access. Here's an example:</p> <pre><code>import pandas as pd import numpy as np n = int(1e6) np.random.seed(0) df = pd.DataFrame({ 'uid': np.arange(n), 'catid': np.repeat('foo bar baz', n), }) </code></pre> <p>The slower version:</p> <pre><code>&...
python|pandas|dataframe|runtime|iteration
1
370,758
37,576,594
Rearrange a pandas data frame to create a 2d ratings matrix
<p>I'm trying to build a item-based recommendation system off of the yelp data set. I managed to process the data to an extent where I have the ratings given by all the users that reviewed a restaurant in a given state. Eventually I want to get to the point where I have a ratings matrix with restaurants on one axis and...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="noreferrer"><code>pivot</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="noreferrer"><code>fillna</code></a></p> <pre><code>print (df.piv...
python|pandas|dataframe|recommendation-engine|yelp
7
370,759
37,152,828
# pandas DataFrame ValueError: Shape of passed values is (1, 3), indices imply (3, 3)
<p>here is my code.</p> <p>the data's shape:</p> <pre><code>data_dict.items() Out[57]: [('Sympathetic', defaultdict(&lt;type 'int'&gt;, {'2011-10-06': 1})), ('protest', defaultdict(&lt;type 'int'&gt;, {'2011-10-06': 16})), ('occupycanada', defaultdict(&lt;type 'int'&gt;, {'2011-10-06': 1})), ('hating', defaultdict...
<p>You can add some few lines to your original code so that you can use your dictionary, seems straightforward:</p> <pre><code>df=pd.DataFrame(data_dict.items()) df=df.rename(columns = {0:'word'}) f1 = lambda x: x.values()[0] df['number']=df[1].apply(f1) df=df.rename(columns = {1:'date'}) f2 = lambda x: x.keys()[0...
python|pandas|dataframe
1
370,760
37,596,333
tensorflow store training data on GPU memory
<p>I am pretty new to tensorflow. I used to use theano for deep learning development. I notice a difference between these two, that is where input data can be stored.</p> <p>In Theano, it supports shared variable to store input data on GPU memory to reduce the data transfer between CPU and GPU.</p> <p>In tensorflow, ...
<p>If your data fits on the GPU, you can load it into a constant on GPU from e.g. a numpy array:</p> <pre><code>with tf.device('/gpu:0'): tensorflow_dataset = tf.constant(numpy_dataset) </code></pre> <p>One way to extract minibatches would be to slice that array at each step instead of feeding it using <a href="htt...
neural-network|tensorflow|theano|deep-learning
17
370,761
41,721,657
ndarray.dot() function hangs in exec
<p>I have a problem to run <em>ndarray.dot(array-like object)</em> either in Python 2.7 and 3.4 in <em>exec()</em> function - python hangs and I need to close it. Based on <a href="https://github.com/numpy/numpy/issues/5752" rel="nofollow noreferrer">Numpy "dot" hangs</a> or <a href="https://stackoverflow.com/questions...
<p>This is probably problem with line <code>'__builtins__': None,</code>. If you comment this line out, your code will work just fine. Btw. what was the purpose of this line? </p> <p><code>exec</code> does not create another thread, it executes in the current thread and any other function. The rest of the code simply ...
python|python-2.7|python-3.x|numpy
1
370,762
41,985,063
cannot convert nan to int (but there are no nans)
<p>I have a dataframe with a column of floats that I want to convert to int:</p> <pre><code>&gt; df['VEHICLE_ID'].head() 0 8659366.0 1 8659368.0 2 8652175.0 3 8652174.0 4 8651488.0 </code></pre> <p>In theory I should just be able to use:</p> <pre><code>&gt; df['VEHICLE_ID'] = df['VEHICLE_ID'].astype(i...
<p>Basically the error is telling you that you <code>NaN</code> values and I will show why your attempts didn't reveal this:</p> <pre><code>In [7]: # setup some data df = pd.DataFrame({'a':[1.0, np.NaN, 3.0, 4.0]}) df Out[7]: a 0 1.0 1 NaN 2 3.0 3 4.0 </code></pre> <p>now try to cast:</p> <pre><code>df['a']...
pandas
28
370,763
41,751,896
Conditionally extract numbers from python list
<p>I have a list of numbers like</p> <pre><code>20 40 45 60 80 </code></pre> <p>That I want to be able to say, for example the average distance between numbers &lt; 50 is 12.5.</p> <pre><code>import numpy as np from sys import argv script, pos_file, output = argv positions = [] with open(pos_file) as f: for x in...
<p>There are several things wrong with your code:</p> <ul> <li>you do not convert them to an <code>int</code> or <code>float</code>;</li> <li>you use <code>np.mean[..]</code> instead of <code>np.mean(..)</code> and <code>np.mean</code> is not scriptable.</li> </ul> <p>The solution is:</p> <pre><code>import numpy as ...
python|numpy
1
370,764
41,993,187
Why is numpy.ndarray.T so much faster than numpy.transpose(numpy.ndarray)?
<p>Recently I came across someone using <code>numpy.transpose</code> instead of <code>numpy.ndarray.T</code>. I was curious so I timed it:</p> <pre><code>from timeit import timeit import numpy as np array1015 = np.random.rand(10,15) def nptrans(): np.transpose(array1015) def npt(): array1015.T print(timeit...
<p>First, the operations are so fast it doesn't really matter if one optimizes there!</p> <pre><code>%timeit nptrans() # 100000 loops, best of 3: 2.11 µs per loop %timeit npt() # 1000000 loops, best of 3: 905 ns per loop </code></pre> <p>Optimizing this doesn't make sense except you would be doing millions of t...
python|performance|numpy
5
370,765
41,781,796
No module named 'pandastable'
<p>I'm trying to change table wrote by me on tkinter with the pandastable one in order to do the handling of data directly from a pandas.DataFrame. But despite I have already installed Anaconda3 with matlplotlib, numpy, pandas ect. modules when i would like to import pandastable I have trouble. This is the problem:</p...
<pre><code>pip install pandastable </code></pre> <p>Requires python>=3.3 or 2.7 and numpy, matplotlib and pandas.<br> See: <a href="https://github.com/dmnfarrell/pandastable" rel="nofollow noreferrer">pandastable on github</a></p> <p>edit: You may have multiple Python environments installed on your machine. Anaconda ...
pandas|tkinter|module|anaconda|python-import
3
370,766
41,890,749
How not to plot missing periods
<p>I'm trying to plot a time series data, where for certain periods there is no data. Data is loaded into dataframe and I'm plotting it using <code>df.plot()</code>. The problem is that the missing periods get connected while plotting, giving an impression that value exists in that period, while it doesn't.</p> <p>Her...
<p>Consider the <code>pd.Series</code> <code>s</code></p> <pre><code>s = pd.Series( np.arange(10), pd.date_range('2016-03-31', periods=10) ).replace({3: np.nan, 6: np.nan}) s.plot() </code></pre> <p><a href="https://i.stack.imgur.com/xtXST.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xtXST....
python|pandas|plot|time-series|nan
4
370,767
41,780,655
What is the difference between tf.group and tf.control_dependencies?
<p>Aside from <code>tf.control_dependencies</code> being a context manager (i.e. used with Python <code>with</code>), what's the difference between <code>tf.group</code> and <code>tf.control_dependencies</code>? </p> <p>When should which be used? </p> <p>Is it that <code>tf.group</code> doesn't have any particular or...
<p>If you look at the graphdef, the <code>c=tf.group(a, b)</code> produces the same graph as </p> <pre><code>with tf.control_dependencies([a, b]): c = tf.no_op() </code></pre> <p>There's no specific order in which ops will run, TensorFlow tries to execute operations as soon as it can (i.e. in parallel).</p>
tensorflow
16
370,768
42,063,672
IBM Watson Studio: Convert an ibmdbpy.frame.IdaDataFrame to pandas.core.frame.DataFrame
<p>I have a problem with the <code>ibmdbpy.frame.IdaDataFrame</code> type in IBM Watson Studio. </p> <p>I have two dataframes. The first of type <code>ibmdbpy.frame.IdaDataFrame</code> and the second of type <code>pandas.core.frame.DataFrame</code>. </p> <p>I would like to merge these two dataframes in Python. </p> ...
<p>You can convert the dataframe of type <code>ibmdbpy.frame.IdaDataFrame</code> to <code>pandas.core.frame.DataFrame</code> by using:</p> <pre><code>ida_df.as_dataframe() </code></pre> <p>Where, <code>ida_df</code> will be your dataframe of type <code>ibmdbpy.frame.IdaDataFrame</code>. This returns an object of type...
python|pandas|data-science-experience|watson-studio
2
370,769
41,837,339
Pandas multilevel index to and from sql
<p>I have a multilevel column index group object that I am trying to send and retrieve from an SQlite database. Pandas by default converts the index into a string that looks like a tuple (which is great), but the issue that I'm having is when the table is read back, the multilevel index is lost and I'm left with strin...
<pre><code>import pandas as pd import numpy as np import sqlite3 # Create a dataframe data = {'Pets and Fruits' : ["Apples", "Oranges", "Puppies", "Ducks"]*5, 'C1' : [1., 2., 3., 4.]*5, 'C2' : [1., 2., 3., 4.]*5,} df = pd.DataFrame(data) # Groupby dataframe df = df.groupby("Pets and Fruits")....
python|sql|sqlite|pandas
0
370,770
41,973,423
TypeError: 'DataFrame' object is not callable
<p>I've programmed these for calculating Variance</p> <pre class="lang-py prettyprint-override"><code>credit_card = pd.read_csv(&quot;default_of_credit_card_clients_Data.csv&quot;, skiprows=1) for col in credit_card: var[col]=np.var(credit_card(col)) </code></pre> <p>I'm getting this error</p> <pre class="lang...
<p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.var.html" rel="noreferrer"><code>DataFrame.var</code></a>:</p> <blockquote> <p>Normalized by N-1 by default. This can be changed using the ddof argument</p> </blockquote> <pre><code>var1 = credit_card.var() </code><...
python|pandas|numpy|matplotlib
10
370,771
41,823,983
Merge Pandas dataframes if string df2.domain occurs within df.url
<p>I have two dataframes: df</p> <pre><code>ID url 111 vk.com/audio/12353546 222 twitter.com/lenad 333 avito.ru/phones 333 facebook.ru/chats </code></pre> <p>and another df2</p> <pre><code>domain Maincategory Subcategory vk.com Entertainment Social Network twitter.com Entertainment Social Net...
<pre><code>import pandas as pd df1 = pd.DataFrame({'ID': ['111', '222', '333', '333'],'url':['vk.com/audio/12353546','twitter.com/lenad','avito.ru/phones','facebook.ru/chats']}) print "----original df1----" print df1 df2 = pd.DataFrame({ 'Maincaregory':['Entertainment','Entertainment','Entertainment','O...
python|pandas|merge
0
370,772
42,071,074
Multidimensional lstm tensorflow
<p>Can someone suggest an improvement on my implementation of multi-dimensional lstm?</p> <p>It is very slow and uses a lot of memory.</p> <pre><code>class MultiDimentionalLSTMCell(tf.nn.rnn_cell.RNNCell): """ Adapted from TF's BasicLSTMCell to use Layer Normalization. Note that state_is_tuple is always True. """ de...
<pre><code>def ln(tensor, scope = None, epsilon = 1e-5): """ Layer normalizes a 2D tensor along its second axis """ assert(len(tensor.get_shape()) == 2) m, v = tf.nn.moments(tensor, [1], keep_dims=True) if not isinstance(scope, str): scope = '' with tf.variable_scope(scope + 'layer_norm'): ...
tensorflow|lstm
2
370,773
41,988,036
tensorflow ImportError "@rpath/libcudart.8.0.dylib" Image Not Found
<p>Trying Tensorflow in Mac Sierra with cuda_gpu, python 2.7 from system default, no virtual environment.</p> <p>Encounter ImportError when doing basic test "import tensorflow"</p> <pre><code>dyld: warning, LC_RPATH $ORIGIN/../../_solib_darwin/_U@local_Uconfig_Ucuda_S_Scuda_Ccudart___Uexternal_Slocal_Uconfig_Ucuda_Sc...
<p>Per above comment from @Yaroslav, disabling SIP resolves the issue immediately.</p>
python|macos|installation|tensorflow
0
370,774
41,891,978
Python: How to make machine learning predictions run faster in production?
<p>I have created a machine learning model in scikit-learn which I need to deploy in production with live data. The features look like this for example:</p> <pre><code> date event_id user_id feature1 feature2 featureX... 2017-01-27 100 5555 1.23 2 2.99 2017-01-...
<pre><code># get list of unique event ids events = df['event_id'].unique().tolist() try: while True: # i don't understand why do you need this loop... start = time.time() for event in events: featureX = request.get(API_URL + event) tmp = pd.DataFrame(featureX.json()['use...
python|pandas|optimization|machine-learning|scikit-learn
1
370,775
41,749,347
How to iterate over a row in a SciPy sparse matrix?
<p>I have a sparse matrix random matrix created as follows:</p> <pre><code>import numpy as np from scipy.sparse import rand foo = rand(100, 100, density=0.1, format='csr') </code></pre> <p>I want to iterate over the cells in a particular row and perform two calculations:</p> <pre><code>row1 = foo.getrow(bar1) row2 =...
<p>Here's an approach -</p> <pre><code># Get first row summation by simply using sum method of sparse matrix sum1 = row1.sum() # Get the non-zero indices of first row idx1 = row1.indices data1 = row1.data # Or get sum1 here with : `data1.sum()`. # Get the non-zero indices of second row and corresponding data idx2 =...
python|numpy|scipy
3
370,776
42,064,624
How to get the minimum value of a row list in a pandas dataframe
<p>I have a pandas dataframe with a column made of <i>lists</i>.<br> The goal is to find the min of every list in row (in an efficient way).</p> <p>E.g.</p> <pre><code>import pandas as pd df = pd.DataFrame(columns=['Lists', 'Min']) df['Lists'] = [ [1,2,3], [4,5,6], [7,8,9] ] print(df) </code></pre> <p>The goal is th...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow noreferrer"><code>apply</code></a> with <code>min</code>:</p> <pre><code>df['Min'] = df.Lists.apply(lambda x: min(x)) print (df) Lists Min 0 [1, 2, 3] 1 1 [4, 5, 6] 4 2 [7, 8, 9] 7 ...
python|list|pandas|row|min
7
370,777
41,723,213
Using BeautifulSoup and Pandas together
<p>I am trying to parse an HTML table and move data from there into my Oracle table. I can successfully capture the data from the HTML table, but the problem I can't seem to overcome is that when I put it into a Dictionary the data is no longer delimited at all. This causes an obvious problem when trying to export beca...
<p>Try this:</p> <pre><code>In [168]: %paste def read_html_latest(filename, **kwargs): with open(filename) as f: text = f.read().replace('&lt;br&gt;', ' ') df = pd.read_html(text, **kwargs)[0] # fix column names df.columns = df.loc[0] df = df.loc[1:] return df.assign(d=pd.to_datetime(df...
python|html|pandas|beautifulsoup
1
370,778
42,124,172
Why there is an extra index when using apply in Pandas
<p>When I use <code>apply</code> to a user defined function in Pandas, it looks like python is creating an additional array. How could I get rid of it? Here is my code:</p> <pre><code>def fnc(group): x = group.C.values out = x[np.where(x &lt; 0)] return pd.DataFrame(out) data = pd.DataFrame({'A':np.random...
<p>As such, you will have no way to avoid level_2 appearing. This is because the result of your grouping is a dataframe with several items in it: pandas is cool enough to understand your wish is to broadcast these items across the grouped keys, yet it is taking the index of the dataframe as an additional level to guara...
python|pandas|apply
5
370,779
7,773,925
Normalize numpy arrays from various "image" objects
<p>please consider this reproducible example:</p> <pre><code>from PIL import Image import numpy as np import scipy.misc as sm import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.cbook as cbook import urllib datafile = cbook.get_sample_data('lena.jpg') lena_pil = Image.open(datafile) len...
<pre><code>def normalize(arr): arr=arr.astype('float32') if arr.max() &gt; 1.0: arr/=255.0 return arr </code></pre>
python|numpy|matplotlib|python-imaging-library|scipy
5
370,780
37,878,864
Groupby df column using pandas
<p>I have data</p> <pre><code>1 member_id application_name active_seconds 2 192180 Opera 6 3 192180 Opera 7 4 192180 Chrome 243 5 5433112 Chrome 52 6 5433112 Opera 34 7 5433112 ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html" rel="nofollow"><code>aggregate</code></a>:</p> <pre><code>df1 = df.groupby(['member_id', 'application_name']) .agg({'application_name':len, 'active_seconds':sum}) print (df1) ...
python|pandas|dataframe|group-by|aggregate
4
370,781
37,987,596
Plotting proportional data python (stacked barplot)
<p>I have a data set where clients answer a question, and clients belong to a certain category. The category is ordinal. I want to visualize the change in percentages as a proportional stacked barplot. Here is some test data:</p> <pre><code>answer | categ 1 1 2 1 3 2 1 2 2 3 3 ...
<p>Once I had the last dataframe, I could get it fairly easily. By doing this:</p> <pre><code>rel_data = rel_data.groupby(['answer','categ']).\ perc.sum().unstack().plot(kind='bar', stacked=True, ylim=(0,1)) </code></pre> <p>It's again dirty but at least it got the job done. The perc.sum turns it into one value p...
python|pandas|matplotlib|data-visualization
2
370,782
37,752,326
Is it possible to export a syntaxnet model (Parsey McParseface) to serve with TensorFlow Serving?
<p>I have the demo.sh working fine and I've looked at the parser_eval.py and grokked it all to some extent. However, I don't see how to serve this model using TensorFlow Serving. There are two issues I can see off the top:</p> <p>1) There's no exported model for these graphs, the graph is built at each invocation usi...
<p>So after a lot of learning, research etc. I ended up putting together a pull request for tensorflow/models and syntaxnet which achieves the goal of serving Parsey McParseface from TF serving. </p> <p><a href="https://github.com/tensorflow/models/pull/250" rel="nofollow noreferrer">https://github.com/tensorflow/mode...
tensorflow|syntaxnet|tensorflow-serving|parsey-mcparseface
6
370,783
37,972,539
Matplotlib Color y-tick Labels via Loop
<p>Given the following data frame:</p> <pre><code>import pandas as pd import numpy as np df=pd.DataFrame({'A':['A','B','C','D','E','F','G','H','I','J','K','L','M','N'], 'B':[20,25,39,43,32,17,40, 40, 34, 56, 76, 23, 54, 34]}) </code></pre> <p>I'd like to create a bubble chart where each y-tick label i...
<p>You just need to set the <code>yticks</code> before you try and set the colours. As it is, matplotlib creates 9 ticks by default, you set their colours, then you tell it you want 14 ticks after. With just a little reordering, it all works:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.ticker as m...
python-3.x|pandas|matplotlib|colors|axis-labels
2
370,784
37,940,654
Python Pandas: Get 2 set of random samples per group
<p>I have a pandas DataFrame say this:</p> <pre><code> user value 0 a 1 1 a 2 2 a 3 3 a 4 4 a 5 5 b 6 6 b 7 7 b 8 8 b 9 9 b 10 10 c 11 11 c 12 12 c 13 13 c 14 14 c 15 </code></pre> <p>Now I w...
<p>You can randomly select 3 records for each user:</p> <pre><code>a = df.groupby("user")["value"].apply(lambda x: x.sample(3)) a Out[27]: user a 3 4 0 1 2 3 b 5 6 7 8 6 7 c 14 15 10 11 13 14 dtype: int64 </code></pre> <p>And...
python|pandas
4
370,785
37,700,808
Pandas Python. Top 3 recommended items in a column
<p>I am new to Pandas and I was given a task: for every product find three other products that are most viewed together in the same session</p> <p>Data frame <code>viewed.products</code> looks like:</p> <pre><code>session products 00b3a43caf4209d2/10 1536 00b3a43caf4209d2/10 42 00b3a43caf4209d2/10 395 00b...
<p>I think you can use first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> column <code>products</code> on <code>session</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofoll...
python|pandas
1
370,786
37,998,861
Fill a list/pandas.dataframe with all the missing data combinations (like complete() in R)
<p>I have data set like the following (this is an example, it actually has 66k rows):</p> <pre><code> Type Food Loc Num 0 Fruit Banana House-1 15 1 Fruit Banana House-2 4 2 Fruit Apple House-2 6 3 Fruit Apple House-3 8 4 Vegetable Broccoli Hous...
<p>You could use a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a>.</p> <p>First you'll need a list of the valid <code>(type, food)</code> pairs. I'll get it from the data itself, rather than writing them out.</p> <pre><code>In [88]...
python|pandas|dictionary|combinations
2
370,787
37,605,531
Python script to clean .csv file based on array values
<p>I am new to Python, so please forgive me. I have pieced this together through things i've found online, however, it's still not working exactly as it should. </p> <p>I'm wanting a python script that will look in a given spreadsheet (list.csv), parse it for any "key_words", then export a file of only the rows that D...
<p>Well code looks fine and worked for me, so there is no problem with it per se.</p> <p>If you only want to check in the first row you have to split the line by ",":</p> <pre><code>key_words = ['Dog', 'Cat', 'Bird', 'Cow', ] with open('list.csv') as oldfile, open('cleaned.csv', 'w') as cleaned, open("matched.csv", ...
python|shell|csv|pandas|export-to-csv
1
370,788
37,870,187
Diagonals of a multidimensional numpy array
<p>Is there a more pythonic way of doing the following:</p> <pre><code>import numpy as np def diagonal(A): (x,y,y) = A.shape diags = [] for a in A: diags.append(np.diagonal(a)) result = np.vstack(diags) assert result.shape == (x,y) return result </code></pre>
<p><strong>Approach #1</strong></p> <p>A <em>clean</em> way would be with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.diagonal.html" rel="nofollow"><code>np.diagonal</code></a> on a transposed version of input array, like so -</p> <pre><code>np.diagonal(A.T) </code></pre> <p>Basically, ...
numpy|multidimensional-array|diagonal
4
370,789
37,636,017
What is the proper way to plot spectrum of a complex signal sampled in a narrow range?
<p>I have some complex data (small bandwidth around a set frequency) that I'm curious to plot, but I am slightly lost as to how should I proceed about interpreting a complex signal sampled in a particular range.</p> <p>So, for instance, here is the code (and my rather poor attempt at the problem) that I wrote so I hav...
<h3>Nyquist Frequency and Aliasing</h3> <p>Your signal should be a (complex) exponential oscillation at +78 kHz, sampled at 100 kHz. <a href="https://en.wikipedia.org/wiki/Nyquist_frequency" rel="noreferrer">This doesn't work</a>. What you see instead is an alias frequency at -22 kHz (78 kHz - 100 kHz). You have to ma...
python|numpy|scipy|signal-processing|fft
8
370,790
37,751,995
How to sum over two indices in python?
<p>Can someone help me out with the <code>sum</code> function ?</p> <p>I am trying to sum over two indices. I want to obtain the following result:</p> <pre><code>p_t[0, 0]+p_t[0, 1]+p_t[0, 2]+p_t[1, 0]+p_t[1, 1]+p_t[1, 2]+p_t[2,0]+p_t[2, 1]+p_t[2, 2] </code></pre> <p>, using this code:</p> <pre><code>num_products=3...
<pre><code>sum(p_t[i][j] for i in range(len(p_t)) for j in range(len(p_t[i]))) </code></pre>
python|numpy|sum
3
370,791
38,058,008
dynamically rename data frame in Python
<p>I'm trying to dynamically create datasets:</p> <pre><code>def CreateDF (indsn, outdsn): outdsn = pd.DataFrame(indsn) .... return outdsn CreateDF (phase_df, phase_df2) </code></pre> <p>But it does not work, I get the following error:</p> <blockquote> <p>NameError: name 'phase_df2' is not defined</p>...
<p>It's a little sparse because you didn't give us info on why this needs to happen, or what your source material looks like, but the general idea is:</p> <pre><code>def make_df(name): ... return df dict_of_dfs = dict() df_names = [] #a list of all the dataframes you want to create for name in df_name...
python|pandas|dataframe|dynamically-generated
4
370,792
31,303,433
TyperError when converting NaN's into number in DataFrame
<p>I have a DataFrame <code>df</code> that looks as follows and I'm trying to convert all cases where there is a <code>NaN</code> in the <code>closing_price</code> column into 100. </p> <pre><code> maturity_dt pay_freq_cd coupon closing_price FACE_VALUE 0 2017-06-30 00:00:00.0 2 0.625...
<p>Use Pandas' <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna()</code></a> method instead. In your case you can write:</p> <pre><code>df['closing_price'].fillna(100) </code></pre> <p>This replaces the <code>NaN</code> values in the 'closing_pri...
python|pandas|dataframe|types|nan
2
370,793
31,422,480
pandas multiple array calculation with different shape and missing data
<pre><code> a b c c d e 0 nan 2 4 0 nan 6 8 1 30 60 90 (-) 1 100 110 120 2 20 nan nan </code></pre> <p>Hello, I'm trying to subtract two arrays above and expecting the result like below.</p> <pre><code> a b c d e 0 0 2 4 ...
<p>found expected solution</p> <pre><code>dfA.sub(dfB, fill_value=0).fillna(0) </code></pre> <p>last part of code above</p> <pre><code>.fillna(0) </code></pre> <p>is because of</p> <p><strong>fill_value:</strong> <em>Fill missing (NaN) values with this value. If both DataFrame locations are missing, the result wil...
python|numpy|pandas
1
370,794
31,317,375
Pandas DataFrame filtering based on second column
<p>I have a Pandas Dataframe called <code>names</code> as follows:</p> <pre><code>name status A X B Y C Z D X </code></pre> <p>I want to get the name column (e.g. <code>names['name']</code>), but only with names which do NOT have the status Y or Z.</p> <p>So the result ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html#pandas.Series.isin" rel="nofollow"><code>isin</code></a> to generate the boolean mask and negate it using <code>~</code>:</p> <pre><code>In [230]: df[~df['status'].isin(['Y','Z'])] Out[230]: name status 0 A X 3 ...
pandas|filter|dataframe
3
370,795
31,226,634
Can't install numpy
<p>I'm trying to install numpy on my PC but every time I try I get some sort of error. I tried using </p> <pre><code>C:\Python34\Scripts\pip install numpy==1.9.2 </code></pre> <p>and got this</p> <pre><code> libraries ptf77blas,ptcblas,atlas not found in C:\Python34\lib libraries lapack_atlas not found in C:\Pyt...
<p>MS-windows lacks the infrastructure that makes building software on UNIX-like systems like Linux and *BSD easy. So trying to build an extension like numpy is a painful experience for most.</p> <p>If you ware stuck on ms-windows, the easiest way out is to use a Python distribution that comes with the extensions you ...
windows|python-3.x|numpy
2
370,796
31,362,837
Total number of chunks in pandas
<p>In the following script, is there a way to find out how many "chunks" there are in total?</p> <pre><code>import pandas as pd import numpy as np data = pd.read_csv('data.txt', delimiter = ',', chunksize = 50000) for chunk in data: print(chunk) </code></pre> <p>Using <code>len(chunk)</code> will only give me ...
<p>CSV, being row-based, does not allow a process to know how many lines there are in it until after it has all been scanned.</p> <p>Very minimal scanning is necessary, though, assuming the CSV file is well formed:</p> <pre><code>sum(1 for row in open('data.txt', 'r')) </code></pre> <p>This might prove useful in cas...
python|pandas
9
370,797
31,297,142
Array of complex numbers in PyopenCL
<p>I've been working on a new problem with PyopenCl in which i have to deal with complex numbers. More accurately, it would be really handy to use a 2D numpy array with complex numbers inside. Something like: np_array[np_array[C_number, C_number, ..], np_array[C_number, C_number, ..], ...]</p> <p>Then for the result...
<p>You're launching a 1D kernel, so <code>get_global_id(1)</code> will always return <code>0</code>. This explains why your kernel simply copies the first element of the <code>dados</code> array into each element of the output.</p> <p>Using a <code>float16</code> to represent one 'row' of your input only works if you ...
python|numpy|opencl|algebra|pyopencl
1
370,798
31,441,521
Making OrderedDict out of Lists
<p>I am trying to modify my code so that it will work over different time spans. I want my variable days_dict to look like months_dict.</p> <p>I have this variable called months_dict which works very well. I made it using these lines of code</p> <pre><code>graphmonths = [pivot_table[(m)].astype(float).values for m in...
<p>Alright I figured out how to make it work. First I had to make a list of Days. I took this from my dataframe. Then I used</p> <pre><code>graphdays = [pivot_table[(m)].astype(float).values for m in range(1, len(Days)+1)] days_dict = OrderedDict(list(zip(Days, graphdays))) </code></pre> <p>and it worked!</p>
python|list|pandas|pivot-table|ordereddictionary
0
370,799
64,478,663
Transpose multiple columns to be in new column using python
<p>I have a table where look like this:</p> <pre><code>id phase type status activity system list_a list_b list_c 1 str x acc pre p 0 0 0 1 str x acc pre p 1 3 2 1 pip x in prog static q ...
<p>For me working well, maybe is necessary assign to new column:</p> <pre><code>df = pd.melt(df, id_vars = ['id', 'phase', 'type', 'status', 'activity', 'system'], value_vars = ['list_a', 'list_b', 'list_c'], var_name='list_type') print (df) id phase type status activity system list_ty...
python|pandas
0