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
355,100
50,741,835
Setting piece wise learning rate in TensorFlow Estimator API
<p>I want to set up a piecewise learning rate for tensor-flow Estimator object, so far I am doing like this</p> <pre><code>boundaries = [100000, 200000, 300000] values = [0.1, 0.05, 0.01, 0.001] global_step = tf.train.get_global_step() learning_rate = tf.train.piecewise_constant(global_step, boundaries, values) </code...
<p>Use <a href="https://www.tensorflow.org/api_docs/python/tf/train/get_or_create_global_step" rel="nofollow noreferrer"><code>tf.train.get_or_create_global_step()</code></a> instead, it will create the global step for you with its expected definition.</p>
python|tensorflow|deep-learning|tensorflow-estimator
1
355,101
50,777,082
Convert 2 dataframe columns into 1 series
<p>How do you take 2 columns from a dataframe and create a series (1 column as index)?</p> <pre><code>number a one 1 two 2 three 3 </code></pre> <p>if the above was a dataframe, how would I convert it to a series with number column being the index?</p> <p>I tried:</p> <pre><code>pd.Series(df['a'], index ...
<p>Need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> and select column <code>a</code>:</p> <pre><code>s = df.set_index('number')['a'] </code></pre> <p>And for your solution is necessary add <a href="http://pandas.p...
python|pandas
1
355,102
51,082,021
Tensorflow: Difference between tf.contrib.slim and tf.layers
<p>When should I use tf.contrib.slim and when tf.layers?</p>
<p>As defined in <a href="https://www.tensorflow.org/api_docs/python/tf/contrib" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/contrib</a> the contrib module contains "volatile or experimental code".</p> <p>Generally speaking, the module <code>tf.contrib</code> contains contributed code. This...
tensorflow
2
355,103
50,681,409
Sort a Dataframe and count a value with percentages
<p>I have a DataFrame like this:</p> <pre><code>Kind Status 1 True 2 False 3 True 2 False 2 True </code></pre> <p>I counted the kinds with it <code>df.Kind.sort_values()</code> and got this: </p> <pre><code>1 1 2 3 3 1 </code></pre> <p>Now I want to see how much of Kind ...
<h3>crosstab + div</h3> <p>Using <a href="http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.crosstab.html" rel="nofollow noreferrer"><code>pandas.crosstab</code></a>:</p> <pre><code>res = pd.crosstab(df['Kind'], df['Status']) res[['Pct False', 'Pct True']] = res.div(res.sum(axis=1), axis=0) print(r...
python|python-3.x|pandas|dataframe
7
355,104
50,804,804
Pandas .min() skipna option not working for mixed string and NaN Series
<p>I have a Pandas Series that basically is a mixture of strings and <code>np.nan</code>. My goal is to take the <code>min()</code> and <code>max()</code> excluding all the <code>NaN</code>. What would be the best way to do it? </p> <p>For instance, using the Pandas built-in <code>.min()</code> doens't work:</p> <pre...
<p>Use <code>dropna</code> or boolean indexing to remove NaN then use <code>min</code>:</p> <pre><code>s.dropna().min() </code></pre> <p>or as @ALollz points out in comments</p> <pre><code>s[s.notnull()].min() </code></pre> <p>Output:</p> <pre><code>'20170101' </code></pre>
string|pandas|max|nan|min
3
355,105
51,083,523
keras trying to shape arrays to suit input
<p>I have a model with inputs like this</p> <pre><code>model = Sequential() model.add(Dense(256, input_dim=256)) model.add(Activation('relu')) </code></pre> <p>I've tried to shape the data in a number of different arrays (32x32=256 floats from grayscale images)</p> <pre><code>X = [] for fn in os.listdir('input'): ...
<p>You could reshape your input as the following (replace <code>num_of_rows</code>):</p> <pre><code>input = X.reshape((num_of_rows, 32 * 32)) </code></pre> <p>And then using the <code>input_shape</code> to specify the shape to keras:</p> <pre><code>model.add(Dense(256, input_shape=(32 * 32,))) </code></pre> <p>You ...
python|numpy|neural-network|keras
0
355,106
50,934,852
better way to automate the loops in pandas dataframe
<p>I have a df like this </p> <pre><code>user = pd.DataFrame({'User':['101','101','101','102','102','101','101','102','102','102'],'Country':['India','Japan','India','Brazil','Japan','UK','Austria','Japan','Singapore','UK'],'Count':[50,1,2,5,6,89,10.9,10,5,6]}) </code></pre> <p>and i am doing this calculations</p> <...
<p>You can perform the operations for all users by first performing a <code>groupby</code>. Then instead of applying your function row-wise use <code>np.select</code> to assign the groups.</p> <pre><code>import pandas as pd import numpy as np user['Percentile'] = user.groupby('User').Count.rank(pct=True, ascending=Tr...
python|pandas
4
355,107
50,952,916
Best way to add pandas DataFrame column to row
<p>I have to find the best way to create a new Dataframe using existing DataFrame.</p> <p>Look at this link to have full code : <a href="http://jdoodle.com/a/xKP" rel="noreferrer">jdoodle.com/a/xKP</a></p> <p>I have this kind of DataFrame :</p> <pre><code>df = pd.DataFrame({'length': [112, 214, 52,88], 'views': [100...
<p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow noreferrer"><code>pandas.melt</code></a> after elevating your index to a series:</p> <pre><code>res = pd.melt(df.assign(index=df.index), id_vars='index', value_name='stat', var_name='type_stat')\ ...
python|pandas|dataframe|reshape
3
355,108
51,036,850
Get pointer from numpy array to send image to C++
<p>I am working on a project on which I have to deal with images between <strong>Python</strong> and <strong>C++</strong>. In order to send an image from C++ to Python, I send a pointer on the first pixel of my image (being a <code>Mat</code> object from <code>OpenCV</code> library) and in Python with two for loops I u...
<p>I found a "simple" way to do that:</p> <p>In <strong>C++</strong>, the function has to take as argument a <code>void * ptr</code>, and like this I can create a Mat object using the pointer sent from Python :</p> <pre><code>void myCfunction(void* ptr){ Mat matrix = Mat(sizes, CV_8UC1, (uchar*)ptr); } </code></p...
python|c++|arrays|numpy|pointers
3
355,109
51,082,752
How to modify value in a pandas series
<p>So i have a pandas series with some values that i pass over a few times in a loop. and each time i want to append something new to the series at that index. </p> <p>e.g. I have a big dataframe called df. Then i create a new column and try to modify it if a condition is satisfied in an interation of a list called ...
<p>As the traceback suggests, you need to use <code>.loc</code>. </p> <pre><code>&gt;&gt;&gt; df.loc[someList.index(a), "mySeries"] = ... </code></pre>
python|pandas
0
355,110
50,691,053
python pandas count no order pairs
<p>I have a pandas data frame looks like:</p> <pre><code>df = pd.DataFrame(data = { 'v1': ['a', 'a', 'c', 'b', 'd', 'c', 'd', 'c', 'f', 'e'], 'v2': ['b', 'b', 'd', 'a', 'c', 'e', 'c', 'd', 'g', 'c'], 'v3': range(0,10)}) v1 v2 v3 0 a b 0 1 a b 1 2 c d 2 3 a b 3 4 c d 4 5 c e 5 ...
<p>Sort the first two columns, drop <em>consecutive</em> duplicates, and then count them:</p> <pre><code>df.iloc[:, :2] = np.sort(df.iloc[:, :2], axis=1) m = ~df.iloc[:, :2].ne(df.iloc[:, :2].shift()).cumsum().duplicated() df[m].groupby(['v1', 'v2'], as_index=False).count() v1 v2 v3 0 a b 2 1 c d 3 2 c ...
python|pandas
5
355,111
51,060,031
How to format a dataframe in Python with multiple columns but a single row?
<p>I have a dataframe in Python which consists of 1 row but 100 columns. It looks like this:</p> <pre><code>_id d.0.id d.0.name d.0.dep.id d.0.dep.name d.0.dep.1.id d.0.dep.1.name .... A B C D E F G </code></pre> <p>I need to transform the dataframe to a c...
<p>Get a new dataframe with these 5 columns:</p> <pre><code>df1 = df.iloc[:,0:5] or df1=df[[_id,d.0.id,d.0.name,d.dep.id,d.dep.name]] </code></pre> <p>Save the new dataframe as csv:</p> <pre><code>df1.to_csv('./file_path') </code></pre> <p><strong>Solution for the Extended Question</strong></p> <p>Convert the sing...
python|pandas|dataframe
1
355,112
50,684,255
How to divide a row by the contents of the previous row with using loops
<p>Using a pandas DataFrame, I would like to take every ith row and divide it by the i-1th row. I would like to use vectorization (i.e., no for loops).</p> <p>e.g. If I have the following DataFrame: </p> <pre><code>1 10 2 20 8 160 32 480 </code></pre> <p>I would end up with: </p> <pr...
<p>Use, <code>div</code>, <code>shift</code>, and <code>fillna</code>:</p> <pre><code>df.div(df.shift(1)).fillna(df).astype(int) </code></pre> <p>Output:</p> <pre><code> A B 0 1 10 1 2 2 2 4 8 3 4 3 </code></pre>
python|pandas|numpy
7
355,113
51,087,484
groupby comma-separated values in single DataFrame column python/pandas
<p>As an example, let's say I have a python pandas DataFrame that is the following:</p> <pre><code># PERSON THINGS 0 Joe Candy Corn, Popsicles 1 Jane Popsicles 2 John Candy Corn, Ice Packs 3 Lefty Ice Packs, Hot Dogs </code></pre> <p>I would like to use the pandas <em>groupby</em> functionality to h...
<p>Create a series by splitting words, and use <code>value_counts</code></p> <pre><code>In [292]: pd.Series(df.THINGS.str.cat(sep=', ').split(', ')).value_counts() Out[292]: Popsicles 2 Ice Packs 2 Candy Corn 2 Hot Dogs 1 dtype: int64 </code></pre>
python|pandas|dataframe|pandas-groupby
7
355,114
50,819,737
create a basket from a Pandas DataFrame - not standard transaction dataset
<p>I'm working on a dataset using pandas. The dataset is in the form:</p> <p><strong>user_id</strong> <strong>product_id</strong></p> <blockquote> <p>user1 product1</p> <p>user2 product3</p> <p>user1 product2</p> </blockquote> <p>or maybe this is more clear:</p> <bloc...
<p>IIUUC you can get what you want with <code>pd.crosstab</code></p> <pre><code>import pandas as pd df = pd.DataFrame({'user_id': ['user1', 'user2', 'user1', 'user3', 'user3', 'user1', 'user2'], 'product_id': ['milk', 'eggs', 'milk', 'bread', 'butter', 'eggs', 'cheese']}) df1 = pd.crosstab(df.user_...
python|pandas
6
355,115
51,042,721
How to handle nested loops with tensorflow?
<p>i am new to tensorflow. I am working with keras but for creating a customized loss function i am more or less forced to write a function in tensorflow. I get stuck at the point where i have to translate this following numpy for loop into tensorflow syntax. </p> <pre><code>for j in range(grid): for k in range(m...
<p>Assuming these:</p> <ul> <li><code>lorentz.shape == (batch, grid, dim, dim)</code> and was zero before the loop. </li> <li><code>osc_stre.shape == (batch, dim, dim, modes)</code> </li> <li><code>energies.shape == (grid,)</code> </li> <li><code>e_j.shape == (batch, modes)</code></li> </ul> <p>Then:</p> <pre...
python|tensorflow|keras|nested-loops|loss-function
0
355,116
50,676,548
Why so low Prediction Rate 25 - 40 [sec/1] using Faster RCNN for custom object detection on GPU?
<p>I have trained a <code>faster_rcnn_inception_resnet_v2_atrous_coco</code> model (available <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md" rel="noreferrer">here</a>) for custom object Detection. </p> <p>For prediction, I used object detection demo <a...
<blockquote> <p><em>Can anyone <strong>figure out the problem</strong> here ?</em></p> </blockquote> <h2>Sorry for being here brutally opened &amp; straight fair<br> on<br>where the root-cause of the observed performance problem is :</h2> <p>One could not find a worse VM-setup from Azure portfolio for such a comput...
tensorflow|machine-learning|deep-learning|object-detection
2
355,117
20,379,874
Integration of normal distribution using Simpson's rule
<p>I'm trying to perform a simple integration using the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.simps.html" rel="nofollow">scipy.integrate.simps</a> function and I can't figure out the results it shows.</p> <p>Here's a MWE:</p> <pre><code>import numpy as np from scipy.integrate im...
<p>Using your sample, just sort <code>a</code> first, since it should be an array of points to sample at, and it expects them to be in order to build the approximation. Simpson's rule uses</p> <p><img src="https://i.stack.imgur.com/gfsrW.png" alt="simpsons rule"></p> <p>So it will be taking values for <code>x</code>...
python|numpy|integration
5
355,118
20,570,626
Selecting a column on a multi-index pandas DataFrame
<p>Given this DataFrame:</p> <pre><code>from pandas import DataFrame arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo'], ['one', 'two', 'one', 'two', 'one', 'two']] tuples = zip(*arrays) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) df = DataFrame(randn(3, 6), index=[1, 2, 3], column...
<p>Start with dataframe of form</p> <pre><code>&gt;&gt;&gt; df first bar baz foo second one two one two one two 1 0.085930 -0.848468 0.911572 -0.705026 -1.284458 -0.602760 2 0.385054 2.539314 0.589164 0.765126 0.210199 -0.48178...
python|matplotlib|pandas|multi-index
12
355,119
20,845,213
How to avoid pandas creating an index in a saved csv
<p>I am trying to save a csv to a folder after making some edits to the file. </p> <p>Every time I use <code>pd.to_csv('C:/Path of file.csv')</code> the csv file has a separate column of indexes. I want to avoid printing the index to csv.</p> <p>I tried: </p> <pre><code>pd.read_csv('C:/Path to file to edit.csv', ind...
<p>Use <code>index=False</code>.</p> <pre><code>df.to_csv('your.csv', index=False) </code></pre>
python|csv|indexing|pandas
1,011
355,120
20,542,552
How to speed up matrix code
<p>I have the following simple code which estimates the probability that an h by n binary matrix has a certain property. It runs in exponential time (which is bad to start with) but I am surprised it is so slow even for n = 12 and h = 9. </p> <pre><code>#!/usr/bin/python import numpy as np import itertools n = 12 h...
<p>To speed up the code above you should avoid loops. </p> <pre><code>import numpy as np import itertools def unique_rows(a): a = np.ascontiguousarray(a) unique_a = np.unique(a.view([('', a.dtype)]*a.shape[1])) return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1])) n = 12 h = 9 iters=100...
python|performance|numpy
3
355,121
20,384,291
Large matrix multiplication in Python - what is the best option?
<p>I have two boolean sparse square matrices of c. 80,000 x 80,000 generated from 12BM of data (and am likely to have orders of magnitude larger matrices when I use GBs of data).</p> <p>I want to multiply them (which produces a triangular matrix - however I dont get this since I don't limit the dot product to yield a ...
<p>If your matrices are relatively empty it might be worthwhile encoding them as a data structure of the non-False values. Say a list of tuples describing the location of the non-False values. Or a dictionary with the tuples as the keys.</p> <p>If you use e.g. a list of tuples you could use a list comprehension to fin...
python|numpy|sparse-matrix|pytables|h5py
1
355,122
20,573,310
Pandas DataFrame Matplotlib BoxPlot Boxes
<p>How to make a boxplot where each row in my dataframe object is a box in the plot?</p> <p>I have some stock data that I want to plot with a box plot. My data is from yahoo finance and includes Open, High, Low, Close, Adjusted Close and Volume data for each trading day. I want to plot a box plot where each box is 1 d...
<p>As I said in the comments, you don't really want boxplots. Instead you should be making a candlestick chart. Here's some code to get you started.</p> <pre><code>import numpy as np import pandas import matplotlib.pyplot as plt from matplotlib.finance import candlestick, candlestick2 import matplotlib.dates as mdates...
python-2.7|matplotlib|pandas|yahoo-finance
4
355,123
33,424,014
Applying function to every other column in pandas dataframe
<p>I have the below code which rounds every column in my dataframe:</p> <pre><code>def column_round(decimals): return partial(pd.Series.round, decimals=decimals) df = df.apply(column_round(2)) </code></pre> <p>I'd like to do this to every other column, in a new dataframe that I have. I believe i read somewhere ...
<p>You can do:</p> <pre><code>df[df.columns[::2]].apply(column_round(2)) </code></pre> <p>This steps over the df columns so you can sub-select them</p> <p>Example:</p> <pre><code>In [2]: df = pd.DataFrame(columns=list('abcdefgh')) df Out[2]: Empty DataFrame Columns: [a, b, c, d, e, f, g, h] Index: [] In [3]: df.c...
python|pandas
2
355,124
33,503,766
Double loop with multiple "if" conditionals
<p>I have two arrays with "a" which corresponds to "coordinates" in my problem and b corresponds to specific values of coordinates. I m trying to know the lines of "a" where i got all the 3 values that is in "b" as example i would like to print the line of [2,4,6] as i have them in "b" but nothing appears...there is a ...
<p>Try this:</p> <pre><code>for i in range(0,a.shape[0]): if (a[i,0] in b and a[i,1] in b and a[i,2] in b): print a[i] </code></pre>
python|for-loop|numpy|conditional
2
355,125
33,303,269
numpy: How to load a bounded (R1 C1 to R2 C2) matrix from file
<p>I am looking for the numpy equivalent of Matlab's</p> <p><code>M = dlmread(filename,delimiter,[R1 C1 R2 C2])</code></p> <p>In numpy's <code>loadtxt</code>, I found that you can skip first <code>n</code> rows and load selected columns but there is now way to say how to limit the rows to a fixed upper bound.</p>
<p><code>genfromtxt</code> has an additional <code>skip_footer</code> argument but you need to know total number of lines in your file.</p> <p>Or you could read the whole file and then slice over the portion you want:</p> <pre><code>M = loadtxt (filename, delimiter=delimiter) [R1:R2+1,C1:C2+1] </code></pre> <p>Or</p...
python|numpy
1
355,126
33,390,465
argpartsort/partsort of 2D array keeping original array dimensions
<p>I have a large 2D array (e.g. [1000, 100]) that I need to do an element-wise partsort on. I need to get the top n largest items in each row of the array, but I need to keep all items in their locations and replace all other entries with 0.</p> <p>E.g. for top 3 items per row of a 3x5 array:</p> <pre><code>input: ...
<p>You could do -</p> <pre><code>n = 3 # Number of elements to keep per row A[np.arange(A.shape[0])[:,None],A.argsort(1)[:,:A.shape[1]-n]] = 0 </code></pre> <p>Sample run -</p> <pre><code>In [38]: A Out[38]: array([[ 1, 85, 59, 1, 67, 33, 6, 61], [ 5, 81, 72, 14, 43, 76, 23, 23], [67, 49, 76...
python|arrays|numpy
1
355,127
33,324,270
Extract data from a compressed numpy masked array
<p>I am trying to plot a compressed numpy masked array but I am having trouble in extracting only the data. For example, I have a compressed array</p> <pre><code>print z_masked.compressed </code></pre> <p>which gives me:</p> <pre><code>&lt;bound method MaskedArray.compressed of masked_array(data = [0.0 0.01234567901...
<p>Take another look at the output of your print statement:</p> <pre> &lt<b>bound method</b> MaskedArray.compressed of masked_array(... </pre> <p><code>z_masked.compressed</code> is the <strong>method</strong> of the array that returns the non-masked data, not the data itself. You need to call it:</p> <pre><code>plt...
python|arrays|numpy
2
355,128
33,206,978
Plot sparsely populated 2d numpy array
<p>from an iterative image pattern search with decreasing step size I have a 'quality' array. Due to the nature of the search pattern the array is not fully filled. In the first iteration I go with stepsize 10, find the best spot and there search a +-10 XY range to find the true best spot. So most of the array has ever...
<p>You can initialize the array with NaN easily:</p> <pre><code>shape = (2*search_size, 2*search_size) q = np.full(shape, np.nan) </code></pre> <p>This can then be searched as normal. To find the minimum indices ignoring NaNs, you can use <code>np.nanargmin()</code></p> <pre><code>In [12]: np.nanargmin([1,-1,4,floa...
python|numpy|matplotlib
-1
355,129
33,168,775
Conditional indexing with Numpy ndarray
<p>I have a Numpy ndarray matrix of float values and I need to select spesific rows where certain columns have values satisfying certain criteria. For example lets say I have the following numpy matrix: </p> <pre><code>matrix = np.ndarray([4, 5]) matrix[0,:] = range(1,6) matrix[1,:] = range(6,11) matrix[2,:] = range(1...
<p>For a numpy based solution, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="noreferrer"><code>numpy.where</code></a> and then get the row indexes from it and then use it for indexing you matrix. Example -</p> <pre><code>matrix[np.where((1 &lt;= matrix[:,0]) &amp; (mat...
python|numpy|matrix|indexing
18
355,130
33,397,871
pandas to_csv and then read_csv results to numpy.datetime64 messed up due to utc
<p>Here is my problem in short: I am trying to write my data (containing, among other, np.datetime64 values) to csv and then read them back, and want my times not to change...</p> <p>As discussed in many places, np.datetime64 keeps everything binary and UTC in mem, but reads strings from local time. </p> <p>Here is a...
<p>The numpy constructor is simply broken and will rarely do what you want. I would simply avoid. Use instead:</p> <pre><code>pd.read_csv(StringIO(df.to_csv(index=False)),parse_dates=['Time']) </code></pre> <p>np.datetime64 is merely <em>display</em> in local timezone. It is already stored in UTC.</p> <pre><code>In ...
python|csv|pandas|datetime64
2
355,131
33,225,059
plotting a row of 3 plots using matplotlib and numpy but getting "IndexError: too many indices for array"
<p>I am trying to plot a panel of 3 plots using <code>matplotlib</code> and the <code>subplots()</code> method. I have a <code>numpy</code> array of the mean values for the data and a second array for the standard error for the mean values. I tried to create a plot but keep getting an <code>IndexError: too many indices...
<p>If you issue the <code>subplots</code> command:</p> <pre><code>f, axarr = plt.subplots(nrows = 1, ncols=3) </code></pre> <p>You will find that</p> <pre><code>In [7]: axarr.shape Out[7]: (3,) </code></pre> <p>In other words, it is a 1d array. Trying to access it with two indices <em>should</em> give an error:</p>...
python|arrays|numpy|matplotlib
4
355,132
33,092,527
Theano scan for fast computations on an array
<p>I am trying to use Theano to speed up code that is already implemented in numpy that sums the elements in an array. In numpy, the function looks like below</p> <pre><code>import numpy as np def numpy_fn(k0, kN, x): output = np.zeros_like(x) for k in range(k0, kN+1): output += k*x return output ...
<p>Building on Divakar's answer...</p> <p>The circumstances where Theano can outperform numpy are quite specific. In general, Theano will only perform well in comparison to numpy when the computation involves vectorisable operations on large tensors.</p> <p>In this case the operation can be performed very efficiently...
python|numpy|theano
2
355,133
33,090,530
How to run single function in to a number of times in python
<p>I tried to run simple function n times by using the code below:</p> <pre><code> df = pd.DataFrame() def repeat_fun(times, f, args): for i in range(times): f(args) def f(x): g = np.random.normal(0, 1, 32) mm = np.random.normal(491.22, 128.23, 32) x = 491.22+(0.557*(mm -491.22))+(g*128.23*(np.sqrt(1...
<p>Hard to know what you mean, but I assume you want the results of <code>f</code> to be stored as columns in a dataframe. If thats's the case:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame() def repeat_fun(times, f, args): for i in range(times): f(i,args) def f(iteration,df): g = n...
python|pandas|statistics|dataframe
1
355,134
33,175,702
SettingWithCopyWarning after using Pandas Dataframe filter function
<p>The objective of my code is to overwrite a dataframe with a filtered version. The following code returns the warning beneath:</p> <p>code: </p> <pre><code>df = df[df.col&gt;1] df.col2 = df.col2.astype(float) </code></pre> <p>error:</p> <pre><code>/root/.virtualenvs/data_tools/local/lib/python2.7/site-packages/p...
<p>The issue as Jeff pointed out is that I was making a view not a copy of the dataframe.</p> <p>This is what I should have written:</p> <p>df = df[df.col>1].copy(deep=True)</p> <p>df.col2 = df.col2.astype(float)</p>
python|pandas
3
355,135
33,337,798
UnicodeEncodeError when using pandas method to_sql on a dataframe with unicode column names
<p>This is my first time posting on stack overflow, so bear with me. I have been scouring the internet for an entire day and I have not been able to fix this problem.</p> <p>Basically, I have a Pandas DataFrame with unicode characters in the column names, and I am getting a UnicodeEncodeError when I try to use to_sql ...
<p>This is a bug in the current <code>to_sql</code> method, and I filed it here: <a href="https://github.com/pydata/pandas/issues/11431" rel="nofollow">https://github.com/pydata/pandas/issues/11431</a> (and will probably be fixed in version 0.17.1)</p> <p>As a workaround, I would suggest to </p> <ul> <li>remove the s...
python|pandas|unicode
0
355,136
33,282,368
Plotting a 2D heatmap with Matplotlib
<p>Using Matplotlib, I want to plot a 2D heat map. My data is an n-by-n Numpy array, each with a value between 0 and 1. So for the (i, j) element of this array, I want to plot a square at the (i, j) coordinate in my heat map, whose color is proportional to the element's value in the array.</p> <p>How can I do this?</p...
<p>The <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html" rel="noreferrer"><code>imshow()</code></a> function with parameters <code>interpolation='nearest'</code> and <code>cmap='hot'</code> should do what you want.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np a = np...
python|numpy|matplotlib
285
355,137
33,480,260
pandas drop row below each row containing an 'na'
<p>i have a dataframe with, say, 4 columns <code>[['a','b','c','d']]</code>, to which I add another column <code>['total']</code> containing the sum of all the other columns for each row. I then add another column <code>['growth of total']</code> with the growth rate of the total.</p> <p>some of the values in <code>[[...
<p>Here's one option that I think does what you're looking for:</p> <pre><code>In [76]: df = pd.DataFrame(np.arange(40).reshape(10,4)) In [77]: df.ix[1,2] = np.nan In [78]: df.ix[6,1] = np.nan In [79]: df['total'] = df.sum(axis=1, skipna=False) In [80]: df Out[80]: 0 1 2 3 total 0 0 1 2 3 6...
python|pandas
1
355,138
33,346,591
What is the difference between size and count in pandas?
<p>That is the difference between <code>groupby("x").count</code> and <code>groupby("x").size</code> in pandas ?</p> <p>Does size just exclude nil ?</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html#pandas.core.groupby.GroupBy.size"><code>size</code></a> includes <code>NaN</code> values, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.count.html#pandas.core.groupby.Grou...
python|pandas|numpy|nan|difference
150
355,139
33,127,106
Print character in a floating numpy array
<pre><code>import numpy as np from random import random x = np.array( [random() , random(), random()]) label = np.array("Ar") y = np.hstack((label,x)) print(y) </code></pre> <p>I want to add a label in front of a 3-D numpy array but it will not return a floating number </p> <pre><code>['Ar' '0.' '0.' '0.'] </code></p...
<p>The problem you are facing here i, that numpy arrays only support a single type per array. When you create the array <code>y</code> by stacking a 1D array of floats (your array <code>x</code>) and a 0D array of type <code>'&lt;U2'</code> meaning two unicode characters (<code>your array label</code>) numpy has to set...
python|arrays|numpy
2
355,140
33,405,483
Plotting in python: My arrays have same dimensions but interpreter complains that they are not
<p>I am a python newbie; trying to migrate from matlab. But I get the following error on the code below: ValueError: x and y must have same first dimension</p> <p>I dont seem to see why as my arrays both have 101 elements: </p> <pre><code>import numpy as np import scipy as sc import pylab as py import matplotlib as p...
<p>Your problem stems from some fundamental differences between Matlab and numpy/scipy.</p> <p>Firstly, arrays in python are indexed from 0, as opposed to 1 in Matlab. Therefore, the variable <code>k</code> should start from 0.</p> <p>The other issue here is that you have assumed the <code>arange(0, 10, 0.1)</code> c...
python|arrays|numpy|matplotlib|scipy
0
355,141
9,548,758
how can I find and delete overlapped slices of an image from a list?
<p>I have divided an image into objects (slices) using the method kindly contributed by unutbu and Joe Kington at this question: <a href="https://stackoverflow.com/questions/9525313/rectangular-bounding-box-around-blobs-in-a-monochrome-image-using-python">Rectangular bounding box around blobs in a monochrome image usin...
<p>Obviously you can take an O(n^2) approach that checks each blob against all other blobs and determines if it should be removed by checking if <code>blob1.dx.start &gt; blob2.dx.start and blob1.dy.start &gt; blob2.dy.start and blob1.dx.stop &lt; blob2.dx.stop and blob1.dy.stop &lt; blob2.dy.stop</code> (if this condi...
python|image-processing|numpy|scipy
1
355,142
9,597,681
read_csv converters for unknown columns
<p>I'm trying to read a csv file that holds several values in every cell and I want to encode them to a single int formatted byte to be stored in a pandas cell, (e.g. (1, 1) -> 771). For that I would like to use the converters parameter of the <code>read_csv</code> function. The problem is that I don't know the names o...
<p>You can pass integers (0, 1, 2) instead of the names. From the docstring:</p> <pre><code>converters : dict. optional Dict of functions for converting values in certain columns. Keys can either be integers or column labels </code></pre>
csv|pandas
3
355,143
9,108,837
numpy recarray strings of variable length
<p>Is it possible to initialise a numpy recarray that will hold strings, without knowing the length of the strings beforehand?</p> <p>As a (contrived) example:</p> <pre><code>mydf = np.empty( (numrows,), dtype=[ ('file_name','STRING'), ('file_size_MB',float) ] ) </code></pre> <p>The problem is that I'm constructing ...
<p>Instead of using the <code>STRING</code> dtype, one can always use <code>object</code> as dtype. That will allow any object to be assigned to an array element, including Python variable length strings. For example:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; mydf = np.empty( (2,), dtype=[('file_name...
python|numpy|recarray
27
355,144
9,305,780
Read numbers from formatted file in Python
<p>I have file with k columns of numbers (same number of elements for each columns). What is the fastest way to read it and save the numbers in each column in a separate numpy.array?</p>
<p>Try using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow"><code>genfromtxt</code></a>.</p> <p>This has the benefit of you being able to specify column names if you like, or even read into a <code>recarray</code>.</p> <p>I made a file 'tmp':</p> <pre><code>1 2 3 4...
python|input|numpy
3
355,145
9,375,878
What database is useful for replacing a dict of numpy arrays?
<p>My code is creating a <code>dict</code> (with strings as keys and numpy arrays as values), which is too big too fit into the RAM, so the program is crashing ('Cannot allocate memory','killed','aborted'). </p> <p>Having read some SO articles, I got the impression, that I would need to use a database to handle this c...
<p>sqlite would seem perfect, given that your query pattern will be very simple. </p> <p>Another option which I frequently mention is redis ( <a href="http://redis.io" rel="nofollow">http://redis.io</a> ), a key-value server. </p> <p>Memcached ( <a href="http://memcached.org/" rel="nofollow">http://memcached.org/</a>...
python|data-structures|numpy
1
355,146
5,941,113
Looking for Python package for numerical integration over a tessellated domain
<p>I was wondering if anyone knew of a numpy/scipy based python package to numerically integrate a complicated numerical function over a tessellated domain (in my specific case, a 2D domain bounded by a voronoi cell)? In the past I used a couple of packages off of the matlab file exchange, but would like to stay within...
<p>This integrates over triangles directly, not the Voronoi regions, but should be close. (Run with different numbers of points to see ?) Also it works in 2d, 3d ...</p> <pre><code>#!/usr/bin/env python from __future__ import division import numpy as np __date__ = "2011-06-15 jun denis" #...............................
python|numpy|scipy|numerical-integration
5
355,147
6,141,955
Efficiently generate a lattice of points in python
<p><strong>Help make my code faster</strong>: My python code needs to generate a 2D lattice of points that fall inside a bounding rectangle. I kludged together some code (shown below) that generates this lattice. However, this function is called many many times and has become a serious bottleneck in my application.</p>...
<p>Since <code>lower_bounds</code> and <code>upper_bounds</code> are only 2-element arrays, <em>numpy</em> might not be the right choice here. Try to replace</p> <pre><code>if all(lower_bounds &lt; lp) and all(lp &lt; upper_bounds): </code></pre> <p>with basic Python stuff:</p> <pre><code>if lower1 &lt; lp and lower...
python|optimization|numpy|matplotlib|scipy
6
355,148
66,369,370
Pandas transform columns into percentage by group
<p>I created a data frame below:</p> <pre><code>gender_mix = pd.DataFrame({ 'user': df.user_type, 'generation': df.generation, 'gender': df.gender, 'record': 1 })\ .groupby(by=['user', 'generation', 'gender'], as_index=False).agg({'record': np.sum})\ .reset_index(drop=True) user generation ...
<p>You can use <code>transform</code> after the <code>groupby</code> and assign the results directly to the column <code>'record'</code>:</p> <pre><code>gender_mix['record'] = gender_mix\ .groupby(['user', 'generation'])['record']\ .transform(lambda x: round((x/sum(x)*100)).astype(int)) </code></pre>
python|pandas|dataframe|pandas-groupby
1
355,149
66,563,709
Weighted average for each row of a pandas dataframe
<p>We have a dataframe df defined as such:</p> <pre><code>t = pd.DataFrame( { &quot;id&quot;: [&quot;id1&quot;, &quot;id2&quot;, &quot;id3&quot;, &quot;id4&quot;], &quot;A&quot;: [1, 4, 6, 12], &quot;B&quot;: [5, 8, 3, 6], &quot;C&quot;: [9, 14, 7, 10], } ) </code></pre> <p>Then I have a list:</p> <pre>...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.average.html" rel="noreferrer"><code>numpy.average</code></a> with filtered columns by list:</p> <pre><code>weight = [2, .5, 1] cols = ['A','B','C'] t['WMean'] = np.average(t[cols], weights=weight, axis=1) print (t) id A B C WMean 0 ...
python|pandas|dataframe|weighted-average
5
355,150
66,410,723
Search string from csv column and print value_counts for string vallue
<p>Ok, Im having trouble searching my csv file columns for specific text in that column and doing a value_count based on certain text found. I'm new to python and everything I search is different than how I even get my values printed.</p> <p>For instance, I see slot of data frames being searched by <code>df(df['column'...
<p>Your syntax is broken. Try this:</p> <pre><code>df[df.colC.str.contains('acct')].colC.value_counts() </code></pre> <p>Where in the square brackets part you filter out everything that does not have 'acct' as part of the string, and then you invoke value counts on the filtered part. At least that's what it seems you a...
python-3.x|pandas|csv
0
355,151
66,530,075
Identify modified rows from updated Dataframe
<p>I collect data and analyze. In this case , there are a times data collected like yesterday or last week missing a value and might get updated when records are available at a later date, or a row value might change. I mean a row value might be modified, see sample dataframe:</p> <p><strong>First dataframe to receive<...
<p>Because there are same index and columns is possible use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ne.html" rel="nofollow noreferrer"><code>DataFrame.ne</code></a> for compare for not equal and test if at least one row <code>True</code> by <a href="http://pandas.pydata.org/p...
python|pandas|dataframe
2
355,152
66,704,707
Python numpy operation does not compute correctly
<p>I stumbled onto something very peculiar and am wondering if it is a Python bug or it's something I did not properly understand with regard to Numpy arrays.</p> <p>I'm computing the Kernel trick:</p> <pre><code>(c + np.matmul(x1, x2.T)) ** n </code></pre> <p>n = nth power; c = free parameter</p> <p>Let x1 be (3,6) an...
<p>The result of operation <code>c + np.matmul(x1, x2.T)</code> is a <code>numpy.int32</code>. The problem seem to be when using the <code>**</code> operation on this class. The result will also be <code>numpy.int32</code>. But the max value for this type is 2147483647 where as the computation result is 6590815232 in y...
python|numpy
0
355,153
66,725,884
Integer overflow while calculating all possible sums of n*m matrix rows
<p>I am using this code to compute all possible sum of a <code>n x m</code> matrix. The code is working absolutely fine and it is fast too when using arrays of 32-bit integers like <code>[[777,675,888],[768,777,698]]</code>. It is using the Numpy package. However, as soon as I use 128-bit integers or bigger, I start ge...
<p>The source of the negative value is coming from integer overflows. If you want to prevent overflows, you should use sufficiently big integers. Beyond 64 bits, Numpy only support unbounded Python integers (which are not very fast). You can enable this with <code>dtype=object</code>.</p> <p>Here the corrected code:</p...
python|arrays|numpy|matrix|vector
0
355,154
66,696,366
Length of values does not match length of index - update dataframe column
<p>I have got this code:</p> <p><code>df['newCol'] = [x if x in df['subject'] else np.NAN for x in myList]</code></p> <p>The error I receive is: <code>ValueError: Length of values (97508) does not match length of index (100)</code></p> <p>What I'm trying to achieve is to check every item in <code>myList</code> (which i...
<p>Here is how:</p> <pre><code>df = pd.DataFrame({'subject':['a','b','c','d','e']}) myList = ['c','e'] df['newCol'] = df[df['subject'].apply(lambda x: x in myList)] print(df) # subject newCol 0 a NaN 1 b NaN 2 c c 3 d NaN 4 e e </code></pre>
python-3.x|pandas|list
0
355,155
66,515,449
Combine Pandas dataframes with similar columns
<p>If I have 2 Pandas DataFrames that look like this:</p> <p>dframe1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;"></th> <th style="text-align: center;">col_a</th> <th style="text-align: center;">col_b</th> <th style="text-align: center;">col_x</th> <th style=...
<p>I'm not getting that error with <code>pd.concat</code>. This is working on my end:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df1 = pd.DataFrame([[1,2,3,4,5]], index=['df1'], columns=list('abxyz')) df2 = pd.DataFrame([[6,7,8,9,10,11]], index=['df2'], columns=list('abcdxy')) pd.concat([df...
python|pandas
1
355,156
66,414,391
What is torch.randn((1, 5))?
<p>I'm confused as to why there are double parantheses instead of just <code>torch.randn(1,5)</code>.</p> <p>Is <code>torch.randn(1,5)</code> the same thing as <code>torch.randn((1,5))</code>?</p>
<p>You should check the definition of this function <a href="https://pytorch.org/docs/stable/generated/torch.randn.html#torch.randn" rel="nofollow noreferrer">here</a>.</p> <blockquote> <p>size (int...) – a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collecti...
pytorch
2
355,157
66,343,325
Splitting a txt file with many tables to a single dataframe
<p>I have a txt file which is downloaded from a website. This txt file has many observations and different tables.</p> <p>An example would be:</p> <p>Table 1</p> <pre><code>&quot;{'ID':'1','Column A':'Observation A', 'Column B':'Observation B',...}&quot; &quot;{'ID':'2','Column A':'Observation G', 'Column C':'Observat...
<p>I have come to a solution.</p> <p>As a first step, I have opened the txt file using an encoding that would not discard any of the data, including diffeerent language, or symbols as explained in the <a href="https://docs.python.org/3/library/functions.html#open" rel="nofollow noreferrer">in-built functions of python ...
python|pandas|dataframe|split|txt
0
355,158
66,488,813
"Stretch" the data-frame and fill with zeros
<p>I have this data-frame:</p> <pre><code>ID X Var1 Var2 Var3 A 1 52 16 17 A 2 73 0 20 A 3 60 42 16 A 4 15 87 73 A 5 0 18 63 B 1 66 42 0 B 3 13 28 64 B 4 0 37 0 C 1 22 16 18 C 2 10 81 82 C 3 11 ...
<p>You could use the <a href="https://pyjanitor.readthedocs.io/reference/janitor.functions/janitor.complete.html#janitor.complete" rel="nofollow noreferrer">complete</a> function from <a href="https://pyjanitor.readthedocs.io/" rel="nofollow noreferrer">pyjanitor</a>, which exposes explicitly missing rows of values:</p...
python|pandas|numpy
2
355,159
66,537,334
How are the multiple source files (.cc) compiled? in which order?
<p>I am working on a project that represents a network simulation. In this network, the signal undergoes multiple processing stages, each one represented in the library as a .cc source code file (and a .h file aswell). Now, Since the signal processing must follow an order (each layer (.cc file) does some operations on ...
<p><code>.cc</code> files are compiled in the order designated in the makefile. The order of compilation does not matter - code from a given <code>.cc</code> file is only run when it is explicitly called from a function (a small caveat here is that global data initialization may involve running code, but in theory it ...
tensorflow|linker
2
355,160
66,392,072
Adding custom names to a GeoPandas legend
<p>I have a shapefile which has an attribute table with a column I would like to make a map/plot of. The attribute values are numerical (integer). I have made two dicts to map the colors and names I want to these integers.</p> <pre><code>Palette = {0: 'black', 20: '#FFBB22', 30: '#FFFF4C', ...
<p>The <a href="https://geopandas.org/gallery/create_geopandas_from_pandas.html#from-longitudes-and-latitudes" rel="nofollow noreferrer">official reference</a> has been edited to address your question. I'm still new to geopandas and had a hard time with it. For the target points I wanted to draw, I could handle the col...
python|matplotlib|legend|geopandas
0
355,161
66,566,973
How do I create a linear regression model for a file that has about 500 columns as y variables? Working with Python
<p>This code manually selects a column from the y table and then joins it to the X table. The program then performs linear regression. Any idea how to do this for every single column from the y table?</p> <pre><code>yDF = pd.read_csv('ytable.csv') yDF.drop('Dates', axis = 1, inplace = True) XDF = pd.read_csv('Xtable.cs...
<p>You can regress multiple y's on the same X's at the same time. Something like this should work</p> <pre><code>import numpy as np from sklearn.linear_model import LinearRegression df_X = pd.DataFrame(columns = ['x1','x2','x3'], data = np.random.normal(size = (10,3))) df_y = pd.DataFrame(columns = ['y1','y2'], data =...
python|pandas|loops|linear-regression
0
355,162
66,422,239
Python transposing multiple dataframes in a list
<p>I have a few dataframes which are similar (in terms of number of rows and columns) to the 2 dataframes listed below</p> <pre><code>0 email factor1_final factor2_final factor3_final 1 john@abc.com 85% 90% 50% 2 peter@abc.com 80% 60% 60% 3 ...
<p>For me second solution working, here is small alternative:</p> <pre><code>df_list = [df1, df2] for i, df in enumerate(df_list): df_list[i] = df.set_index('email').T print (df_list[0]) email john@abc.com peter@abc.com shelby@abc.com jess@abc.com \ factor1_final 85% 80% 50%...
python|pandas|dataframe|transpose
0
355,163
66,531,778
Change bar order and legend order in plot (matplotlib/pandas)
<p>I would like to have the order of the legend and of the bars as the one defined in label_order</p> <pre><code>for feat in df.columns: label_order = ['Very Low', 'Low', 'Average', 'High', 'Very High'] df.groupby('class')[feat].value_counts().unstack(0).plot.bar() plt.ylabel('Count') plt.xlabel('Score'...
<p>The order of columns is determined by the column order in the dataframe you are plotting, therefore simply reordering the columns between unstacking and plotting will do the trick:</p> <pre class="lang-py prettyprint-override"><code>df.groupby('class')[feat].value_counts().unstack(0)[label_order].plot.bar() </code><...
python|pandas
1
355,164
66,358,974
How to extract as csv file multiple rows with single id containing all the attributes that belong to that one specific id?
<p>I am a beginner in Python and do not have much experience with it. My scenario is as follows: I have data that contains many records with different ids. Each id has multiple records (rows containing the same id) but different attributes. I extracted and grouped each attribute for each id, but I need to have each id ...
<p>This is the whole solution for my problem with the output saved into a .csv file:</p> <pre><code>import pandas as pd import io df = pd.read_csv(io.FileIO('dataset.csv'), sep=',', engine='python') df = df.drop_duplicates(subset=['id', 'procedure', 'value']) df = df.drop_duplicates(subset=['id', 'procedure']) results...
python|python-3.x|pandas|jupyter-notebook
0
355,165
66,641,594
Get index of column where consecutive values are zero in pandas df
<p>I have a pandas dataframe like below in Python</p> <pre><code> user_id 2020-03 2020-04 2020-05 2020-06 2020-07 2020-08 2020-09 2020-10 2020-11 2020-12 2021-01 2021-02 2021-03 0 5 20.0 0 0 38.0 45.0 54.0 83.0 107.0 129.0 146.0 174.0 1...
<p>You can do this with <code>df.shift</code> on <code>axis=1</code> and then checking with <code>any</code> with the condition with <code>df.where</code></p> <pre><code>u = df.drop('user_id',1) c = (u.eq(0)&amp;u.shift(-1,axis=1).eq(0)) df['first_month'] = c.idxmax(1).where(c.any(1)) #c.idxmax(1).where(c.any(1),'-') ...
python|pandas|dataframe
5
355,166
66,346,364
pandas sort within group then aggregation
<p>I am doing query analysis of search engine. User may search different query one by one on google search engine at different time in one session.</p> <p>I have data with several field: <code>session_id</code>, <code>log_time</code>, <code>query</code>, <code>feature_i</code>, etc. I want to group by <code>session_id<...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</code></a> before <code>groupby</code>, if need apply same function is possible use list of columns names:</p> <pre><code>df = (toy_data.sort_values(['sessio...
python|pandas|dataframe|sorting|group-by
4
355,167
66,454,214
Index error while creating a new dataframe
<p>Got this error while creating new dataframe. Example:</p> <pre><code>df = pd.DataFrame({'type': 20, 'status': 'good', 'info': 'text'}, index=[0]) Out[0]: TypeError: Cannot interpret '&lt;attribute 'dtype' of 'numpy.generic' objects&gt;' as a data type </code></pre> <p>I tried also pass index...
<p>I've just checked your code in my environment and it works ok.</p> <p>I assume your Pandas lib might be outdated.</p> <p>Here is the related github issue: <a href="https://github.com/numpy/numpy/issues/18355" rel="nofollow noreferrer">https://github.com/numpy/numpy/issues/18355</a></p> <p>Thanks!</p>
python|dataframe|numpy
1
355,168
66,584,157
Bound optimization using pytorch
<p>How to include bounds when using optimization method in pytorch. I have a tensor of variables, each variable has different bound.</p> <pre><code>upper_bound = torch.tensor([1,5,10], requires_grad=False) lower_bound = torch.tensor([-1,-5,-10], requires_grad=False) X = torch.tensor([10, -60, 105], require_gr...
<p>Gradient descent is not the best method to achieve constrained optimization, but here you can enforce your constraints with :</p> <pre><code>x = ((X-lower_bound).clamp(min=0)+lower_bound-upper_bound).clamp(max=0)+upper_bound </code></pre> <p>Requires two <code>clamp</code> instead of one but I could not find any nat...
optimization|pytorch|tensor|constraint-programming
1
355,169
66,669,185
pass multiple rows into a function
<p>I have a function</p> <pre><code>def get_similar_row(rows, target): &quot;&quot;&quot;Return the index of the most similar row&quot;&quot;&quot; return np.argmax(cosine_similarity(rows, [target])) get_similar_row([[1191, 3, 0, 1, 1], [3251, 2, 1, 0, 0], [1641, 1, 1, 1, 0...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>DataFrame.drop</code></a> for remove <code>id</code> column, convert to numpy array and pass to function:</p> <pre><code>#target id id1 = 3 #convert id to index if necessary df1 = df.se...
python|python-3.x|pandas|dataframe
2
355,170
66,575,963
Python - Eliminating NaN values in each row of a numpy array or pandas dataframe
<p>I have a pandas dataframe that currently looks like this</p> <pre><code>|Eriksson| NaN | Boeser | NaN | | NaN | McDavid| NaN | NaN | | ... | ... | ... | ... | </code></pre> <p>I don't care whether its converted to a Numpy array or it remains a Data Frame, but I want an output object where the...
<p>I think that this would do the trick for you:</p> <pre><code>df.apply(lambda x: pd.Series(x.dropna().values), axis=1) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame(np.random.randn(5,4)) &gt;&gt;&gt; df.iloc[1,2] = np.NaN &gt;&gt;&gt; df.iloc[0,1] = np.NaN &gt;&gt;&gt; df.iloc[2,1] = np.NaN ...
python|pandas|numpy
1
355,171
66,388,901
how do i only populate cells that has the same values in python from a csv file?
<p>I'm having a little trouble with my code, what I want to do is only populate the output to be of a certain value, meaning if I have a column which we shall label A and below column A has names ranging from A to D and I only want to print names starting with C, the problem I'm having is I'm generating all the names a...
<p>I am not sure what exactly you want to do with the names but here is some code that selects the strings beginning with a certain letter and prints them out.</p> <pre><code>import pandas as pd df = pd.DataFrame({'Names': ['betty', 'chris', 'steve', 'carly']}) letter = 'c' print(df.loc[df['Names'].str.startswith(le...
python|pandas|csv|pycharm
0
355,172
66,591,812
How to sort and count each unique value in a column in Pandas
<p>I currently have a data frame that is a reading a csv file called: &quot;wimbledons_champions_claned.csv&quot; I need to gather the data for the number of each unique nationality in the column &quot;Champion Nationality&quot;. For example, nationality that shows up in the data is &quot;AUS&quot; and I need to count ...
<p>Something like this:</p> <pre><code>df['Champion Nationality'].value_counts() </code></pre>
python|pandas|dataframe
0
355,173
66,531,198
Unable to train tensorflow 2 model in Colab
<p>I have this issue and i am using tensorflow 2 in google colab and i believe the error has something to do with path in the config file. I have used &quot;./&quot; and &quot;//&quot; and i also gave full path but i am unable to get rid of this error.</p> <blockquote> <p>tensorflow.python.framework.errors_impl.NotFoun...
<p>Issue was with the model, i have used a different model with it's config pipeline file and it works.</p>
python-3.x|google-colaboratory|tensorflow2.0
0
355,174
66,576,677
Accuracy decreasing after iteration in federated learning setting
<p>I am working on a federated learning to detect bad clients.</p> <p>Brief about federated learning - Data is divided into various clients, training is done on client side and the results are then sent by each client to central server where aggregation of the client weights is done and the aggregated model is then aga...
<p>A common problem could be that you are trying to aggregate in a no_grad() scope. Happened to me once. The optimizer was essentially resetting once every federated round even though the models are being aggregated.</p> <p>This is a hunch as I can't say more since I haven't seen any code.</p>
python|tensorflow|machine-learning|mnist|federated-learning
0
355,175
66,653,022
'numpy.concatenate' produces error: "TypeError: only integer scalar arrays can be converted to a scalar index"
<p>I am self-answering the following question as when I made the following mistake, I couldn't find an answer.</p> <pre class="lang-py prettyprint-override"><code>a = np.array([1,2,3]) b = np.array([4,5,6]) np.concatenate(a, b) </code></pre> <p>Produces the following error:</p> <blockquote> <p>TypeError: only integer ...
<p>The arrays to be concatenated need to be wrapped in parentheses:</p> <pre class="lang-py prettyprint-override"><code>np.concatenate((a, b)) &gt;&gt;&gt; array([1, 2, 3, 4, 5, 6]) </code></pre>
python|arrays|numpy
-1
355,176
66,484,841
Combination of pair elements within lists in a DataFrame
<p>I'm trying to obtain the pair combinations of elements (list elements) within a DataFrame. I need to keep the first column to determine the original 'group' of the element pairs but splitting the element lists into element pairs in new rows.</p> <p>I would have the following case:</p> <div class="s-table-container">...
<p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow noreferrer"><code>itertools.combinations</code></a> to find all combinations of elements of length 2 for each row in the dataframe. This will give you a list exploded using <a href="https://pandas.pydata.org/pandas-do...
python|pandas|dataframe|combinations
2
355,177
66,340,462
How to replace a column in dataframe for the result of a function
<p>currently I have a dataframe with a column named age, which has the age of the person in days. I would like to convert this value to year, how could I achieve that? at this moment, if one runs this command</p> <pre><code>df['age'] </code></pre> <p>the result would be something like</p> <pre><code>0 18393 1 ...
<p>As suggested:</p> <pre><code>&gt;&gt;&gt; df['age'] / 365 age 0 50.391781 1 55.419178 2 51.663014 3 48.282192 4 47.873973 </code></pre> <p>Or if you need a real year:</p> <pre><code>&gt;&gt;&gt; df['age'] // 365 age 0 50 1 55 2 51 3 48 4 47 </code></pre>
python-3.x|pandas|dataframe
1
355,178
66,680,972
How can I use numpy to change an array's shape to be in columns?
<p>I have an array:</p> <pre><code>[ [[1],[2],[3]], [[1],[2],[3]] ] # I don't know how many [[1],[2],[3]] there will be (the batch size) </code></pre> <p>I want it to become</p> <pre><code>[ [[1], [1]], [[2], [2]], [[3], [3]] ] </code></pre> <p>Doing the following <code>reshape</code> in numpy yields an inco...
<p>You're looking for <code>x.transpose([1, 0, 2])</code></p> <p><code>np.reshape</code> reshapes the dimensions without changing the order of the data. <code>np.transpose</code> allows you to change the order of specified dimensions. In this example, you are swapping dimensions 1 and 0 while leaving dimension 2 in pla...
python|arrays|numpy
1
355,179
66,605,378
How to index over a table tag in order to return a pandas df for a list of links?
<p>I am trying to get second table elements for a list of links and store them as a pandas dataframe, to accomplish this task I defined a function <code>getCitySalaryTable()</code>:</p> <pre><code>from bs4 import BeautifulSoup import lxml import requests import pandas as pd job_title_urls=['https://www.salario.com.br/...
<p>Use nth-of-type if it is truly the 2nd table</p> <pre><code>soup.select_one('table:nth-of-type(2)') </code></pre> <p>Though a class selector is faster than type selector</p> <pre><code>soup.select_one('.listas:nth-of-type(2)') </code></pre> <hr /> <pre><code>import request from bs4 import BeautifulSoup as bs soup =...
python|html|pandas|web-scraping|beautifulsoup
1
355,180
66,728,780
Neural network errors don't change
<p>I am training a model using TensorFlow. I was getting weird results when looking at my model performance. I built two models to classify images, one using a CNN and the other using a traditional ANN. Below is the code setup for each of them.</p> <pre><code>#CNN model model = Sequential() model.add(Reshape((20, 60, 3...
<p>I think the issue is from your training data, try using another data and check the results again</p>
python|tensorflow
0
355,181
66,352,991
Get a keras model to output a result and another using ma of the weights
<p>Given two keras models <code>model1</code> and <code>model2</code> with identical architectures, I need to train the first using the model weights and the second using the moving average of the model weights. Here's an example to illustrate:</p> <pre><code>from tensorflow.keras.models import Model from tensorflow.ke...
<p>Basically, you could create two copies of the same network under one model, but under different name scopes, and then at optimization time, use one optimizer to update your <code>regular</code> weights, and have another optimizer only update your <code>moving average</code> weights.</p> <h3>Data</h3> <pre class="lan...
python|tensorflow|keras|moving-average
1
355,182
66,354,661
How to fix the date and time fields Pymongo
<p>When i import my data to mongodb i get this:</p> <pre><code> _id:object(&quot;603678958a6eade21c0790b8&quot;) id1:3758 date2:2010-01-01T00:00:00.000+00:00 time3:1900-01-01T00:05:00.000+00:00 date4 :2009-12-31T00:00:00.000+00:00 time5:1900-01-01T19:05:00.000+00:00 id6 :2 id7:-79.09 ...
<p><code>strptime</code> create a datetime object from a string.</p> <p><code>strftime</code> do the opposite by creating a string from a datetime</p> <p>You will actually want to use both because you have a string, you will then create a datetime object and then parse it again in string, but with the desired format</p...
python|pandas|mongodb|datetime|time
1
355,183
66,395,492
Removing one source value when there are multiple sources
<p>I have the following dataset:</p> <pre><code>year ID Source Category Value 2010 1 A P 10 2010 1 B P 15 2010 1 A q 20 2011 2 A P 12 2011 2 B q 15 </code></pre> <p>I wanna reorganize the dataset in the follo...
<p>Try</p> <pre><code>df.drop_duplicates(subset=['year', 'Category'], keep=&quot;first&quot;) </code></pre>
python|pandas|pandas-groupby
3
355,184
66,741,051
Incrementing column headers in pandas
<p>Could you please help me to solve the below issue.</p> <p>From the initial data frame given below, I want to create a new data frame based on a column condition like this:</p> <p><code>if mean &gt; median, add 1 to A &amp; -1 to B, elif mean &lt; median, add -1 to A &amp; 1 to B, else add 0 to both A and B.</code>...
<p>Use:</p> <pre><code>#count mean and median df1 = df.agg(['mean','median']).round(2) #difference in sample data so set 0.85 df1.loc['mean', 'A/B'] = 0.85 </code></pre> <p>First transpose DataFrame and split <code>index</code> to <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference...
python|pandas
1
355,185
66,488,646
Python Numpy: perform arithmatic operations on array of numpy objects
<p>I have multiple data values saved in the database. I just want to perform arithmetic action. Below is the sample of data:-</p> <pre><code>items = [ [1,2,3,4,5], &quot;+&quot;, 5 ] </code></pre> <p>I have above mentioned array of data. Is there any posiblity by which I can perform arithmetic action? Actua...
<p>As indicated in the comments, intentions are hard to work with. But assuming the following constraints:</p> <p>Input:</p> <ul> <li>The first item is always a list, int or float</li> <li>The second item is always an operator (+, -, /, *, etc...)</li> <li>The third item is always a list, int or float</li> </ul> <p>Log...
python|python-3.x|numpy
0
355,186
66,445,867
Pandas condition over two/multiple column
<p>Below is my sample df. I want to find if a combination exist in the df.</p> <pre><code>import pandas as pd import io output = &quot;&quot;&quot; name weight performance_l performance_r Arash 62.2 85 100 Bash 91.2 90 79 Kim 88.2 85 85 ...
<p>You can use:</p> <pre><code>if len(df[(df['name'] == 'Arash') &amp; (df['performance_l'] == 90)]): print('True') else: print('False') </code></pre> <p>This should check both conditions being met in one row rather than checking those values exist in any one element in either columns.</p> <p>Explanation:</p> <...
python|pandas
0
355,187
66,470,880
File Not Found Error while Downloading Image files
<p>I am using Windows 8.1, so I have been web scraping a lot recently and have been very successful in finding out some errors as well, but now I am stuck in downloading the files as they will not download and giving me a</p> <blockquote> <p>FileNotFoundError.</p> </blockquote> <p>I have removed all the unknown charact...
<ol> <li>It seems like you don't have <code>Images</code> folder in your path.</li> <li>It's better way to use <code>os.path.join()</code> function for joining path in python.</li> </ol> <p>Try Below:</p> <pre class="lang-py prettyprint-override"><code>import os import time import pandas as pd import requests Final1 =...
python|python-3.x|pandas|error-handling|python-requests
0
355,188
66,461,902
Flattening Nested dictionary into Dataframe Python
<p>I'm trying to flatten out a nested dictionary into a pandas dataframe. I tried a few of the other answers for multiple datasets but they're all close but not quite what I want.</p> <p>I would appreciate some help on figuring out the best way this may be flattened.</p> <p>Here is an example of the dictionary's entrie...
<p>assuming this is the example that covers the issue:</p> <pre><code>example_dict = { 1:{ 'Name': &quot;Thrilling Tales of Dragon Slayers&quot;, 'IDs':{ &quot;StoreID&quot;: ['11','31'], &quot;BookID&quot;: ['12','32'], &quot;SalesID&quot;: ['13','33']}}, 2:{ 'Name': &quot;Thri...
python|pandas|dataframe|dictionary
2
355,189
66,555,069
With python, how do I find out if a string contains anything characters besides characters in another list
<p>I have a list of characters:</p> <pre><code>example_list = ['a','b','c','1','2','3'] </code></pre> <p>And I am running through a column in a pandas data frame iteratively and evaluating if something is &quot;off&quot;. Lets call the column/list I am running through value. An example of the values I am looking throug...
<p>Your <code>values</code> are lists of strings. That means, in each case you check if the <strong>complete string</strong> (like &quot;a12&quot;) is included in the list of <strong>single characters</strong> =&gt; this is never True.</p> <p>If you don't want to change the <code>values</code>, you can index the first ...
python|regex|pandas|contains
1
355,190
66,509,560
Doubling a list in numpy
<p>I'm trying to add the same copy of a list to itself to double its size.</p> <pre><code>import pandas as pd import tensorflow as tf from tensorflow.keras.preprocessing import sequence from tensorflow.keras.models import Sequential from tensorflow.keras.datasets import imdb (x_train, y_train), (x_test, y_test) = imdb....
<p>Numpy treats the <code>+</code> sign as element-wise addition between lists. Meanwhile python concatenates them. To concatenate arrays in numpy, you would do</p> <pre><code>augmented_y_train = np.concatenate((y_train, y_train)) </code></pre>
python|arrays|list|numpy
0
355,191
66,676,369
How do I remove the ValueError: Length of values (55) does not match length of index (100) in python?
<p>I Have created a list whose length is 55. The list looks like</p> <pre><code>list1 = [1653423,6415453,..........14799324] </code></pre> <p>I have already created a dataframe and I want to add the list elements to the column 'A'. I am adding the list in the dataframe like</p> <pre><code>df['A'] = list1 df.explode('A'...
<p>Assuming you have a df already with multiple columns, you can use <code>append</code>:</p> <pre><code>df1 = pd.DataFrame({'A': [1, 2, 3], 'B': ['a','b','c']}) df2 = pd.DataFrame({'A': list1}) df1 = df1.append(df2) </code></pre>
python|pandas
2
355,192
66,495,876
Issue with Label in Stacked Bar chart in Matplotlib from a Pandas Dataframe
<p>I have a Dataframe with a column (say 'Col') with values either from this list ['PO101','NI101','NE101'].</p> <p>Count is:</p> <ul> <li>PO101 = 30000</li> <li>NI101 = 5000</li> <li>NE101 = 3000</li> </ul> <p>I am trying to show how many are which on a stacked bar chart.</p> <p>I created the stacked chart using follo...
<p>Try:</p> <pre><code>(df['col'].value_counts() .to_frame().T .plot.bar(stacked=True) ) </code></pre> <p>You would get something similar to this:</p> <p><a href="https://i.stack.imgur.com/pm5Wv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pm5Wv.png" alt="enter image description here" /></a></...
python-3.x|pandas|matplotlib|legend|stacked-chart
1
355,193
66,389,270
Multiplying a float Number to a Function in Python and getting can't multiply sequence by non-int of type 'float'
<p>I have the following code written in python 2.7. Here I've defined two function, a cosine function and an exponential function and I need to multiply these functions to a float Value, but I am getting this error. I assume we can't multiply a float value to a function in <code>list()</code> format... I would be grate...
<p>Sticking to NumPy (and specifically avoiding <code>math</code>/<code>cmath</code> altogether) would just solve the issues you are observing, by completely avoiding non-broadcast-friendly containers / operations:</p> <pre><code>import numpy as np delta = 2.0 * np.pi * 1.46 * ((1.0 / 1530) - (1.0 / 1550)) def apFu...
python|python-2.7|numpy|typeerror|python-cmath
2
355,194
66,353,125
pvlib.irradiance.disc returns seemingly incorrect values on certain days
<p>I am trying to use the DISC model, to calculate DNI from GHI. It seems to return logical values on certain days, yet on others, it seems to be massively off the mark. I calculate DHI afterwards, using the standard formula of GHI - DNI * cos(θ).</p> <p>Here's a sample of my dataframe for reference:</p> <div class="s-...
<p>As @kevinsa5 pointed out, the data seems correct, as GHI is not made up of mostly DNI on cloudy days.</p>
python|pandas|numpy|pvlib
0
355,195
66,616,597
Tensorflow.js error in loading augmentation layers operation
<p>I have trained a model via tensorflow in python, using image augmentation incorporated into the model layers. However, when I converted to trained model to tensorflow.js (model.json) and run it, there is an error:</p> <pre><code>jquery-3.3.1.slim.min.js:2 Uncaught Error: Unknown layer: RandomFlip. This may be due to...
<p>There must be some sort of issue when converting the keras model to tensorflow.js format so converting it like this will work</p> <pre><code>tensorflowjs_converter --input_format keras --output_format=tfjs_graph_model G:/Deep learning/test.h5 G:/Deep learning/Test/ </code></pre>
tensorflow|tensorflow.js
3
355,196
66,680,149
how to compare two different data frames df1 df2 with specific column ( column w) and update the matched rows column AD in df1 from df2
<pre><code>df1 A B C D E F 1 xyz y z 0 1 1 xab z z 0 1 2 xyz x p 1 1 3 xmn m q 2 1 3 xyx n r 3 1 df2 A B C D E F 1 xyz x z 4 1 1 xab y q 3 2 2 xyz z p 8 3 3 xmn q m 1 4 3 xyx r r 32 5 </code></pre> <p>expected Output DF1</p> <pre><code>df1...
<p>Looking at your output I assume that you want to merge the datasets . . . ?</p> <pre><code>import pandas as pd d = {'A': [1, 1, 2, 3, 3], 'B': ['xyz', 'xab', 'xyz', 'xmn', 'xyx'], 'C': ['y', 'z', 'x', 'm', 'n'], 'D': ['z', 'z', 'p', 'q', 'r'], 'E': [0, 0, 1, 2, 3], 'F': [1, 1, 1, 1, 1]} df...
python|pandas
0
355,197
16,287,366
A better way to express a multitude of dot products?
<p>is there a better and faster way to express the following dot-products in numpy? I have the following shapes:</p> <pre><code>&gt;&gt;&gt; h.shape (600L, 400L, 3L) &gt;&gt;&gt; c.shape (400L, 3L) </code></pre> <p>I want to calculate the following, if possible without a loop:</p> <pre><code>ans = np.empty((600, 400...
<p>You can use <code>numpy.einsum</code></p> <pre><code>ans = einsum('ijk,jk-&gt;ij', h, c) </code></pre>
python|numpy
8
355,198
16,505,000
Numpy: Difference between a[i][j] and a[i,j]
<p>Coming from a Lists background in Python and that of programming languages like C++/Java, one is used to the notation of extracting elements using <code>a[i][j]</code> approach. But in <code>NumPy</code>, one usually does <code>a[i,j]</code>. Both of these would return the same result.</p> <p>What is the fundamenta...
<p>The main difference is that <code>a[i][j]</code> first creates a view onto <code>a[i]</code> and then indexes into that view. On the other hand, <code>a[i,j]</code> indexes directly into <code>a</code>, making it faster:</p> <pre><code>In [9]: a = np.random.rand(1000,1000) In [10]: %timeit a[123][456] 1000000 loop...
python|list|numpy
21
355,199
16,074,392
Getting vertical gridlines to appear in line plot in matplotlib
<p>I want to get both horizontal and vertical grid lines on my plot but only the horizontal grid lines are appearing by default. I am using a <code>pandas.DataFrame</code> from an sql query in python to generate a line plot with dates on the x-axis. I'm not sure why they do not appear on the dates and I have tried to s...
<p>You may need to give boolean arg in your calls, e.g. use <code>ax.yaxis.grid(True)</code> instead of <code>ax.yaxis.grid()</code>. Additionally, since you are using both of them you can combine into <code>ax.grid</code>, which works on both, rather than doing it once for each dimension.</p> <pre><code>ax = plt.gca...
python|matplotlib|pandas
112