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
351,300
46,005,899
tf.nn.sigmoid_cross_entropy_with_logits weights
<p>I have a multi-label problem with ~1000 classes, yet only a handful are selected at a time. When using tf.nn.sigmoid_cross_entropy_with_logits this causes the loss to very quickly approach 0 because there are 990+ 0's being predicted. </p> <pre><code>loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(l...
<p>The larger your loss is, the bigger your gradient will be. Therefore, if you multiply your loss by 1000, your gradient step will be big and can lead to divergence. Look into gradient descent and backpropagation to understand this better.</p> <p>Moreover, <code>reduce_mean</code> compute the mean of all the elements...
python|tensorflow
2
351,301
45,898,942
Pyomo solves over NVIDIA Cuda
<p>I would like to know if there is a way to solve an Pyomo Concrete Model over a GPU with using the NVIDIA Cuda.</p> <p>I checked out <a href="https://developer.nvidia.com/how-to-cuda-python" rel="nofollow noreferrer">https://developer.nvidia.com/how-to-cuda-python</a>, and saw a video about it. And It turns out if y...
<p><strong>No you can't.</strong></p> <p>In fairness one could write a book on how misguided this idea is, but let's make it simple and just point out some basic stuff (and ignore a lot of other details):</p> <ul> <li>GPUs are working differently and use other instructions than cpus</li> <li>GPUs will need some drive...
python|numpy|cuda|gpu|pyomo
6
351,302
45,954,497
In pandas, group by date from DatetimeIndex
<p>Consider the following synthetic example:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(42) ix = pd.date_range('2017-01-01', '2017-01-15', freq='1H') df = pd.DataFrame( { 'val': np.random.random(size=ix.shape[0]), 'cat': np.random.choice(['foo', 'bar'], size=ix.shape[0]) ...
<p>For first question need convert to <code>datetime</code>s with no times <a href="https://stackoverflow.com/a/45943387/2901002">like</a>:</p> <pre><code>df1 = df.groupby(['cat',df.index.floor('d')]).agg({'val': ['count', 'mean']}) #df1 = df.groupby(['cat',df.index.normalize()]).agg({'val': ['count', 'mean']}) #df1 ...
python|pandas
3
351,303
46,156,555
Reset secondary index in pandas dataframe to start at 1
<p>Suppose I construct a multi-index dataframe like the one show here:</p> <pre><code>prim_ind=np.array(range(0,1000)) for i in range(0,1000): prim_ind[i]=round(i/4) d = {'prim_ind' :prim_ind, 'sec_ind' : np.array(range(1,1001)), 'a' : np.array(range(325,1325)), 'b' : np.array(range(8318,9318))} d...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a> for count categories.</p> <pre><code>df.index = [df.index.get_level_values(0), df.groupby(level=0).cumcount() + 1] </code></pre> <p>Or better if ...
python|pandas|dataframe|multi-index
1
351,304
46,002,097
How to use Apply() and self defined function to change data in DataFrame?
<p>What is the easiest way to make some changes in the index column of different rows in a DataFrame ?</p> <pre><code>def fn(country): if any(char.isdigit() for char in country): return country[:-2] else: return country df.loc["Country"].apply(fn,axis=1) </code></pre>
<p>I cant test now. Can you try: <code>df['Country'] = df.apply(lambda row: fn(row),axis = 1)</code> and change your function argument to take the row into account (like <code>row['Country']</code>). This way you can manipulate anything you want row by row using other column values.</p>
python|pandas
0
351,305
46,026,184
Stacked horizontal bar plot, legend is inside the plot. How do I make this plot more visible
<p>The legend is inside the chart, is there a way that it does not overlap with the horizontal bar plot?</p> <p><a href="https://i.stack.imgur.com/Jzxkm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jzxkm.png" alt="bar_plot"></a></p> <p>My Data set is the following:</p> <pre><code>df=pd.DataFram...
<p>Use <a href="https://matplotlib.org/users/legend_guide.html#legend-location" rel="nofollow noreferrer"><code>bbox_to_anchor</code></a>:</p> <pre><code>ax = df.plot.barh(stacked=True, edgecolor='none') horiz_offset = 1.03 vert_offset = 1. ax.legend(bbox_to_anchor=(horiz_offset, vert_offset)) </code></pre> <p><a hr...
python|pandas|matplotlib|plot
2
351,306
46,026,935
Sample rows of pandas dataframe in proportion to counts in a column
<p>I have a large pandas dataframe with about 10,000,000 rows. Each one represents a feature vector. The feature vectors come in natural groups and the group label is in a column called <code>group_id</code>. I would like to randomly sample <code>10%</code> say of the rows but in proportion to the numbers of each <co...
<p>You can use groupby and sample</p> <pre><code>sample_df = df.groupby('group_id').apply(lambda x: x.sample(frac=0.1)) </code></pre>
python|pandas
24
351,307
45,818,796
"soft match/merge" of 2 different pandas dataframes
<p>I have 2 data sets. Below is a sample representation of the 2 datasets (the actual data sets have approximately 9000 rows of data).</p> <pre><code>Ds01=pd.dataframe({ ‘name’:[‘James', 'Henry', 'Abe', 'Brian', 'Claude'] ‘ID’:[1001, 1234,#N/A,#N/A,#N/A] ‘Amount’:[10000, 15000, 350000, 45000000, 400] }) D...
<p>I think <code>pd.merge(Ds01,Ds02,how="outer")</code> should work.</p>
python|pandas
0
351,308
45,748,469
Transform 2D array to a 3D array with overlapping strides
<p>I would convert the 2d array into 3d with previous rows by using NumPy or native functions. </p> <p>Input:</p> <pre><code>[[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15]] </code></pre> <p>Output:</p> <pre><code>[[[7,8,9], [4,5,6], [1,2,3]], [[10,11,12], [7,8,9], [4,5,6]], [[13,14,15], [10,11,12...
<p><strong>Approach #1</strong></p> <p>One approach with <a href="http://www.scipy-lectures.org/advanced/advanced_numpy/#indexing-scheme-strides" rel="noreferrer"><code>np.lib.stride_tricks.as_strided</code></a> that gives us a <code>view</code> into the input <code>2D</code> array and as such doesn't occupy anymore o...
python|arrays|numpy
7
351,309
46,078,995
Speed up sub-array shuffling and storing
<p>I have a list of integers (<code>di</code>), and another list (<code>rang_indx</code>) made up of <code>numpy</code> sub-arrays of integers (code below). For each of these sub-arrays, I need to store in a separate list (<code>indx</code>) a number of random elements, given by the <code>di</code> list.</p> <p>For wh...
<p><strong>Approach #1 :</strong> Here's one idea with the intention to keep minimal work when we loop and use one loop only -</p> <ol> <li>Create a <code>2D</code> random array in interval <code>[0,1)</code> to cover the max. length of subarrays.</li> <li>For each subarray, set the invalid places to <code>1.0</code>....
python|arrays|list|numpy|shuffle
1
351,310
46,025,990
Counting the number of values that fall in a set of between x,y,z coordinates
<p>I am trying to write a method that allows me to count the number of objects in 3 dimensions that fall in another object with 3 dimensional coordinates. You could say this object that has values in it has a radius too, so i'm trying to count the number of object inside of a sphere.</p> <p>I won't post my current scr...
<p>You could use <code>zip</code> to iterate over the galaxies + radii and then use broadcasting and boolean indexing to find matches:</p> <pre><code>result = [] for galaxy, galaxy_radius in zip(gal_pos, gal_rad): # With broadcasting you can simply subtract the positions from the galaxy center # and using abs ...
python|arrays|list|numpy
3
351,311
45,959,112
Get coefficients of a linear regression in Tensorflow
<p>I've done a simple linear regression in Tensorflow. How can I know what are the coefficients of the regression? I've read the docs but I cannot find it anywhere! (<a href="https://www.tensorflow.org/api_docs/python/tf/estimator/LinearRegressor" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf...
<p>EDIT: As <a href="https://stackoverflow.com/users/1906456">Jason Ching</a> points out, there have been some changes after this answer was posted. There are now the estimator methods <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#get_variable_names" rel="nofollow noreferrer"><code>get_vari...
python|machine-learning|tensorflow
3
351,312
46,064,280
How to turn array of array into single high dimension array?
<p>I have a Python script and somehow in my Numpy calculation I got a variable like this:</p> <pre><code>In [72]: a Out[72]: array([[ array([-0.02134025+0.1445159j , -0.02136137+0.14458584j, -0.02138250+0.14465578j, ..., -0.01568173+0.12424096j, -0.01569507+0.12429295j, -0.01570842+0.12434494j]), ...
<p>This behaviour is caused by the <code>complex</code> data type you are using. If you look carefully at your array, you can spot, that the <code>dtype</code> of the inner array is <code>object</code> and not <code>complex</code> as it should be. Please check if this is solved by setting the <code>dtype</code> of the ...
python|arrays|numpy
0
351,313
46,054,644
Custom FeatureUnion won't work?
<p>I'm trying to modify <a href="http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html" rel="nofollow noreferrer">this</a> example to use a Pandas dataframe instead of the test datasets. I am not able to do so, as <code>ItemSelector</code> does not seem to recognise the column name.</p> <p>Please do n...
<p>Yes, thats because LabelEncoder only requires a single array y whereas FeatureUnion will try sending X and y both to it. </p> <p>See this: <a href="https://github.com/scikit-learn/scikit-learn/issues/3956" rel="nofollow noreferrer">https://github.com/scikit-learn/scikit-learn/issues/3956</a></p> <p>You can use a s...
python|pandas|scikit-learn
0
351,314
45,761,167
Shouldn't preallocation of arrays in numpy be faster?
<p>I am confused why <code>test2</code> is not faster than <code>test1</code> in the following code:</p> <pre><code>import timeit setup = """ import numpy as np A = np.ones((220, 220, 220)) B = np.ones((220, 220, 220)) class store: def __init__(self): self.C = np.empty((220, 220, 220)) Z = store() """ t...
<p>Allocation is a fast operation, addition is more expensive:</p> <pre><code>In [7]: %timeit np.empty((220, 220, 220)) 1000 loops, best of 3: 472 µs per loop In [8]: u= np.ones((220, 220, 220)) In [9]: %timeit u+u 10 loops, best of 3: 73.5 ms per loop </code></pre> <p>So, even if you correctly update your array...
python|python-2.7|numpy|malloc
0
351,315
23,353,248
Define Pandas DataFrame as composite boolean condition
<p>I'm trying to do this:</p> <pre><code>data['thing'] = data['a'] &gt; 0.75 and data['b'] &gt; 0.5 </code></pre> <p>I can do this:</p> <pre><code>dummy_1 = data['a'] &gt; 0.75 </code></pre> <p>And I can do this:</p> <pre><code>dummy_2 = data['b'] &gt; 0.5 </code></pre> <p>But I can't and them.</p> <p>Is there a...
<p>need to use a boolean and condition (and the parens are important)</p> <p>docs are <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">here</a></p> <pre><code>data['thing'] = (data['a'] &gt; 0.75) &amp; (data['b'] &gt; 0.5) </code></pre>
python|pandas
2
351,316
23,209,848
Manually create dummy based on some condition, what went wrong?
<p>I have a dataset that has a column of numbers and NaNs. I want to create a new column of dummy variables for further calculation. Apparently something is wrong, because whatever I do the dummy will be 1.</p> <pre><code>import pandas as pd import numpy as np all_air = pd.read_csv('small.csv') all_air['D(0/1)']=np.n...
<p>The assignment operation</p> <pre><code>all_air['D(0/1)'] = 0 </code></pre> <p>sets the value to <code>0</code> for the entire column named <code>'D(0/1)'</code>. So in effect, each time you encounter a value of <code>n</code> where <code>n is None</code>, you set <em>the whole column</em> to 0. Likewise, when <co...
python-2.7|csv|pandas
1
351,317
23,098,146
Iteration to update 2 dimensional array
<p>Hi so essentially I have the basic text file:</p> <pre><code>3 1 0 1 0 1 0 1 1 1 </code></pre> <p>And I'm trying to create a 2 dimensional array that contains the values as integers.<br> My code so far is:</p> <pre><code>import numpy as np f = open('perc.txt', 'r') n = f.readline() j = 0 dim = int(n.rstrip(' \n')...
<p>You need to reset <code>j</code> to zero before the <code>while</code> loop.</p>
python|arrays|numpy|iteration
0
351,318
23,178,129
Getting min and max Dates from a pandas dataframe
<p>How do I get the min and max Dates from a dataframe's major axis?</p> <pre><code> value Date 2014-03-13 10000.000 2014-03-21 2000.000 2014-03-27 2000.000 2014-03-17 200.000 2014-03-17 5.000 2014-03-17 70.000 2014-03-21 200.000 2014-03-27...
<p>'Date' is your index so you want to do,</p> <pre><code>print (df.index.min()) print (df.index.max()) 2014-03-13 00:00:00 2014-03-31 00:00:00 </code></pre>
python|datetime|pandas
127
351,319
23,269,648
How to combine time range and boolean indexing?
<p>I have a DataFrame with a datetime index:</p> <pre><code>tbl.iloc[:,:2].head(5) date_time var1 var2 2011-01-01 00:05:00 97.97 1009.28 2011-01-01 00:10:00 97.53 1009.53 2011-01-01 00:15:00 97.38 1009.15 2011-01-01 00:20:00 97.23 1009.03 2011-01-01 00:25:00 97.01 10...
<p>I found a solution now:</p> <pre><code>criterion1 = tbl.index.map(lambda i: i.hour &gt;= 8) criterion2 = tbl.index.map(lambda i: i.hour &lt; 19) criterion3 = (tbl['weekday'] == 4) tbl[criterion1 &amp; criterion2 &amp; criterion3] </code></pre> <p>Is there something more elegant? </p>
python|datetime|pandas|indexing
0
351,320
23,318,012
Fastest way to count number of occurrences in Pandas
<p>What is the fastest way to compute the number of occurrences of elements within a Pandas series?</p> <p>My current fastest solution involves <code>.groupby(columnname).size()</code>. Is there anything faster within Pandas? E.g. I want something like the following:</p> <pre><code>In [42]: df = DataFrame(['a', 'b'...
<p>The <code>value_counts()</code> function in pandas does this exactly.</p> <p>Use that function on the column you want. i.e.</p> <pre><code>df['column_i_want'].value_counts() </code></pre>
python|pandas
3
351,321
23,257,699
Pandas shifting uneven timeseries data
<p>I have some irregularly stamped time series data, with timestamps and the observations at every timestamp, in pandas. Irregular basically means that the timestamps are uneven, for instance the gap between two successive timestamps is not even.</p> <p>For instance the data may look like</p> <pre><code> Timestamp...
<p>Edit: added a second, more elegant, way to do it. I don't know what will happen if you had a timestamp at 1 and two timestamps of 61. I think it will choose the first 61 timestamp but not sure.</p> <pre><code>new_stamps = pd.Series(range(df['Timestamp'].max()+1)) shifted = pd.DataFrame(new_stamps) shifted.columns =...
pandas|shift
1
351,322
22,983,638
Remove Decimal Point in a Dataframe with both Numbers and String Using Python
<p>I have a data Frame with about 50,000 records; and I noticed that ".0" have been added behind all numbers in a column. I have been trying to remove the ".0", so that the table below;</p> <pre><code>N | Movies 1 | Save the Last Dance 2 | Love and Other Drugs 3 | Dance with Me 4 | Love Actua...
<p>Use a function and apply to whole column:</p> <pre><code>In [94]: df = pd.DataFrame({'Movies':['Save the last dance', '2012.0']}) df Out[94]: Movies 0 Save the last dance 1 2012.0 [2 rows x 1 columns] In [95]: def trim_fraction(text): if '.0' in text: return text[:text...
python|pandas|dataframe
4
351,323
23,316,526
Prebuilt numpy with BLAS/ATLAS?
<p>I'm implementing a real-time LMS algorithm, and numpy.dot takes more time than my sampling time, so I need numpy to be faster (my matrices are 1D and 100 long). </p> <p>I've read about building numpy with ATLAS and such, but never done such thing and spent all my day trying to do it, with zero succes...</p> <p>Can...
<p>If you download the official binaries, they should come linked with ATLAS. If you want to make sure, check the output of <code>np.show_config()</code>. The problem is that ATLAS (Automatically Tuned Linear Algebra System) checks many different combinations and algorithms, and keeps the best at compile time. So, when...
python|numpy|scipy
4
351,324
23,081,035
Python code to perform anisotropic diffusion, having trouble running it in Anaconda
<p>The following is the python code to perform the anisotropic diffusion, however when I run it through anaconda/ipython notebook nothing is happening, I'm assuming an input image is required, any help would be greatly appreciated. </p> <pre><code>import numpy as np import warnings def anisodiff(img,niter=1,kappa=...
<p>Here's some example usage code. Paste your code above into an iPython cell and press control+Enter. Then paste the below code into a cell below and press control+Enter and you should see two images - the original image and the smoothed result.</p> <p>You can replace the lena thing with <code>from scipy.misc import ...
python|numpy|python-imaging-library|anaconda
1
351,325
35,730,161
How to convert a list of tensors of dim N to a tensor of dim N+1
<p>I need to convert a list of tensors of dimensionality N to a new tensor with dimensionality N+1 so that the new dimension would be the right most dimension.</p> <p>For example if x and y would be tensors of shape (4,3) both then I am trying to create a new tensor z of shape (4,3,2) by forming z and setting tensor x...
<p>If I'm reading you correctly, you want to <em>interleave</em> the data of the two tensors.</p> <p>You want to <code>tf.pack()</code> them together, which would form a tensor of shape <code>[2, 4, 3]</code> and then <code>tf.transpose([1, 2, 0])</code> that resulting tensor to get to the interleaving you want.</p>
tensorflow
12
351,326
35,782,747
Different versions of Python 2.7 and Numpy produce different results for the same script
<p>I have the following script:</p> <pre><code>import numpy as np pin_info = {} pinID = 4 pin_info[pinID] = {} pin_info[pinID]['matvols'] = np.array([0.4096,0.418,0.475,1.26])**2 pin_info[pinID]['matvols'][:-1] *= np.pi pin_info[pinID]['matvols'][1:] -= pin_info[pinID]['matvols'][:-1] print(pin_info) </code></pre> ...
<p>~ 0.87877816 would indeed be the correct result:</p> <ul> <li><p>Using <a href="http://www.isthe.com/chongo/tech/comp/calc/" rel="nofollow"><code>calc</code></a> (from <a href="http://packages.ubuntu.com/search?keywords=apcalc" rel="nofollow">Ubuntu package <code>apcalc</code></a>):</p> <pre class="lang-sh prettyp...
python-2.7|debugging|numpy
2
351,327
35,609,555
Group by date in pandas in order to plot categorical distributions
<p>I am trying to plot data that has been binned by certain date ranges. </p> <p>Say for example I have the following dataframe:</p> <pre><code>dates = pd.date_range(start=pd.datetime(2013, 6, 1), periods=50, freq='D') df = pd.DataFrame(np.random.normal(10, 3, 50), columns=['x'], index=dates) df[:3] x 201...
<p>Perhaps you can use TimeGrouper.</p> <pre><code>df.groupby(pd.TimeGrouper('3w', how=np.mean)).describe().unstack() x count mean std min 25% 50% 75% max 2013-06-02 2 1...
python|pandas|matplotlib|seaborn
2
351,328
35,777,774
What happens to events written after a checkpoint?
<p>I have a bunch of summary nodes (scalars, histograms, etc) that are constantly writing to the log. Checkpointing is not as frequent, and so I often have situations in which I'm recovering from a checkpoint that is earlier than the events that have been written to the log. When I resume from the checkpoint and start ...
<p>TensorBoard does have logic to handle this case - it looks for restart events, and tries to purge everything with a global_step greater than the restart step. <a href="https://github.com/tensorflow/tensorflow/blob/r0.7/tensorflow/python/summary/event_accumulator.py#L310" rel="nofollow">See this code</a>. If you are ...
tensorflow|tensorboard
1
351,329
35,751,306
python how to pad numpy array with zeros
<p>I want to know how I can pad a 2D numpy array with zeros using python 2.6.6 with numpy version 1.5.0. But these are my limitations. Therefore I cannot use <code>np.pad</code>. For example, I want to pad <code>a</code> with zeros such that its shape matches <code>b</code>. The reason why I want to do this is so I can...
<p>NumPy 1.7.0 (when <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html" rel="noreferrer"><code>numpy.pad</code></a> was added) is pretty old now (it was released in 2013) so even though the question asked for a way <em>without using</em> that function I thought it could be useful to know how ...
python|arrays|numpy|pad
253
351,330
35,374,958
Reshape tensor using placeholder value
<p>I want to reshape a tensor using the [int, -1] notation (to flatten an image, for example). But I don't know the first dimension ahead of time. One use case is train on a large batch, then evaluate on a smaller batch.</p> <p>Why does this give the following error: <code>got list containing Tensors of type '_Message...
<p>To make this work, replace the function:</p> <pre><code>def reshape(_batch_size): return tf.reshape(x, [_batch_size, -1]) </code></pre> <p>…with the function:</p> <pre><code>def reshape(_batch_size): return tf.reshape(x, tf.pack([_batch_size, -1])) </code></pre> <p>The reason for the error is that <a hre...
tensorflow
11
351,331
35,694,883
KMeans in Python: ValueError: setting an array element with a sequence
<p>I am trying to perform kmeans clustering in Python using <strong>numpy</strong> and <strong>sklearn</strong>. I have a txt file with 45 columns and 645 rows. The first row is Y and remaining 644 rows are X. </p> <p>My Python code is:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import csv fro...
<p>Your data matrix should not be of type <code>object</code>. It should be a matrix of numbers of shape <code>n_samples x n_features</code>.</p> <p>This error usually crops up when people try to convert a list of samples into a data matrix, and each sample is an array or a list, and at least one of the samples does n...
python|numpy|scikit-learn|k-means
1
351,332
35,738,174
Python numpy, skip columns & read csv file
<p>I've got a CSV file with 20 columns &amp; about 60000 rows. </p> <p>I'd like to read fields 2 to 20 only. I've tried the below code but the browser(using ipython) freezes &amp; it just goes n for ages</p> <pre><code>import numpy as np from numpy import genfromtxt myFile = 'sampleData.csv' myData = genfromtxt(myF...
<pre><code>import pandas as pd myFile = 'sampleData.csv' df = pd.DataFrame(pd.read_csv(myFile,skiprows=1)) // Skipping header print df </code></pre> <p>This works like a charm</p>
python|numpy
2
351,333
35,411,925
How to shift dates in a pandas dataframe (add x months)?
<p>I have a dataframe with columns of dates.</p> <p>I know how to shift dates by a fixed number of months (eg add 3 months to all the dates in column x); however, I cannot figure out how to shift dates by a number of months which is not fixed, but is another column of the dataframe.</p> <p>Any ideas?</p> <p>I have c...
<p>IIUC you could use <code>apply</code> with <code>axis=1</code>:</p> <pre><code>In [23]: df.apply(lambda x: x['mydate'] + pd.DateOffset(months = x['month shift']), axis=1) Out[23]: 0 2000-03-01 1 2001-04-01 2 2002-05-01 3 2003-06-01 4 2004-07-01 5 2005-08-01 6 2006-09-01 7 2007-10-01 8 2008-11-01 9...
python|date|pandas
5
351,334
35,716,635
Error Tokenizing Data
<p>I have a csv file from a collaborator. He told me I could read it into into python using</p> <pre><code>import csv t = [] f = open("measles.csv", "rb") d = csv.reader(f, quotechar='"', delimiter="\t", lineterminator='\r\n') for row in d: t.append(row) </code></pre> <p>I tried to make a dataframe out of t...
<p>With pd.read_csv try <code>engine='python'</code> parameter.</p> <p>ex.</p> <pre><code>df = pd.read_csv(file_name , engine='python') </code></pre>
python|csv|pandas
0
351,335
11,824,341
Pandas: date_range error
<p>I'm getting an error using pandas <code>date_range</code> function. I've given the trace below, and can provide more context, but it seems like something I'm really going to have to dig into myself to solve. </p> <p>So what I'd like to know is if there's a way to get at the source for the files mentioned in the tra...
<p>To find datetime.pyx, I'd suggest starting with:</p> <pre><code>find /usr/local/lib/python2.7 -name 'datetime.pyx' </code></pre> <p>To find the definition of the Timestamp class, I'd start with:</p> <pre><code>grep -r 'class Timestamp' /usr/local/lib/python2.7/dist-packages/pandas-0&lt;tab&gt; </code></pre>
python|date|pandas
1
351,336
11,993,790
Inverted order of numpy array gradient and matplotlib quiver
<p>I'm using numpy 1.6 and matplotlib 1.1.1, trying to generate a velocity field from a scalar field that I have. So far, I'm generating my scalar data as such:</p> <pre><code> num_samples = 50 dim_x = np.linspace(self.min_x, self.max_x,num_samples) dim_y = np.linspace(self.min_y, self.max_y,num_samples) ...
<p>I think you're right, (this is an array ordering issue). <code>a</code> is built as <code>a[yidx,xidx]</code> but when you take the gradient, you do: <code>velx, vely = np.gradient(a)</code> when you should be doing <code>vely, velx = np.gradient(a)</code>. Since the gradient along the 0th axis should give you <c...
python|numpy|matplotlib
3
351,337
11,622,692
Is there a better way to broadcast arrays?
<p>I want to broadcast an array <code>b</code> to the shape it would take if it were in an arithmetic operation with another array <code>a</code>.</p> <p>For example, if <code>a.shape = (3,3)</code> and <code>b</code> was a scalar, I want to get an array whose shape is <code>(3,3)</code> and is filled with the scalar....
<p>If you just want to fill an array with a scalar, <code>fill</code> is probably the best choice. But it sounds like you want something more generalized. Rather than using <code>broadcast</code> you can use <code>broadcast_arrays</code> to get the result that (I think) you want. </p> <pre><code>&gt;&gt;&gt; a = numpy...
python|numpy|array-broadcasting
7
351,338
28,455,982
Why are there two np.int64s in numpy.core.numeric._typelessdata (Why is numpy.int64 not numpy.int64?)
<p>This isn't as much of a problem as a curiosity. </p> <p>In my interpreter on 64 bit linux I can execute</p> <pre><code>In [10]: np.int64 == np.int64 Out[10]: True In [11]: np.int64 is np.int64 Out[11]: True </code></pre> <p>Great, just what I would expect. However I found this weird property of the numpy.core.nu...
<p><a href="https://github.com/numpy/numpy/blob/4ed1587a7de85b4fa01dff8ef6e0e901a25f149c/numpy/core/numeric.py#L1655-L1660" rel="nofollow">Here</a> are the lines where <code>_typelessdata</code> is constructed within <code>numeric.py</code>:</p> <pre><code>_typelessdata = [int_, float_, complex_] if issubclass(intc, i...
python|numpy
4
351,339
28,856,507
How to group numpy array position values?
<p>There is a np.array:</p> <pre><code>[ array(['x_0', '2/20/1990', '3/20/1990'], dtype=object), array(['x_1', '1', '2'], dtype=object), array(['x_3', 'foo', 'bar'], dtype=object), etc...] </code></pre> <p>I want to make an array that will contain all of this values grouped (all first values with 1-st values, seco...
<p>You can use python built-in <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code></a> function and <code>join</code> :</p> <pre><code>&gt;&gt;&gt; a=[ ... np.array(['x_0', '2/20/1990', '3/20/1990'], dtype=object), ... np.array(['x_1', '1', '2'], dtype=object), ... np.array...
python|arrays|numpy
2
351,340
28,845,067
remove a specific month-day (leapyear day, to be exact. ie: 02-29) from time series
<p>I would like to use awk (though open to python/pandas solutions) to pull everything but a specific day form a timeseries dataset. The specific day happens only sometimes throughout the file, as it is a leapyear day that is only present if there were records being taken during a leapyear. </p> <p>Dataset looks like ...
<pre><code>awk '!/02-29/' your_file.txt | tee new_file.txt </code></pre> <p>How about <code>grep</code>:</p> <pre><code>grep -Ev '02-29' your_file.txt &gt; new_file.txt </code></pre>
python|shell|datetime|pandas|awk
1
351,341
28,862,334
k-means with selected initial centers
<p>I am trying to k-means clustering with selected initial centroids. It says <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html" rel="noreferrer">here</a> that to specify your initial centers:</p> <pre><code>init : {‘k-means++’, ‘random’ or an ndarray} </code></pre> <p>If an <co...
<p>The default behavior of <code>KMeans</code> is to initialize the algorithm multiple times using different random centroids (i.e. the <a href="http://en.wikipedia.org/wiki/K-means_clustering#Initialization_methods" rel="noreferrer">Forgy method</a>). The number of random initializations is then controlled by the <cod...
python|numpy|scikit-learn|k-means
21
351,342
28,488,885
for loop to produce multiple polyfit scatter plots
<p>I have a dataframe with 20 columns. I am looking to create scatter plots each with a line of best fit. The x column will be constant and I want to use a for loop to run through each of the other columns in the dataframe. The result would be 19 scatter plots. </p> <p>my current setup looks something like this:</p> ...
<p>You have to create each of the subplots explicitly. In this toy code, I use a 4x5 grid which leads to an empty last plot.</p> <p>The subplots are created with <code>plt.subplots(nrows, ncols, ...)</code>. My choice for 4x5 was arbitrary. You can easily adapt the grid by changing the number of rows and columns.</p> ...
python|numpy|matplotlib|plot
2
351,343
28,570,222
Python: numpy where command with if statement
<p>I have a dataframe <code>df</code> that contains a column of dates in a string format like <code>'2011-12-13'</code> and a column of time, again in a string format, like <code>'15:40:00'</code>.</p> <p>df</p> <pre><code>index date time 2011-01-03 09:40:00 2011-01-03 09:40:00 2011-01-03 0...
<p>You don't need to use <code>where</code>. Just use <code>isin</code> and apply your condition directly to the columns:</p> <pre><code>df['F1'] = df.date.isin(dates) &amp; (df.time=='09:40:00') </code></pre>
python|numpy|pandas
4
351,344
28,444,382
Python: Pandas Create new csv with contents counted
<p>I'm reading in a csv and I'm trying to count how many times each entry appears The csv looks like this:</p> <pre><code> Image# color1 color2 color3 1 red blue yellow 2 blue blue red 3 white red pink </code></pre> <p>What I'm...
<p>Use Stack.</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html</a></p> <p><a href="https://stackoverflow.com/questions/17691447/get-count-of-values-across-colum...
python|csv|pandas
2
351,345
28,586,238
Does numpy recfunctions append_fields fail when when array names are unicode?
<p>I am trying to append an array to a numpy recarray using the numpy.lib.recfunctions append_fields function. </p> <p>I receive a "TypeError: data type not understood" error if the recarray field names are unicode. </p> <p>Is this behaviour as-designed, and if so, is there a work-around?</p> <p>Using python 2.7 ...
<p>Your code, with the <code>unicode</code> names runs fine under <code>Python3</code>, where unicode is the default string type.</p> <hr> <p>Edit: Initially I thought the problem lay with masked arrays. But with further testing, I've concluded that <strong>the real issue is whether <code>dtype</code> can accept uni...
python|numpy|unicode
2
351,346
28,849,614
Common item selection - Pandas Dataframe
<p>OK, I know this should be easy but the solution is escaping me. I am doing some social network analysis in python and have a pandas Dataframe (connections) that contain data like this...</p> <pre><code>uid | name | fuID | friendName | 1 | Bob | f1 | Jimmy | 1 | Bob | f2 | ...
<p>Well, you were nearly there -- </p> <pre><code>fdfg = connections.groupby('friendName') for k, v in fdfg: if len(v) &gt; 1: print k print v.name </code></pre> <blockquote> <pre><code>Artie 5 Mark 7 Steve Name: name, dtype: object Jimmy 0 Bob 4 Mark 6 Steve Name: name, dtype: ...
python|pandas
1
351,347
28,579,535
Pandas Dataframe
<p>I want to represent data using pandas dataframe , the column name - Product Title and populate t .</p> <p>For eg :</p> <p><strong>Product Title</strong></p> <p>Marvel : Movies Collection</p> <p>Marvel </p> <p>Diney Movie and so on.. </p> <hr> <pre><code>import requests from bs4 import BeautifulSoup import cs...
<p>Well this will get you started, this extracts all the titles into a dict (I use a defaultdict for convenience):</p> <pre><code>In [163]: from collections import defaultdict data=defaultdict(list) for product_title in g_data: a_product_title = product_title.find_all("a","js-product-title") for text_title in...
python|pandas|beautifulsoup|dataframe
4
351,348
28,610,011
how to effectively loop over matrix elements?
<p>I have to loop over a 800 000* 800 000 matrix. I tried to do that by simple loops but it take me so huge time. How can I loop fastly ?</p> <pre><code>for in in xrange(800000): for j in xrange(800000): print i,j </code></pre> <p>Typically, I am reading an image using OpenCV, then I need to loop over every ...
<p>For performant array looping, you can use <a href="http://cython.org/" rel="nofollow">Cython</a>. You can use most of the syntax of Python, with a lot of the performance gains of using C. It is also compatible with <a href="http://docs.cython.org/src/tutorial/numpy.html" rel="nofollow">NumPy</a>.</p> <p><a href="ht...
python|arrays|loops|numpy|matrix
1
351,349
50,975,430
Numpy vectorize python for loop
<p>This is a code snippet using Keras library for creating models:</p> <pre><code> for state, action, reward, next_state, done in minibatch: target = reward if not done: target = (reward + self.gamma * np.amax(self.model.predict(next_state)[0])) target_f = s...
<p>You are very close! Assuming that <code>minibatch</code> is an <code>np.array</code>:</p> <p>First find all the indices where <code>done</code> is true. Assuming <code>done</code> is index number 4.</p> <pre><code>minibatch_done=minibatch[np.where(minibatch[:,4]==True)] minibatch_not_done=minibatch[np.where(miniba...
numpy|vectorization
3
351,350
50,735,705
tensorflow lite(tflite) invoke error after resize the input dimension
<p>I am using mobilenet_ssd.tflite as the mode from the official tensorflow github. Code below:</p> <pre><code>int input = interpreter-&gt;inputs()[0]; interpreter-&gt;ResizeInputTensor(input, sizes); </code></pre> <p>This will cause error when calling :</p> <pre><code>interpreter-&gt;AllocateTensors() </code></pre>...
<p><code>ResizeInputTensor</code> is restricted by the neural network architecture. It fails since MobileNet &amp; MobileNet SSD can only handle fixed size input.</p> <p>The thing that may work is changing the batch size. For example, you can try to change the size from (1, 244, 244, 3) to (4, 244, 244, 3) and run inf...
tensorflow|tensorflow-lite
1
351,351
50,701,690
PyTorch Tutorial Error Training a Classifier
<p>I just started the PyTorch-Tutorial <em>Deep Learning with PyTorch: A 60 Minute Blitz</em> and I should add, that I haven't programmed any python (but other languages like Java) before.</p> <p>Right now, my Code looks like</p> <pre><code>import torch import torchvision import torchvision.transforms as transforms i...
<p>Because of different implementation of <code>multiprocessing</code> in Windows, you need to wrap your main code with this block:</p> <pre><code>if __name__ == '__main__': </code></pre> <p>For more info, you can check <a href="https://pytorch.org/docs/stable/notes/windows.html" rel="nofollow noreferrer">the officia...
python-3.6|pytorch
1
351,352
50,705,637
No Residuals With Numpy's Least Squares
<p>I am trying to compute a <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html" rel="noreferrer">least squares</a> problem in Numpy (i.e. Ordinary Least Squares (OLS) with Simple Regression) in order to find the corresponding R² value. However, <strong>in some cases</strong>, Numpy is...
<p>From documentation of <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.linalg.lstsq.html" rel="nofollow noreferrer"><code>numpy.linalg.lstsq()</code></a>:</p> <blockquote> <p><strong>residuals : {(), (1,), (K,)} ndarray</strong></p> <p>... If the rank of a is <code>&lt; N</code> or <code>M ...
python|numpy|statsmodels|least-squares|empty-list
4
351,353
50,723,316
Smooth values from skimage.measure.marching_cubes
<p>I'm using <code>skimage.measure.marching_cubes</code> to extract a surface, defined as <code>faces</code> and <code>vertices</code>. <code>marching_cubes</code> also outputs <code>values</code> for each face.</p> <p>How do I "smooth" these <code>values</code> (the actual smoothing could be a low-pass filter, median...
<p>I eventually found a way to do this, based on MATLAB code from this paper:</p> <p>Welf et al. "Quantitative Multiscale Cell Imaging in Controlled 3D Microenvironments" in Developmental Cell, 2016, Vol 36, Issue 4, p462-475</p> <pre><code>def median_filter_surface(faces, verts, measure, radius, p_norm=2): from...
python|numpy|graph-theory|scikit-image|surface
0
351,354
50,912,184
Replacing values in a dataframe for given indices
<p>I want to add values to a dataframe from a few lists. The lists are:</p> <pre><code>car_list milage_lists avg_speeds </code></pre> <p>and a list of indices, <code>idx</code> (not sorted). I want to replace the value of all elements at indices <code>idx</code> with the values from the three lists. What I tried was...
<p>This should do the trick (allows you to specify the column headers):</p> <pre><code>import pandas as pd df = pd.DataFrame([[1, 2, 4, 7], [1, 3, 3, 6], [4, 3, 6, 6], [1, 2, 4, 7], [1, 3, 3, 6], [4, 3, 6, 6]], columns=['A', 'B', 'C', 'D']) indices = [1, 3] car_values = [344, 626] gas_values = [12321 , 124124] for ...
python|python-3.x|pandas|dataframe
1
351,355
50,903,350
Is it possible to train two separated networks based on the loss of one of them? (Tensorflow custom optimization)
<p>Due to memory limitation, I had to separate the two networks (CNN and BLSTM) in the feedforward prop and do the back prop on both networks at the same time. However, it seems that only the BLSTM weights get updated and CNN weights stay the same! </p> <p>My implementation is quite long to post it here, but I have m...
<p>The output of the first network (<code>pred1</code>) doesn't appear anywhere in the cost calculations. Thus the gradients for the variables involved in calculating it are 0, since changing them wouldn't change the cost at all. Your first network serves absolutely no purpose in this setup.</p> <p>If you want <code>n...
python|tensorflow|optimization|loss
0
351,356
50,863,504
Splitting String numerical values into new columns-Pandas Dataframe
<p>I have a dataframe column having values like this:</p> <pre><code>Salary Offered ---------------------- £18,323 per annum £18,000 - £22,000 per annum Salary not specified £15,000 - £17,000 per annum, pro-rata £37,000 - £45,000 per annum £9,100 - £9,152 per annum, OTE £9.25 - £10.15 per hour £35,000 - £40,000...
<p>If I understand correctly, you can extract what you need (numbers) with a regex, and do your calculations on the result:</p> <pre><code>salaries = (df['Salary Offered'] .str.replace(',','') .str.findall(r'(\d+\.?\d+)') .apply(lambda x: pd.Series(x).astype(float)) .mea...
python|pandas|dataframe|data-presentation
4
351,357
50,858,680
group pandas DataFrame by one column and then get lists of values which occur in those categories from other column
<p>I am looking for a possibility to group a DataFrame by one (or more) columns and than add another column to the grouped DataFrame which gives me those values that occure in this categorie from another column in the original DataFrame. (It's probably easier understand what I would like to do by the follwing example.)...
<p>IIUC:</p> <pre><code>In [90]: df.groupby('color').agg({'cars':'size','city':'unique'}).reset_index() Out[90]: color cars city 0 blue 3 [X, Z] 1 red 2 [Y, Z] </code></pre> <p>@Dillon,</p> <p>if you want to see all available aggregate methods (functions) and attributes, then try to use <code>ipyt...
python-3.x|pandas
3
351,358
50,729,229
Display 480x115x115 3-D Numpy model in browser?
<p>What is the cheapest way to display a 480x115x115 3-D model on my personal website? I've heard of Maya, Blender, Unity, and Unreal Engine, but don't know which to use.</p> <h3>Picture of the model of Benji's torso:</h3> <p><img src="https://imgur.com/gallery/i4wMLZd" alt="Benji's torso" /></p> <h3>My specs:</h3> <p...
<blockquote> <p>What is the cheapest way to display a 480x115x115 3-D model on my personal website? I've heard of Maya, Blender, Unity, and Unreal Engine, but don't know which to use.</p> </blockquote> <p>Maya and Blender are both modeling tools only. They are not made for displaying models on web browsers. They...
javascript|python|numpy|blender|unreal-engine4
0
351,359
51,083,030
paste dataframe on dataframe in python dictionary
<p>I want to create a dictionary in which the key is a city name and the value is a list of pandas dataframes which are formed from ID's of instances that are in that city. Currently I have the following code:</p> <pre><code>city_idframes_dictionary = dict() if city in city_idframes_dictionary: city_idframes_dictio...
<p>In </p> <pre><code>city_idframes_dictionary[city] = pd.DataFrame(df) </code></pre> <p>you are not defining as value a list (as you stated you wanted) but rather a dataframe. Use:</p> <pre><code>city_idframes_dictionary[city] = [pd.DataFrame(df)] </code></pre> <p>instead.</p>
python|pandas|dictionary|dataframe|append
0
351,360
50,981,714
Multi-label, multi-class image classifier (ConvNet) with PyTorch
<p>I am trying to implement an image classifier (CNN/ConvNet) with PyTorch where I want to read my labels from a csv-file. I have 4 different classes and an image may belong to more than one class.</p> <p>I have read through the <a href="https://pytorch.org/tutorials/beginner/data_loading_tutorial.html" rel="nofollow ...
<p>Maybe I am missing something, but if you want to convert your columns <code>1..N</code> (<code>N = 4</code> here) into a label vector or shape <code>(N,)</code> (e.g. given your example data, <code>label(img1) = [0, 0, 0, 1]</code>, <code>label(img3) = [1, 0, 1, 0]</code>, ...), why not:</p> <ol> <li><p>Read all th...
python|classification|pytorch|convolutional-neural-network|multilabel-classification
2
351,361
50,987,650
Parsing of nested structured json in Pandas
<p>I'm receiving request from the API and try to process it in Python using <code>requests</code> library and <code>json_normalize()</code> function. Here are my steps:</p> <pre><code>import requests from pandas.io.json import json_normalize url = "Some String" headers = { 'Authorization':"Some Token"} response =...
<p>Just create a dataframe from your col2 content it will work perfectly.</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; pd.DataFrame([[1528322400000, 24], [1528322460000, 24]], columns=['c1','c2']) c1 c2 0 1528322400000 24 1 1528322460000 24 </code></pre> <p>Is this what you want?<...
python|json|list|pandas|python-requests
1
351,362
50,740,148
Pandas Dataframe too large for memory, problems implementing dask
<p>I am writing a script which adds my simulated data to a pandas dataframe for n simulations in my loop. When I choose a value of n >~15 it crashes, I think my df becomes becomes too big to store in memory whilst running my simulations. </p> <p>I create an empty DF</p> <pre><code>df = pd.DataFrame( {'gamma': [],...
<p>As the error message suggests, Dask does not generally allow you to alter the contents of a dataframe in-place. Furthermore, it is really unusual to try to append or otherwise change the size of a dask dataframe once created. Since you are running out of memory, Dask is still your tool of choice, so here is somethin...
python|pandas|dataframe|dask
2
351,363
50,825,248
Keras.backend.reshape: TypeError: Failed to convert object of type <class 'list'> to Tensor. Consider casting elements to a supported type
<p>I'm designing a custom layer for my neural network, but I get an error from my code.</p> <p>I want to do a attention layer as described in the paper: <a href="https://arxiv.org/abs/1805.08318" rel="nofollow noreferrer">SAGAN</a>. And the <a href="https://github.com/taki0112/Self-Attention-GAN-Tensorflow" rel="nofol...
<p>You are accessing the tensor's <code>.shape</code> property which gives you Dimension objects and not actually the shape values. You have 2 options:</p> <ol> <li>If you know the shape and it's fixed at layer creation time you can use <code>K.int_shape(x)[0]</code> which will give the value as an integer. It will ho...
python|tensorflow|keras|generative-adversarial-network
9
351,364
50,983,398
Pandas: join on partial string match, like Excel VLOOKUP
<p>I am trying to perform an action in Python which is very similar to VLOOKUP in Excel. There have been many questions related to this on StackOverflow but they are all slightly different from this use case. Hopefully anyone can guide me in the right direction. I have the following two pandas dataframes:</p> <pre><co...
<p>This is one way using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow noreferrer"><code>pd.Series.apply</code></a>, which is just a thinly veiled loop. A "partial string merge" is what you are looking for, I'm not sure it exists in a vectorised form.</p> <pre>...
python|python-3.x|pandas|dataframe|join
2
351,365
50,993,271
Jupyter Notebook Kernel dies when importing Tensorflow
<p>I am trying to use Tensorflow-gpu on a jupyter notebook inside a docker containing running on my Ubuntu 18.04 Bionic Beaver server.</p> <p>I have done the following steps:<br> 1) Installed Nvidia Drivers 390.67 <code>sudo apt-get install nvidia-driver-390</code><br> 2) Installed CUDA Drivers 9.0 <code>cuda_9.0.176_...
<p>It turns out i needed to downgrade to tensorflow 1.5.0. 1.5.1 is where AVX was added. AVX instructions are apparently used on module load to set up the library.</p>
python|docker|tensorflow|jupyter-notebook
1
351,366
50,994,825
Can I train an object detector using both thermal and RGB imagery in tensorflow?
<p>I have a camera that can take thermal and RGB imagery and for detecting certain animals I want a classifier that will look at both the RGB and thermal imagery. Is it possible to use multiple image layers/channels for a tensorflow classifier?</p>
<p>It is possible to create a classifier with multiple layers, but the major issue here will be that your classifier will have to learn to detect animals for both thermal and RGB images and that is a tough ask for any classifier since RGB and thermal images are represented in very different ways. </p> <p>Your problem ...
tensorflow|neural-network|computer-vision
0
351,367
50,873,572
Retain order of values in binary matrix in Python
<p>I created a binary matrix from 2 pandas columns</p> <p>df:</p> <pre><code>ID_2 ID_1 1111 1 22222 2 33333 3 33333 4 44444 5 55555 6 55555 7 66666 8 66666 9 77777 10 77777 11 77777 12 </code></pre> <p>Using:</p> <pre><code>A = pd.get_dummies(df.set_index('ID_1')['ID_2'].astype(str)).max(level=0) print (A) </code...
<p>If you want to reorder the columns, I think you need this:</p> <pre><code>A = A.reindex_axis(['11111'] + list(A.columns[:-1]), axis=1) </code></pre> <h1>Edit</h1> <p>You can do in this way:</p> <pre><code> from collections import OrderedDict cols = list(OrderedDict.fromkeys(list(df['ID_2'].values))) cols = [st...
python|pandas|matrix
1
351,368
50,769,141
Order one numpy array by another
<p>I have an array that determines an ordering of elements:</p> <pre><code>order = [3, 1, 4, 2] </code></pre> <p>And then I want to sort another, larger array (containing only those elements):</p> <pre><code>a = np.array([4, 2, 1, 1, 4, 3, 1, 3]) </code></pre> <p>such that the element(s) that come first in <cod...
<h3>Specific case : <code>Ints</code></h3> <p>For <code>ints</code>, we could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow noreferrer"><code>bincount</code></a> -</p> <pre><code>np.repeat(order,np.bincount(a)[order]) </code></pre> <p>Sample run -</p> <pre><cod...
python|arrays|sorting|numpy
5
351,369
50,878,717
How can I compare time frequencies in Pandas?
<p>I have a fixed timeseries frequency, <code>'MS'</code>, against which I wish to compare data frequency in a Pandas DataFrame.</p> <p>So, for example, I am given a DataFrame with a <code>date</code> column, and I can infer its time frequency using <code>pd.infer_freq(df['date'])</code>, which returns, for example <c...
<p>You could create a dictionary that maps all of the possible time frequencies to a number, where smaller numbers indicate it's a higher frequency. This allows you to map the same frequency, with a different description to the same number. Then just create a function to compare</p> <pre><code>dct = {'N': 0, 'U': 1, '...
python|pandas|dataframe
2
351,370
50,819,058
Numpy - Find 3-d distance to a testpoint for all gridpoints on 3-d grid
<p>I tried np.hypot() and np.linalg.norm() but both of them have some issues (at least how I am using thm).</p> <p><strong>I am pretty sure np.hypot can only calculate 2-d distance</strong>. If I have a test point P (1,1,1) and a grid point G (3,3,3), then the returned value a grid point G will be something like : ((3...
<p>How about simply:</p> <pre><code>d = np.sqrt((point[0]-xx)**2 + (point[1]-yy)**2 + (point[2]-zz)**2) </code></pre>
numpy|numpy-einsum
1
351,371
51,019,813
First row of data has become a column in Pandas table
<p>The first row in pandas data table has turned into a column. I've tried various renaming methods and restructuring and it hasn't been working. Something really trivial, but unfortunately I need some help.</p> <p><a href="https://i.stack.imgur.com/64Qfb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur....
<p>I think there is problem your csv have no header, so is possible create default range columns names:</p> <pre><code>df_degree = pd.read_csv(file, header=None) </code></pre> <p>Or is possible define custom columns names:</p> <pre><code>df_degree = pd.read_csv(file, names=['col1','col2']) </code></pre>
python|pandas|jupyter
9
351,372
50,933,543
need to drop the rows in data frame based on the values which has in a separate list
<p>For Example im having a data frame</p> <pre><code>col1 col2 col3 a 12 34 b 23 67 c 67 86 </code></pre> <p>im having list</p> <pre><code>list=['b','f','r'] </code></pre> <p>i need to remove the rows in the data frame which was there in the list</p>
<p>You need <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow noreferrer"><code>series.isin</code></a>:</p> <pre><code>df[~df["col1"].isin(lst)] </code></pre> <p>P.S. Please, avoid calling variables with python reserved words like <code>list</code>. </p>
python-3.x|pandas|dataframe|merge
1
351,373
51,106,747
Getting the non-trivial solution to a set of linear equations
<p>I'm trying to write a program that will allow me to solve a system of equations using numpy, however, I want the solution to be non-trivial (not all zeros). Obviously the program is just going to set everything to 0, and boom, problem solved. I attempted to use a while loop (like below), but quickly found out it's g...
<p>In your case, the matrix a is invertible. Therefore your system of linear equations has only one solution and the solution is [0, 0]. Are you wondering why you only get that unique solution?</p>
python|numpy
1
351,374
51,100,994
Trouble installing pandas package on Python via PiP
<p>I want to install the pandas package on my Python. I am using pip to do it so I executed</p> <pre><code>python -m pip install --upgrade pandas </code></pre> <p>I get an error:</p> <pre><code> Could not find a version that satisfies the requirement numpy==1.9.3 (from versions: 1.10.4, 1.11.0, 1.11.1rc1, 1.11.1, 1....
<p>Have you tried uninstalling Numpy and installing it again? </p>
python|pandas|installation|pip
0
351,375
50,937,875
Plot in python after crosstab merge
<p>I'd like to plot my <code>DataFrame</code>. I had this DF first:</p> <pre> id|project|categories|rating 1 | a | A | 1 1 | a | B | 1 1 | a | C | 2 1 | b | A | 1 1 | b | B | 1 2 | c | A | 1 2 | c | B | 2 </pre> <p>used this code:</p> <pre...
<p>I reproduced your data using below code:</p> <pre><code>import pandas as pd df = pd.DataFrame({'id': [1, 1, 1, 1, 1, 2, 2,],\ 'project': ['a', 'a', 'a', 'b', 'b', 'c', 'c'],\ 'categories': ['A', 'B', 'C', 'A', 'B', 'A', 'B'],\ 'rating': [1, 1, 2, 1, 1, 1, 2]}) ...
python|pandas|dataframe|seaborn|crosstab
0
351,376
50,897,418
Pandas Dataframe SettingWithCopyWarning copy-method
<p>I have this program for demonstration:</p> <pre><code>import pandas as pd d = {'foo':[100, 111, 222], 'bar':[333, 444, 555]} df = pd.DataFrame(d) list = [333,444] dferg = df.loc[df.bar.isin(list)] dferg['test'] = 123 </code></pre> <p>I get the warning:</p> <pre><code>SettingWithCopyWarning: A value is ...
<p><code>dferg = df.loc[df.bar.isin(list)]</code> is a get operation which can return either a view or a copy. Calling <code>.copy()</code> is explicitly telling it's actually a copy, thus no warning is raised. <code>dferg['test'] = 123</code> modifies the original <code>df</code> too, so pandas warns you in case you ...
python|pandas
2
351,377
50,752,605
In pandas is there a way to compute a subsection of a expanding window; without calculating the entire array and "tail-ing" the result
<p>I want to compute the expanding window of just the last few elements in a group...</p> <pre><code>df = pd.DataFrame({'B': [np.nan, np.nan, 1, 1, 2, 2, 1,1], 'A': [1, 2, 1, 2, 1, 2,1,2]}) df.groupby("A")["B"].expanding().quantile(0.5) </code></pre> <p>this gives:</p> <pre><code> 1 0 NaN 2 1.0 ...
<p>Maybe try using tail: <a href="https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.core.groupby.GroupBy.tail.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.core.groupby.GroupBy.tail.html</a></p> <pre><code>df.groupby('A')['B'].rolling(4, min_perio...
python|pandas
1
351,378
50,708,767
Converting String to int array
<p>I'm stucked with some problem. I've sent int array from JS to Python via AJAX and it has been converted to JSON (as I used JSON.stringify()), so now it's a string "[1,2,3,4,5]". How can I convert it in Python back to int array [1,2,3,4,5]? I've tried to convert this array to numpy array <code>np.asarray(features_u...
<p><code>json.loads()</code> is what you're looking for. make sure you add the <code>s</code> in load. the <code>s</code> stands for <code>string</code>.</p> <p>So <code>json.load</code> is for a file, <code>json.loads</code> for a string</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; a = "[1,2,3,4,5]" &gt;&gt;...
python|arrays|django|python-3.x|numpy
1
351,379
50,992,000
Pandas assign series to new column to multiindex
<p>So I create a dataframe with MultiIndex</p> <pre><code>df = pd.DataFrame({ 'C1': ['x', 'x', 'y', 'y', 'z', 'z'], 'C2': ['a', 'b', 'a', 'b', 'a', 'b'], 'C3': [10, 11, 12, 13, 14, 15]}) df.set_index(['C1', 'C2'], inplace=True) </code></pre> <p>And I get the following dataframe</p> <pre><code> C3 C...
<p>You can go for <code>pd.IndexSlice</code> i.e </p> <pre><code>df.loc[pd.IndexSlice['x',series.index.tolist()],'C4'] = series.values C3 C4 C1 C2 x a 10 100.0 b 11 NaN y a 12 NaN b 13 NaN z a 14 NaN b 15 NaN </code></pre>
python|pandas|dataframe|indexing|series
6
351,380
50,951,274
Folding pandas time series into single day
<p>I have a time series of events that spans multiple days-I'm mostly interested in counts/10min interval. So currently, after resampling, it looks like this</p> <pre><code>2018-02-27 16:20:00 5 2018-02-27 16:30:00 4 2018-02-27 16:40:00 0 2018-02-27 16:50:00 0 2018-02-27 17:00:00 0 ... 2018-06-19 05:30:...
<p>If your series index is a DatetimeIndex, you can use the attribute <code>time</code> -- if it's a DataFrame and your datetimes are a column, you can use <code>.dt.time</code>. For example:</p> <pre><code>In [19]: times = pd.date_range("2018-02-27 16:20:00", "2018-06-19 05:50:00", freq="10 min") ...: ser = pd.S...
python|python-3.x|pandas|numpy|time-series
0
351,381
51,027,447
Save structured numpy array using np.savetxt with header
<p>I have a structure array in the form of </p> <pre><code>output = np.zeros(names.size, dtype=[('name', 'U32'), ('r', float),('m',float)]) </code></pre> <p>Then I tried to save it into a csv file using np.savetxt. I am wondering if there is way I could also save the label of each column as the header of the csv file...
<p>You could try a solution similar to <a href="https://stackoverflow.com/a/6473724/943773">this SO answer</a> to pivot the data</p> <pre><code>dtypes = [('name', 'U32'), ('r', float),('m',float)] a = np.zeros(5, dtype=dtypes) b = numpy.vstack(map(list, a)) </code></pre> <p>Where you map list over the recarray tuples...
python|numpy|save|structured-array
2
351,382
50,770,626
How to ensure pandas.DataFrame.to_csv is flush immediately
<p>Is there a way to force <code>pandas.DataFrame.to_csv</code> flush the csv that it is writing? </p> <p>In CSV file writing we can do the following (<code>f1.flush</code>)</p> <pre><code>with open("t.csv", 'w', encoding='utf-8') as f1: writer = csv.writer(f1, delimiter=',', quoting=csv.QUOTE_MINIMAL, linetermin...
<p>when passing a file path to <code>pandas.to_csv()</code>, the function will open a file, write to it, and close the file. </p> <pre><code>df.to_csv('my_output_file.csv') # the file will now be fully written and fully flushed </code></pre> <p>thus flushing <strong>definitely</strong> happens as part of the OS handl...
python-3.x|pandas|dataframe
2
351,383
50,706,431
Please how to do this basic thing with tensorflow?
<p>Imagine that I have a tensor like that as input:</p> <pre><code>[[1,1,1,1,1,1,0,0,0,0,0,0,0], [[1,1,1,1,1,1,0,0,0,0,0,0,0], [[1,1,1,1,1,1,0,0,0,0,0,0,0], [[1,1,1,1,1,1,0,0,0,0,0,0,0], [[1,1,1,1,1,1,0,0,0,0,0,0,0], [[1,1,1,1,1,1,0,0,0,0,0,0,0], [[1,1,1,1,1,1,0,0,0,0,0,0,0] [[1,1,1,1,1,1,0,0,0,0,0,0,0]] </code></pre>...
<p>Here is a solution with a zero-fill -- it is straightforward to replace with a random fill.</p> <pre><code>import numpy as np import tensorflow as tf x = np.zeros((8, 13), dtype=np.float32) x[:, :6] = 1 x = tf.constant(x) s0 = tf.shape(x)[0] # add an extra zero column on the right x2 = tf.concat([x, tf.zeros((s0,...
python|tensorflow
0
351,384
50,705,494
How to store by columns in a structured numpy array
<p>I have a list of tuples that look like this:</p> <pre><code>&gt;&gt;&gt; y [(0,1,2,3,4,...,10000), ('a', 'b', 'c', 'd', ...), (3.2, 4.1, 9.2, 12., ...), ] </code></pre> <p>etc. <code>y</code> has 7 tuples, where each tuple has 10,000 values. All 10,000 values of a given tuple are the same dtype, and I have a list ...
<p>Use the <code>zip*</code> idiom to 'transpose' your list of tuples:</p> <pre><code>In [150]: alist = [(0,1,2,3,4),tuple('abcde'),(.1,.2,.4,.6,.8)] In [151]: alist Out[151]: [(0, 1, 2, 3, 4), ('a', 'b', 'c', 'd', 'e'), (0.1, 0.2, 0.4, 0.6, 0.8)] In [152]: dt = np.dtype([('0',int),('1','U3'),('2',float)]) In [153]:...
python|arrays|numpy|structured-array
1
351,385
50,759,044
Analysing data set with pandas
<p>I am a beginner in the data science field. I am trying to do some aggregation on the data but not sure how to code it. I have the following data frame. I need to udnerstand how i can calculate the total no of jobs done by a driver (Driver ID is unique)</p> <p><img src="https://i.stack.imgur.com/eLoiF.png"> <img sr...
<p><code>sum</code> No_of_jobs and <code>groupby</code> driver id should do the job</p> <pre><code>data.groupby('Driver_Id')['No_of_jobs'].sum() </code></pre> <p>another option is <code>pivot_table</code> with <code>aggfunc=['count']</code> :</p> <pre><code>df.pivot_table(values=['No_of_jobs'],index='Driver_Id',aggf...
pandas
0
351,386
50,860,877
Subsetting last business day of the week in python data frame
<p>I have a below sample Data Frame and would like to subset the dataframe which has the last business day of particular week to separate data frame. I have tried many ways but not able to do for weekday. </p> <p>df = </p> <pre><code> Date Open High Low Close Adj Close Volume 0 2007-06-01 0.33...
<p>Could this help you?</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({"Date": ["2007-06-01", "2007-06-02", "2007-06-04", "2007-06-05", "2007-06-06", "...
python|pandas|date|finance
1
351,387
51,098,540
insert to Db2 using Flask and sqlalchemy
<p>I have a Flask application with sqlalchemy in it. Running <code>manage db init</code>, <code>manage db migrate</code> and <code>manage db upgrade</code> worked perfectly. So the tables are created on db2 without any problems. When i try to do an insert, i get all kinds of errors. </p> <hr> <pre><code>Traceback (m...
<p>Got it to work! </p> <p>Had to cast the types in the insert code as:</p> <pre><code>ins = Sensor(sensor_id = int(sensor_coords['sensor_code'][0]), code = int(sensor_coords['sensor'][0]), lat = float(sensor_coords['lat'][0]), ...
python|numpy|sqlalchemy|db2
1
351,388
50,950,793
can anyone explain this phenomenon in neural network?
<p>I have trained an [50, 500, 500, 5] neural network, the input layer have 50 neurons and the output layer have 5 neurons. The biases in layer2 change like this <img src="https://i.stack.imgur.com/F2Ip8.png" alt="layer2/biases"></p> <p>why does the distribution of the bias in layer2 change so dramatic ?</p> <p>(the ...
<p>What you’re seeing is almost certainly overfitting. This isn’t a bug in your implementation, but rather an issue with your understanding. This 1,055 neuron multi-layer perceptron (MLP) has on the order of 6.25M weights (depending on you implementation)! That’s enough capacity to memorize almost any pattern. What you...
python|tensorflow|neural-network
0
351,389
51,069,567
get count and sum grouping dataframe by Pandas
<p>I have a sql table looks like this:</p> <pre><code>+----+------------+--------+------------+ | id | department | amount | date | +----+------------+--------+------------+ | 1 | d1 | 20 | 2018-06-10 | | 2 | d1 | 12 | 2018-06-10 | | 2 | d1 | 10 | 2018-06-11 | | 3 | d2 ...
<p>For each unique department, summing 'amount' over day and plotting it on the same plot.</p> <p>Firstly, <code>date</code> needs to be of <code>datetime</code> type before any Grouping based on it.</p> <pre><code>df['date'] = pd.to_datetime(df['date']) </code></pre> <p>and then plotting the time-series as below:</...
python|sql|pandas|numpy|matplotlib
2
351,390
20,539,915
Colorcode the indents level / visual indication in Spyder
<p>I am using Spyder for some Numpy work currently and python's indentation mechaninc is confusing me a little. It would be really helpful if I could have some color coding for each indentation level or some dotted lines (like in notepad++). Is there a way to turn such a feature on, or any plugins I can use?</p>
<p>(<em>Spyder developer here</em>) This functionality is available since Spyder <strong>2.3.3</strong> and you can activate it under the menu entry</p> <pre><code>Source &gt; Show blank spaces </code></pre>
python|numpy|spyder
2
351,391
20,887,190
SciPy UnivariateSpline Specifying Axis?
<p>Using <code>scipy.interpolate.interp1d</code> it is possible to pass in a (1080, 4) nd.array and compute an interpolation function for each 'row' in a single command:</p> <pre><code>spline = interp1d(np.arange(1,5), np.random.random(1080,4), kind='cubic') </code></pre> <p>I am getting slightly different interpolat...
<p>In older version of SciPy (I observed it in 0.14) the splines returned by interp1d were of relatively poor quality. In versions 0.19 and later, <code>interp1d</code> is consistent with other spline routines, and since it accepts vector inputs, I think that answers the question. Here is the comparison of three splin...
numpy|scipy|interpolation|spline
0
351,392
20,865,487
Pandas plot() without a legend
<p>Using the pandas library in python and using </p> <pre><code>.plot() </code></pre> <p>on a dataframe, how do I display the plot without a legend?</p>
<p>There is a parameter in the function corresponding to legend; by default it is True</p> <pre><code>df.plot(legend=False) </code></pre> <p>Following is the definition of the <code>.plot()</code> method</p> <blockquote> <p>Definition: df.plot(frame=None, x=None, y=None, subplots=False, sharex=True, sharey=False, ...
python|pandas|plot
176
351,393
20,754,746
Using boolean indexing for row and column MultiIndex in Pandas
<p>Questions are at the end, in <strong>bold</strong>. But first, let's set up some data:</p> <pre><code>import numpy as np import pandas as pd from itertools import product np.random.seed(1) team_names = ['Yankees', 'Mets', 'Dodgers'] jersey_numbers = [35, 71, 84] game_numbers = [1, 2] observer_names = ['Bill', 'J...
<p>As of Pandas 0.18 (possibly earlier) you can easily slice multi-indexed DataFrames using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.IndexSlice.html" rel="nofollow noreferrer">pd.IndexSlice</a>. </p> <p>For your specific question, you can use the following to select by team, jersey, and g...
python|pandas|multi-index
2
351,394
20,724,919
Pandas Dataframe AttributeError: 'DataFrame' object has no attribute 'design_info'
<p>I am trying to use the <code>predict()</code> function of the <code>statsmodels.formula.api</code> OLS implementation. When I pass a new data frame to the function to get predicted values for an out-of-sample dataset <code>result.predict(newdf)</code> returns the following error: <code>'DataFrame' object has no attr...
<p>Pickling and unpickling of a pandas DataFrame doesn't save and restore attributes that have been attached by a user, as far as I know.</p> <p>Since the formula information is currently stored together with the DataFrame of the original design matrix, this information is lost after unpickling a Results and Model ins...
python|pandas|scipy|pickle|statsmodels
14
351,395
33,088,679
Calculate Mean for certain sets of numbers in a dataframe (Pandas,Python3)
<p>I have a dataframe as such:</p> <pre><code> Group Importance 1 100% 1 100% 1 50% 2 75% 2 50% </code></pre> <p>I would like to standardize the importance so for each group, the combined importance equals 100% (e.g. each individual cell is divi...
<p>Assuming the values in your dataframe are numeric (e.g. .50 vs '50%'):</p> <pre><code>df['Weight'] = df.groupby('Group')['Importance'].transform(lambda x: x / sum(x)) &gt;&gt;&gt; df Group Importance Weight 0 1 1.00 0.4 1 1 1.00 0.4 2 1 0.50 0.2 3 2 ...
python|pandas
2
351,396
33,123,315
Scipy Python wheel
<p>I have got a problem with installing Scipy on my Python 2.7 , Windows in IPython. When I enter "pip install scipy", I have one first error message: "Failed building wheel for scipy" and then at the end</p> <pre><code>" Command "c:\python27\python.exe -c "import setuptools,tokenize;__file__='c:\\us ers\\admini...
<p>You can download the wheel from this web site:</p> <p><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy" rel="nofollow noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy</a></p> <p>You need to pick the right one. So, for</p> <p>scipy‑0.19.0‑cp34‑cp34m‑win32.whl</p> <p>cp34 means it will work wi...
python|numpy
1
351,397
33,461,135
Pandas dataframe apply refer to previous row to calculate difference
<p>I have the following pandas dataframe containing 2 columns (simplified). The first column contains <em>player names</em> and the second column contains <em>dates</em> (<code>datetime</code> objects):</p> <pre><code> player date A 2010-01-01 A 2010-01-09 A 2010-01-11 A 201...
<p>You can simply write:</p> <pre><code>df['difference'] = df.groupby('player')['date'].diff().fillna(0) </code></pre> <p>This gives the new timedelta column with the correct values:</p> <pre><code> player date difference 0 A 2010-01-01 0 days 1 A 2010-01-09 8 days 2 A 2010-01-11 ...
python|pandas|dataframe|apply
6
351,398
33,350,381
Average of daily count of records per month in a Pandas DataFrame
<p>I have a pandas DataFrame with a <code>TIMESTAMP</code> column, which is of the datetime64 data type. Please keep in mind, initially this column is not set as the index; the index is just regular integers, and the first few rows look like this:</p> <pre><code> TIMESTAMP TYPE 0 2014-07-25 11:...
<p>I think you'll want to do two rounds of <code>groupby</code>, first to group by day and count the instances, and next to group by month and compute the mean of the daily counts. You could do something like this.</p> <p>First I'll generate some fake data that looks like yours:</p> <pre><code>import pandas as pd # ...
python|pandas|timestamp|time-series
10
351,399
33,423,081
converting numpy vector to cvxopt
<p>This may be a very silly question, but I have been struggling with it and couldn't find it readily in the documentation.</p> <p>I am trying to do a quadratic programming using the <a href="http://cvxopt.org/userguide/coneprog.html#quadratic-programming" rel="nofollow">description given here</a>. The <a href="http:/...
<p>You have not included any sample data, but when I encountered this error, it was because of the dtype.</p> <p>try:</p> <pre><code>q = q.astype(np.double) cvx_q = matrix(q) </code></pre> <p>CVX only accepts doubles, not ints.</p>
python|numpy|cvxopt
6