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 |
|---|---|---|---|---|---|---|
11,600 | 59,618,870 | Why are model predictions not updating in tensorflow (python)? | <p>I built a tensorflow graph according to a few different resources online and am trying to fit a curve to <code>y=x^2</code>. I am using two hidden layers with 25 and 10 neurons respectively. The code completes, but the cost function never reduces and the ultimate chart of <code>x_test</code> to <code>preds</code> ... | <p>I was just playing with a model then i remembered this problem
the issue was Y_range is so big in some point, so for tensorflow in order to run some calculation the memory will exceed and the value will be <code>inf</code>
for that you need to normalize the data with <code>mean</code> equal to 0 and <code>std</code... | python|tensorflow|machine-learning | 0 |
11,601 | 40,562,105 | python 3 - count in array | <p>I have input array like this in python 3.
input: [[4 1 -1 4][2 0 5 1 ] [1 6 2 -1][7 3 0 -2]]
output1:[[1] [1] [1] [2]]
output2:3</p>
<p>output1:count number of elements <=0 and display in the output
output2:display the index which has maximum value in output1
How to get this output 1 and output2?
Even if we coul... | <p>This should do what you're after</p>
<pre><code>def output1(lst):
return [ [sum(1 for i in inner if i <= 0)] for inner in lst ]
def output2(lst):
return max(enumerate(lst), key = lambda tup: tup[1])[0]
>>> x = output1([[4, 1, -1, 4],[2, 0, 5, 1],[1, 6, 2, -1],[7, 3, 0, -2]])
>>> x
[[1... | arrays|python-3.x|numpy|count | 0 |
11,602 | 40,641,160 | time delta in pandas dataframe | <p>Have a question regarding how to create a day count type of column in pandas. Given a list of dates, I want to be able to calculate the difference from one date to the previous date in days. Now, I can do this with simple subtraction and it will return me a timedelta object I think. What if I just want an integer nu... | <p>Try this:</p>
<pre><code>In [197]: df['day_count'] = df.INDEX_DATE.diff().dt.days
In [198]: df
Out[198]:
INDEX_DATE day_count
0 2009-10-06 NaN
1 2009-10-07 1.0
2 2009-10-08 1.0
3 2009-10-09 1.0
4 2009-10-12 3.0
5 2009-10-13 1.0
</code></pre> | python|datetime|pandas | 2 |
11,603 | 18,256,220 | Numpy: understanding the numpy array concept for row names | <p>Maybe a very vague question, but digging the links on numpy did not help me.</p>
<p>I need to do a similarity matrix calculation with following hierarchial clustering for binary array that look like this </p>
<pre><code>name val1 val2 val3 val4 val5
comp1 0 0 1 0 1
comp2 1 0 0 0 ... | <p>Numpy doesn't really support row names. It does support column names, through <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html" rel="nofollow">structured arrays</a>. You could use something like <code>dtype=[('name', object), ('val1', int), ...]</code>. That could also be automated by reading the first ... | python|arrays|numpy | 6 |
11,604 | 18,302,358 | Create array of outer products in numpy | <p>I have an array of n vectors of length m. For example, with <em>n = 3</em>, <em>m = 2</em>:</p>
<pre><code>x = array([[1, 2], [3, 4], [5,6]])
</code></pre>
<p>I want to take the outer product of each vector with itself, then concatenate them into an array of square matrices of shape <em>(n, m, m)</em>. So for the ... | <p>Maybe use <code>einsum</code>?</p>
<pre><code>>>> x = np.array([[1, 2], [3, 4], [5,6]])
>>> np.einsum('ij...,i...->ij...',x,x)
array([[[ 1, 2],
[ 2, 4]],
[[ 9, 12],
[12, 16]],
[[25, 30],
[30, 36]]])
</code></pre> | python|numpy|indexing | 4 |
11,605 | 61,829,595 | Pandas datrafame inconsistent data in mulitple rows | <p>I have something like that:</p>
<pre><code>>>> x = {'id': [1,1,2,2,2,3,4,5,5], 'value': ['a', 'a', 'b', 'b', 'c', 'd', 'e', 'f', 'g']}
>>> df = pd.DataFrame(x)
>>> df
id value
0 1 a
1 1 a
2 2 b
3 2 b
4 2 c
5 3 d
6 4 e
7 5 f
8 5 g
<... | <p>In your case we do <code>groupby</code> + <code>transform</code> with <code>nunique</code> </p>
<pre><code>unc_df=df[df.groupby('id').value.transform('nunique').ne(1)]
id value
2 2 b
3 2 b
4 2 c
7 5 f
8 5 g
</code></pre> | python|pandas|dataframe | 1 |
11,606 | 61,907,722 | Python: dynamically binning the columns in pandas | <p>I am trying to bin the following fields using <code>for</code> loop in pandas. </p>
<pre><code>KUNNR Value_1 Value_2 Value_3 Value_4
1001 0 30 15 20
1002 1 10 10 31
1003 0 30 35 40
1004 0 10 0 ... | <p>Does this work for you?</p>
<pre><code>df_cols = df.columns.tolist()
for c in df_cols:
num = df[c].nunique()
df[c] = pd.cut(df[c].astype('int'), bins=num, labels=range(num), duplicates='drop')
</code></pre>
<p>I believe you were getting NaN values because, according to the docs for <code>pd.cut</code> <a h... | python|pandas | 0 |
11,607 | 37,135,460 | Pymc size / indexing issue | <p>I am trying to model Kruschke's "filtration-condensation experiment" with pymc 2.3.5. (numpy 1.10.1)
Basicaly there are:</p>
<ul>
<li>4 groups</li>
<li>each group has 40 individuals</li>
<li>each individual has 64 Bernoulli trials (correct/incorrect)</li>
</ul>
<p>What I am modeling:</p>
<ul>
<li><p>each individu... | <p>First of all, I can confirm that the first version doesn't lead to stable results. What I can't confirm is that the second one is much better; I have seen very different results also with the second code, with values for the first mu parameter varying between 0.17 and 0.9 for different runs. </p>
<p>The convergence... | numpy|modeling|bayesian|pymc|mcmc | 1 |
11,608 | 54,778,472 | Google Colab - tensowflow object detection api - 'function' object has no attribute 'called' | <p>I encountered the following error when I try to test the object detection api model_builder_test.py.</p>
<pre><code>!apt-get install -y -qq protobuf-compiler python-pil python-lxml
!git clone --quiet https://github.com/tensorflow/models.git
import os
os.chdir('models/research')
!protoc object_detection/protos/*.p... | <p>This is how I overcame the issue:</p>
<ol>
<li><p>install prompt-toolkit to the version 1.0.15, as explained in the link below
<a href="https://github.com/jupyter/jupyter_console/issues/158" rel="nofollow noreferrer">https://github.com/jupyter/jupyter_console/issues/158</a></p></li>
<li><p>restart the runtime to ac... | python-3.x|tensorflow|matplotlib|google-colaboratory|object-detection-api | 0 |
11,609 | 54,991,948 | How to use numpy roots for trig function | <p>Trying to write some code to find the roots of the function -1.5sin(3x) on the domain [-2, 2]. Is this possible with the numpy roots function? </p>
<p>Essentially the code will look something like this:</p>
<pre><code>import numpy as np
def f(x):
x = -1.5*sin(3*x)
return x
print(np.roots())
</code></pre>
<p>I... | <p><code>numpy.roots</code> needs a polynomial. You do not have one. <code>numpy.roots</code> cannot be used to find the roots of an arbitrary function.</p> | python|numpy | 0 |
11,610 | 49,630,178 | how to know which node is dropped after using keras dropout layer | <p>From <a href="https://nickcdryan.com/2017/06/13/dropconnect-implementation-in-python-and-tensorflow/" rel="nofollow noreferrer">nick blog</a> it is clear that in dropout layer of CNN model we drop some nodes on the basis of bernoulli. But how to verify it, i.e. how to check which node is not selected. In DropConnect... | <p>Concerning your second question, if you see <a href="https://github.com/keras-team/keras/blob/master/keras/layers/core.py" rel="nofollow noreferrer">Keras code</a>, in the <code>call</code> method form <code>Dropout</code> class:</p>
<pre><code>def call(self, inputs, training=None):
if 0. < self.rate < 1.... | python|tensorflow|keras|keras-layer|keras-2 | 1 |
11,611 | 49,444,465 | "OSError: [Errno 1] Operation not permitted" error when downloading Pandas on macOS | <p>I tried installing Pandas on macOS.
It first tries to install Numpy, says </p>
<p>Found existing installation: numpy 1.8.0rc1</p>
<pre><code>DEPRECATION: Uninstalling a distutils installed project (numpy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a dist... | <p>I guess you need to run <code>pip</code> as <code>super user</code> or a system user that has the permission to write to <code>Python package site</code> directory;
I don't own a <code>mac</code> but I think the general course of action for you will be to try to install <code>pandas</code> as <code>root</code> like ... | python|pandas|numpy | 0 |
11,612 | 27,913,157 | Recursive subtraction in numpy | <p>Consider the following recursive problem: Say I have <code>total_units</code> of something that I can spend in <code>total_days</code>. On any given day, as I spend these units, I have <code>units_left</code> units and <code>days_left</code> left. Based on this, I can define the <code>ideal_daily_rate</code> as <co... | <p>I don't see why this needs recursion. Here is a short simulation to get the values you are describing. It is essentially a decay difference equation (a discrete version of a differential equation). Correct me if you think I have misunderstood something.</p>
<pre><code>days_left = 100
units_left = 50
ideal_daily_rat... | python|numpy|recursion|scipy | 2 |
11,613 | 35,258,528 | after adding constant column in Dataframe it overrides previous one | <p>'tell_skills' is a dictionary which forms dataframe with columns a,b,c. Now I want to add another constant column d with value 'z'. There are two different dataframes with two different values of z which I want to concatenate. The 'final' dataframe is showing last column 'd' as 150 only instead of 150 and 133 divide... | <p>When you use</p>
<pre><code>df_comp=df_company
</code></pre>
<p>it makes <code>df_comp</code> a second reference to the original <code>df_company</code> so when </p>
<pre><code>`df_comp['d'] = z`
</code></pre>
<p>will essentially set <code>df_company['d'] = z</code>, to make a copy of the dataFrame you can use ... | python|pandas|dataframe | 0 |
11,614 | 35,130,990 | subsetting pandas dataframe on specific date value | <p>I have a pandas dataframe like this</p>
<pre><code>order_id buyer_id item_id time
537 79 93 2016-01-04 10:20:00
540 191 93 2016-01-04 10:30:00
556 251 82 2016-01-04 13:39:00
589 191 104 2016-01-05 10:59:00
596 251 99 2016-01-05 13... | <p>The problem here is that the comparison is being performed for an exact match, as none of the times are <code>'00:00:00'</code> then no matches occur, you'd have to compare just the date components in order for this to work:</p>
<pre><code>In [20]:
df[df['time'].dt.date == pd.to_datetime('2016-01-04').date()]
Out[... | python|date|pandas | 1 |
11,615 | 31,044,837 | Python: How to check if an array is contained in another array using `numpy.all`and `numpy.any`? | <p>I am working on detecting certain areas on an image using <code>scikit-image</code>. I was able to detect blobs using <code>blob_doh</code> function. Also I was able to find regions using <code>Canny edge detector</code> and labeling. </p>
<p>Now I want to check if the blobs, which I found before, are inside of tho... | <p>You can do it if you convert pixel_array to a list. Not sure how efficient that would be, but this works:</p>
<pre><code>if [x,y] in pixel_array.tolist():
</code></pre>
<p><strong>EDIT:</strong></p>
<p>Looks like someone has already timed lots of different options <a href="https://stackoverflow.com/a/14766816/588... | python|arrays|python-2.7|numpy|scikit-image | 2 |
11,616 | 67,272,899 | Regex, Pandas and flagging rows | <p>I'm attempting to flag any records that contain User Defined "incorrect" characters. In this case, record two (2) should return as a Non-Valid Record, but I seem to be capturing either record 1 or 3. These would be deemed "correct". <strong>Any suggestions on why these are flagging rather than &q... | <pre><code>for x in dft['HOME1']:
for c in x:
if c not in chars:
print(c,x)
conditions = [dft['HOME1'].apply(lambda x: x)==x, dft['HOME1'].apply(lambda x: x)!=x]
choices = [1,0]
dft['NonValidHOME1'] = np.select(conditions,choices,default=0)
#[print(c) for x in dft['HOME1'] for c in ... | python|regex|pandas|dataframe | 0 |
11,617 | 67,263,594 | Making a hierarchical (MultiIndex) or pivot from data with many rows per date | <p>How can I best format data that has multiple "levels" per time/date into a pandas DataFrame?</p>
<p>e.g. (CSV data from <a href="http://www.bccdc.ca/Health-Info-Site/Documents/BCCDC_COVID19_Regional_Summary_Data.csv" rel="nofollow noreferrer">http://www.bccdc.ca/Health-Info-Site/Documents/BCCDC_COVID19_Reg... | <p>You don't need to lose granularity when using a pivot-table. <code>DataFrame.pivot</code> reshapes the data without aggregation. You just have to decide what is an index (row levels) and what is a column (column levels). In your case you might want the provinces/subprovinces as an index.</p>
<pre><code>import pandas... | python|pandas | 1 |
11,618 | 60,154,057 | How to create pandas dataframe from array([[[135, 2270.24]]], dtype=object) | <p>I am embarassed with this. I would like to transform this array to pandas dataframe with one column let's say called "feature" and one value: [135, 2270.24]:
array([[[135, 2270.24]]], dtype=object)</p>
<p>I tried this but returns ValueError: Must pass 2-d input
<code>df = pd.DataFrame(C, columns = ['feature'])</cod... | <p>I'm not entirely sure I follow exactly what you're asking for. But if my interpretation is correct you're looking for something like this?</p>
<pre><code>import pandas as pd
import numpy as np
# setup
val = np.array([[[135, 2270.24]]])
# logic
data = [{'feature': val[0][0]}]
df = pd.DataFrame(data)
</code></pre>
... | arrays|pandas|dataframe | 0 |
11,619 | 60,221,579 | Python slicing list of tuples and converting values to integers - Confusion regarding why it's possible with numpy arrays but not list of tuples | <p>I am trying to slice the first and last values from a list of list then convert these values to integers. I found a solution but I am confused why this solution works and am wondering if there is a simpler way as it seems rather inelegant. </p>
<p>The two ways I found to slice a single value from a list of a list a... | <p>If you just want the first and last number to be converted to integer, you can simply do this:</p>
<pre><code>a = [('1', 'T', ''), ('2', 'R', 'S'), ('3', 'E', 'S'), ('4', 'T', 'S')]
firstNum = int(a[0][0])
lastNum = int(a[-1][0])
print(firstNum)
print(lastNum)
</code></pre>
<p>There is no need for slicing or oth... | python|arrays|list|numpy|tuples | 1 |
11,620 | 60,101,973 | How to use GPU in pytorch? | <p>I tried following steps at: <a href="https://pytorch.org/get-started/locally/" rel="nofollow noreferrer">https://pytorch.org/get-started/locally/</a></p>
<p>First I created a conda environment as:</p>
<pre><code>conda create -n facenet37_2 python=3.7
</code></pre>
<p>Then on above site I selected:</p>
<pre><code... | <p>The GeForce GT 630M has compute capability 2.1 and therefore only supports up to CUDA 8.</p>
<ul>
<li>PyTorch <strong>binaries</strong> dropped support for compute capability <= 5.0 in <a href="https://github.com/pytorch/pytorch/releases/tag/v0.3.1" rel="nofollow noreferrer">PyTorch 0.3.1</a>. It's not clear to ... | python|installation|gpu|pytorch|conda | 3 |
11,621 | 60,252,322 | How to join multiple rows sequentially in a numpy array? | <p>I've a data like this,</p>
<pre><code>data = [array(['a', 'b', 'c']),
array([['d', 'e', 'f'], ['g', 'h', 'i']]),
array([['j', 'k', 'l'], ['m', 'n', 'o'], ['p', 'q', 'r']])]
</code></pre>
<p>I want to join values in inner list sequentially. This is the desired output that I need.</p>
<pre><code>[... | <pre><code>In [300]: [np.array([' '.join(ij) for ij in zip(*np.atleast_2d(row))]) for row in data]
Out[300]:
[array(['a', 'b', 'c'], dtype='<U1'),
array(['d g', 'e h', 'f i'], dtype='<U3'),
array(['j m p', 'k n q', 'l o r'], dtype='<U5')]
</code></pre>
<p>The first array is 1d, thus requiring the <... | python|python-3.x|numpy | 3 |
11,622 | 65,473,095 | numpy test if each value in row in row of another array | <p>I have two arrays of the same shape (2500, 9). I am trying to figure out the most efficient way to test if each value in a row in <code>array1</code> is in the corresponding row in <code>array2</code>. Consider the following simplified example:</p>
<pre><code>>>> array1 = np.array([[1, 2, 3], [4, 5, 6], [3,... | <p>Numpy's <code>==</code> equal does it:</p>
<pre><code>>>> array1 = np.array([[1, 2, 3], [4, 5, 6], [3, 8, 9]])
>>> array2 = np.array([[0, 2, 4], [3, 5, 6], [6, 8, 9]])
>>> print(array1 == array2)
[[False True False]
[False True True]
[False True True]]
>>>
</code></pre>
<p>... | python|numpy|numpy-ndarray | 2 |
11,623 | 65,194,102 | Merge Different Dataframe which is already grouped on column | <p>First dataframe:</p>
<pre><code>Subject Branch Test1 Test2 Test3
DS IT 45 43 44
CE 40 45 39
JAVA MCA 43 34 39
IT 38 43 44
CE ... | <p>If you are sure first, second, third... rows by <code>Subject</code> are same for both DataFrames is possible use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> for counter and use it for mergin... | python|pandas|dataframe|pandas-groupby | 2 |
11,624 | 50,219,134 | Adjust number of samples in Tensorflow nce_loss while training | <p>I'd like to adjust the sampling rate during training of my neural network to test some stuff and see what happens. To achieve that my idea was to create an new loss and optimizer for every iteration using the same computation graph. </p>
<pre><code>def optimize(self, negative_sampling_rate):
return tf.train.Gra... | <p>First of all, it should be okay to change the number of samples in the nce loss without causing problems for the optimizer. The internal variables stored by some optimizers relate to the historical gradients of the trainable variables in your graph. </p>
<p>Secondly, if you do want to reset the state of your optimi... | python|tensorflow|machine-learning|loss-function | 1 |
11,625 | 50,146,213 | Numpy equal dtype | <p>Should the keyword argument <code>dtype</code> is not considered in <code>np.equal</code>?</p>
<p>In the function <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.equal.html" rel="nofollow noreferrer">documentation</a>, it seems to indicate that <code>dtype</code> should a valid keyword ar... | <p><code>np.equal()</code> is a "<a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/ufuncs.html" rel="nofollow noreferrer">ufunc</a>", all of which have an optional <code>dtype</code> parameter. But not all ufuncs actually need the <code>dtype</code> parameter--it's just part of their universal signature.</p>
... | python|numpy|numpy-ufunc | 2 |
11,626 | 49,882,714 | Sum elements in a list by index within a loop | <p>I have a function that returns a oneliner pd.DataFrame. I have wrapped that function in a loop and want to aggregate the results based on an index.</p>
<pre><code>def func(input):
some calculation
return oneliner
</code></pre>
<p><code>oneliner</code> looks like this</p>
<pre><code>date return ... | <p>Your idea of returning a list of dataframes and then appending them or adding a result via a loop is inefficient.</p>
<p>Instead, I advise you output a list of lists and then build your dataframe in one step.</p>
<pre><code>def func(var):
"""Return list of [date, return, return_lev]"""
# some calculation
... | python|list|pandas|dataframe|aggregate | 3 |
11,627 | 64,127,733 | How to create a cumulative sum column in python if column value is greater than other value | <p>I am working now in getting a cumulative sum column using pandas. However, this column most include cumulative sum only if other column value is greater than other column value. Here's an example of my current data:</p>
<pre><code>Index A B C
0 1 20 3
1 10 15 11
2... | <p>There probably is more legant solution, but this also works.</p>
<p>We first create two dummy columns - x and x_shift.</p>
<p>df.x is conditional where we retain values of df.A where df.B > df.C.</p>
<p>df.x_shift is where we shift values one row below and fill na with 0.</p>
<p>In last step we conditionally add ... | python|pandas | 3 |
11,628 | 46,832,865 | tensorflow softmax_cross_entropy code | <p>Since the source code of <code>tf.nn.softmax_cross_entropy_with_logits</code> in <code>gen_nn_ops</code> is hidden, could anyone perhaps explain me how tensorflow compute the cross entropy after Softmax. I mean, after softmax it might output 0 because of precision which will give rise to a NaN problem with cross ent... | <p>The implementation of <code>tf.nn.softmax_cross_entropy_with_logits</code> further goes to native C++ code, <a href="https://github.com/tensorflow/tensorflow/blob/r1.3/tensorflow/compiler/tf2xla/kernels/softmax_op.cc#L81" rel="nofollow noreferrer">here</a> is XLA implementation. Logits are not bound and <code>0</cod... | tensorflow|softmax|cross-entropy | 0 |
11,629 | 46,666,342 | How to create data frame from pandas series containg lists of different length | <p>I've got pandas series withe below structure:</p>
<pre><code>> 0 [{k1:a,k2:b,k3:c},{k1:d,k2:e,k3:f}]
> 1 [{k1:g,k2:h,k3:i},{k1:j,k2:k,k3:l},{k1:ł,k2:m,k3:n}]
> 2 [{k1:o,k2:p,k3:r}
> 3 [{k1:s,k2:t,k3:w},{k1:q,k2:z,k3:w},{k1:x,k2:y,k3:z},{k1:v,k2:f,k3:g}]
</code></pre>
<p>As You can see this series c... | <p>Use concat with <code>apply pd.DataFrame</code> i.e </p>
<pre><code>x = pd.Series([[{'k1':'a','k2':'b','k3':'c'},{'k1':'d','k2':'e','k3':'f'}], [{'k1':'g','k2':'h','k3':'i'},{'k1':'j','k2':'k','k3':'l'},{'k1':'ł','k2':'m','k3':'n'}],
[{'k1':'o','k2':'p','k3':'r'}],[{'k1':'s','k2':'t','k3':'w'},{'k1':'q','k2'... | python|pandas|dataframe | 1 |
11,630 | 46,790,749 | a possible bug in numpy.isclose when comparing matrices with nans | <p>consider the next piece of code:</p>
<pre><code>In [90]: m1 = np.matrix([1,2,3], dtype=np.float32)
In [91]: m2 = np.matrix([1,2,3], dtype=np.float32)
In [92]: m3 = np.matrix([1,2,'nan'], dtype=np.float32)
In [93]: np.isclose(m1, m2, equal_nan=True)
Out[93]: matrix([[ True, True, True]], dtype=bool)
In [94]: n... | <p>The problem comes from <code>np.nan == np.nan</code>, which is <code>False</code> in the float logic.</p>
<pre><code>In [39]: np.nan == np.nan
Out[39]: False
The `equal_nan` parameter is to force two `nan` values to be considered as equal , not to consider any value to be equal to `nan`.
In [37]: np.isclose(m3,m3... | numpy|matrix|nan | 1 |
11,631 | 46,850,111 | Fill NA values in Pandas Dataframe using Collaborative Filtering | <p>I am working on a database of Organic Compounds, and some of the cells have NA values (look at the HFUS column in the second pic):</p>
<p><a href="https://i.stack.imgur.com/H0VEv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H0VEv.png" alt="enter image description here"></a></p>
<p><a href="ht... | <p>you need to transpose the matrix. To create recommend for HFUS, you need to find closet element based on other fields.</p>
<p>from your link</p>
<pre><code>tf_trans = td.T
target = tf_trans[traget_col]
sim_target = tf.corrwith(target)
</code></pre>
<p>I think you also can use cosine to find similarity and iterate... | python|pandas|machine-learning|collaborative-filtering|data-cleaning | 0 |
11,632 | 33,059,254 | group data ranges by column value not zero | <p>I have the following dataframe</p>
<pre><code> count
2015-09-28 2
2015-09-29 2
2015-09-30 0
2015-10-01 2
2015-10-02 3
2015-10-05 2
2015-10-06 1
2015-10-07 0
2015-10-08 1
</code></pre>
<p>I would like to group by data ranges that are separated by the days with... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html" rel="nofollow"><code>cumsum</code></a> to associate each row with a group number:</p>
<pre><code>In [134]: df['groupno'] = (df['count'] == 0).cumsum()
In [135]: df
Out[135]:
count groupno
2015-09-28 2 ... | python|pandas | 3 |
11,633 | 33,056,799 | create a Data frame as a function of row index value and column name? | <p>What is the best way to create a pandas Data frame as a function of row index value and column name?</p>
<p>So for DataFrame where index in X, columns in Y, each value would be some f(x,y) where x in X and y in Y (eg could be concatenation of index and column names)</p>
<p>I know I can write a loop to do this, but... | <p>You could use a list comprehension to prepare the values as a list of lists, and then pass the list of lists to <code>pd.DataFrame</code>:</p>
<pre><code>import pandas as pd
rows = ['1','2','3']
cols = ['X','Y']
df = pd.DataFrame(([col+row for col in cols] for row in rows),
index=rows, columns=co... | python|pandas|dataframe | 2 |
11,634 | 38,804,820 | [Numpy/Pandas]How can I efficiently create a panel data set from transaction records? | <p>I have data arranged in the following form:</p>
<pre><code>ID,DATE,STATUS
1,6/20/2011,A
1,1/14/2013,B
1,8/1/2016,C
2,3/1/2005,A
2,4/30/2005,B
2,6/30/2010,C
2,8/20/2010,D
</code></pre>
<p>I want to convert these transactions into an unbalanced panel with an annual frequency:</p>
<pre><code>ID,YEAR,STATUS
1,2011,A
... | <p>Here's one way:</p>
<pre><code>import pandas as pd
df = pd.read_csv('file', parse_dates=['DATE'])
df = df.set_index('DATE').resample('A').ffill()
df['YEAR'] = df.index.year
df = df.sort_values(['ID', 'YEAR']).reset_index(drop=True)
df
Out:
ID STATUS YEAR
0 1 A 2011
1 1 A 2012
2 1 B ... | python|pandas|numpy | 2 |
11,635 | 38,935,005 | Need warning message if count of each country code is less than 5 | <p>I am trying to get a warning or print message if count or frequency of a particular country code is less than 5.</p>
<pre><code>QuoteID
1500759-BE
1500759-BE
1500759-BE
1500759-BE
1605101-FR
1605101-FR
1605101-FR
1605119-FR
1605119-FR
1605119-FR
1605119-FR
1605119-FR
1600896-NL
1600896-NL
1600896-NL
1600898-NL
1600... | <p>You can use a <code>Counter</code> provided by Python's <code>collections</code> module to count the occurrences of the elements in a list.
In addition you can extract the country codes given in your sample data by splitting all lines and strip off the last two elements of each line (which is the country code).</p>
... | python|loops|pandas|dataframe | 0 |
11,636 | 38,823,331 | How do I vectorize a conditional timedelta operation? | <p>I wanted to avoid the for loops in Python pandas, but I didn't make it due to lack of exposure. I wanted to derive a new column based on an existing column by adding some amount of information to it.</p>
<p>My Scenario:</p>
<pre><code>for each in data['days']:
if each<100000:
clsdate.append(datetime... | <p>You can use pandas' datetime functions:</p>
<pre><code>df = pd.DataFrame()
df['days'] = [1, 3, 2, 4]
pd.to_datetime('now') + pd.to_timedelta(df['days'], unit='days')
Out:
0 2016-08-09 07:25:22
1 2016-08-11 07:25:22
2 2016-08-10 07:25:22
3 2016-08-12 07:25:22
Name: days, dtype: datetime64[ns]
</code></pre> | python|loops|pandas | 4 |
11,637 | 63,113,500 | How to select all rows of group if one row within group meets certain condition in pandas | <p>I have a dataframe which looks like this</p>
<pre><code>pd.DataFrame({'a': ['cust1', 'cust1', 'cust1', 'cust2', 'cust2', 'cust3', 'cust3', 'cust4', 'cust4'],
'year': [2017, 2018, 2019, 2018, 2019, 2017, 2018, 2018, 2019],
'cond': [True, True, False, True, True, True, True, True,... | <p>try this, <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="nofollow noreferrer"><code>boolean_indexing</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html#pandas-series-isin" rel="nofollow noreferrer"><code>Series.isin</code></a... | python|pandas|pandas-groupby | 2 |
11,638 | 63,287,783 | Compare of 2 csv files to get the result in a different csv file with the result of True or False in python | <p>I have 2 csv files and I am trying compare it, where the output should come in a different csv file with the the result comparing the data in multiple file with True or false.</p>
<p>Could you please help me to get the right code.</p>
<p><img src="https://i.stack.imgur.com/IVBG0.png" alt="" /></p>
<p><img src="https... | <p>Using Pythons CSV module and assuming that your CSV files use commas as delimiters:</p>
<pre><code>import csv
with open("Book1.CSV") as book1, open("Book2.CSV") as book2, open("Result.csv", "w") as result:
reader1 = csv.DictReader(book1)
reader2 = csv.DictReader(book2... | python|pandas | 0 |
11,639 | 63,069,647 | Showing specific columns in a dataframe based on list | <p>I have the following data frame</p>
<pre><code>df = pd.DataFrame({'Name': ['Sally', 'Fred', 'Tim'],
'Random Text - Amish': [1,1,1],
'Text is Random - Matt': [1,0,1],
'More Random Text - Luke': [1,0,0],
'OMG this text is random - Phil': [0,0,1],
... | <p>Using <code>str.endswith</code> on <code>df.columns</code></p>
<p><strong>Ex:</strong></p>
<pre><code>df = pd.DataFrame({'Name': ['Sally', 'Fred', 'Tim'],
'Random Text - Amish': [1,1,1],
'Text is Random - Matt': [1,0,1],
'More Random Text - Luke': [1,0,0],
... | python|pandas|list|dataframe|sorting | 0 |
11,640 | 63,048,710 | OpenCV findHomography should return an identity matrix. Why is it instead returning these unexpected homography matrices? | <p>I use findHomography to stitch images together. But as I was testing it with already perfectly overlapping pictures I got some unexpected results. I was expecting that the homography would always be an identity matrix and most of the time that was true, but one time it returned a completely different matrix.</p>
<p>... | <p>So now I tested the suggestions by @ZWang and @Micka. Here is an updated version of the code provided in my question with added comments for explanation. I hope this will help some people!</p>
<pre><code> import numpy as np
import cv2
# Original arrays were the problem occurs. There are enough points... | python|numpy|opencv|homography|image-stitching | 0 |
11,641 | 67,929,030 | pandas subtract values in two dataframes with identical columns create new dataframe to store result | <p>I am trying to create a new dataframe <code>new_df</code> with a new column containing the difference in values from subtracting identical columns in 2 separate dataframes: <code>df1</code> <code>df2</code></p>
<p>I have tried to use the code <code>new_df.loc['difference'] = df1.loc['s_values'] - df2.loc['s_values']... | <p>You can try this (full example):</p>
<p><strong>Input:</strong></p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'gender': {0: 'woman', 1: 'woman'},
'year': {0: 2007, 1: 2007},
'stats': {0: 'height', 1: 'cigarette use'},
's_values': {0: 40, 1: 31}})
df2 = pd.DataFrame({'gender': {0: 'men', 1: 'men'},
'ye... | python|pandas|dataframe | 1 |
11,642 | 68,000,322 | Count number of columns above a date | <p>I have a pandas dataframe with several columns and I would like to know the number of columns above the date 2016-12-31 . Here is an example:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Bill</th>
<th>Date 1</th>
<th>Date 2</th>
<th>Date 3</th>
<th>Date 4</th>
<th>Bill 2</... | <p>Just create the mask and call <code>sum</code> on <code>axis=1</code></p>
<pre class="lang-py prettyprint-override"><code>date = pd.to_datetime('2016-12-31')
(df[['Date 1','Date 2','Date 3','Date 4']]>date).sum(1)
</code></pre>
<p><strong>OUTPUT:</strong></p>
<pre class="lang-py prettyprint-override"><code>0 0... | python|pandas | 3 |
11,643 | 67,681,863 | How to match two dataframes based on lookup fields and update those fields only in pandas? | <p>I have two dataframes. I have to match them based on lookup field columns and update those columns in one of the dataframe if found any mismatch.</p>
<p>Example:</p>
<pre><code>lkp_field = ['program_name', 'file_type']
df1:
project_number file_name program_name file_type
10 pdf_11... | <p>If need match by <code>project_number</code> values first match DataFrame by convert values to index and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.update.html" rel="nofollow noreferrer"><code>DataFrame.update</code></a> only by selected columns:</p>
<pre><code>df1 =... | python|python-3.x|pandas|dataframe | 0 |
11,644 | 67,983,448 | Plot dates in Pandas with line connecting their duration | <p>I have a dataframe that contains two columns with dates astype Timestamps. I would like to plot a figure where the time between those dates is 1 and the time outside those dates is 0: kinda like an 'active on/off' binary situation. I have discretised and indexed the whole day in intervals of 1 minute. After that, I ... | <p>you can use <a href="https://plotly.com/python-api-reference/generated/plotly.express.timeline.html" rel="nofollow noreferrer">plotly timeline</a> to simply plot when a sensor is on or off. I added a row to your sample as sensor is always on across the 5 rows.</p>
<pre><code>import plotly.express as px
df = pd.rea... | pandas|dataframe | 1 |
11,645 | 41,268,455 | How to load Pickle objects with JSON in Python 2.7? | <p>I have a pickled object that I want to load. However, Pickle gives some strange (possibly memory-related) errors, that are briefly described here as well:</p>
<p><a href="https://stackoverflow.com/questions/10263564/python-pickling-dictionary-eoferror">Python Pickling Dictionary EOFError</a></p>
<p>When loading, i... | <p>No. The <code>json</code> module cannot read pickled data, as Pickle is not JSON. Converting Pickle to JSON would be equivalent to unpickling and then serializing as JSON, both of which you've said aren't working.</p> | python|json|numpy|pickle|jsonpickle | 0 |
11,646 | 41,231,526 | Fine-tuning / Retraining transferred learning model with an additional image set | <p>Using the <code>retrain.py</code> script provided in the tensorflow source example, I've retrained the top layer of the <code>inception-v3</code> model to be able to classify the flower set (provided image set of the 5 flowers).</p>
<p>What I am trying to do now, is to take the new transferred learning model (TL-mo... | <p>(Converted from a comment to an answer, per @dga's request)</p>
<p>Unfortunately this isn't easy without doing some 'brain surgery' on the model structure. I don't have a great answer, since I've never done this myself, but in theory you should be able to restore the old five-category fully-connected layer into a n... | tensorflow | 0 |
11,647 | 41,551,658 | How to create a frequency distribution table on given data with Python in Jupyter notebook with as few code as possible? | <p>Develop a frequency distribution summarizing this data.This data is a demand for an object over a period of 20 days.</p>
<p>2 1 0 2 1 3 0 2 4 0 3 2 3 4 2 2 2 4 3 0. The task is to create a table in the jupyter notebook with columns Demand and Frequency. Note: Demand has to be in ascending order. This is what I did.... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.value_counts.html" rel="noreferrer"><code>value_counts</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>reset_index</code></a> and sorting by... | python|pandas|statistics|jupyter-notebook | 7 |
11,648 | 27,559,781 | imshow assertion failed drawChessboardCorner() of opencv returns nothing in Python | <p>I am new in OpenCV programming in Python. Tried with most basic camera feed program that went well. When trying to calibrate a pinhole camera using <a href="http://docs.opencv.org/trunk/doc/py_tutorials/py_calib3d/py_calibration/py_calibration.html#calibration" rel="nofollow">OpenCV Calibration and 3d Reconstruction... | <p>It looks to me like the problem is that you are assigning the output of </p>
<pre><code>cv2.drawChessboardCorners(img, (7, 6), corners2, ret)
</code></pre>
<p>to img, which the tutorial does not do. This function call is probably not returning anything. Try removing the assignment from that line and see what happe... | python|opencv|numpy | 6 |
11,649 | 27,464,955 | Is it possible to sum over multiple axis in numexpr? | <p>I am trying to do something like the following:</p>
<pre><code>import numexpr as ne
a = np.random.rand(10, 1)
b = np.random.rand(1, 10)
ne.NumExpr('sum(sum(a*b, 1), 0)').run(a, b) # <- error: reduction operations must occur last
ne.NumExpr('sum(a*b, [1, 0])').run(a, b) # <- error: ValueError: cannot encode a... | <p>You can sum over multiple axes using numexpr as follows:</p>
<pre><code>import numpy as np
import numexpr as ne
a = np.random.rand(10, 1)
b = np.random.rand(1, 10)
ne.evaluate('sum(x, 0)', {'x': ne.evaluate('sum(a*b, 1)')})
</code></pre> | python|arrays|numpy|numexpr | 0 |
11,650 | 61,439,662 | How to find out the index of value in list? | <p>I have a list with floats and I am looking for an index of the value in the interval (5-eps;5+eps). How to do that please? This gives me an error about types: TypeError: '<' not supported between instances of 'list' and 'float'</p>
<pre><code>import numpy as np
LIST = [4.1, 5.02, 4.99999, 5.00001]
eps = 0.001
i... | <p>Use a numpy array.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
LIST = [4.1, 5.02, 4.99999, 5.00001]
np_list = np.array(LIST)
eps = 0.001
index, = np.where((np_list < 5+eps) & (np_list > 5-eps))
print('Index', index)
</code></pre>
<p><strong>OUTPUT</strong></p>
<pre class="lan... | python-3.x|numpy | 1 |
11,651 | 61,307,648 | Optimizing function to compare every value in array to each other | <p>I'm using tensorflow for some machine learning, and I need to do some transformations to the data beforehand. The bottleneck I'm running into is my function to take an array of numbers and compare every number to every other number and create a table of those comparisons.</p>
<p>The function is the following:</p>
... | <p>Regarding the Comparison algorithm it seems that it is optimised only as since you have to create a comparison table matrix of n*n (n = size of list). So, you need total n^2 records . It means Time complexity is fair enough.</p>
<p>Now coming to next point that how you can do it using GPU?</p>
<ul>
<li>you can use ... | python|tensorflow|math|optimization | 2 |
11,652 | 68,759,682 | Re-shape a dataframe for plotting in python | <p>I have a table of data that I wish to plot as a line plot in python, but cannot get my head around how to shape it to plot as I want it.</p>
<ul>
<li>I want there to be 10 lines on the graph, the Cost Ranges (hue='Cost_Range_' in my eyes).</li>
<li>The x axis to be 6 points: Actual_Cost_7 - Actual_Cost_12.</li>
<li>... | <ul>
<li>have used <strong>plotly</strong> to generate figure</li>
<li>start with <code>pd.melt()</code> to structure for <strong>plotly</strong></li>
<li>xaxis needs to be a continuous not a categorical to generate the plot you want. Hence have generated another dataframe that will provide a continuous number to the ... | python|pandas|dataframe|matplotlib|seaborn | 0 |
11,653 | 68,712,530 | "To location array" to index array | <p>I have some data array</p>
<pre><code>a = [6,4,3,1,5]
</code></pre>
<p>and a "to location array", that gives indices for how these elements should be reshuffled,</p>
<pre><code>b = [4,2,0,1,3]
</code></pre>
<p>What this means: the 1st element of <code>a</code> should go to index 4, the 2nd element of <code... | <p>If you don't need <code>d</code>, you can directly get <code>c</code> with <a href="https://numpy.org/doc/stable/reference/generated/numpy.put_along_axis.html#numpy.put_along_axis" rel="nofollow noreferrer"><code>np.put_along_axis</code></a>:</p>
<pre><code>>>> a = np.array([6,4,3,1,5])
>>> b = np.... | python|arrays|numpy|permutation|shuffle | 1 |
11,654 | 5,578,172 | Can I use my own Python class with numpy or some other matrix library? | <p>I'd like to be able to do matrix operations using a Python class as the elements—in this case, a simple <a href="http://en.wikipedia.org/wiki/Galois_field" rel="nofollow noreferrer">Galois field</a> implementation. It implements the necessary <code>__add__</code>, <code>__mul__</code>, <code>__sub__</code> etc.</p>
... | <p>You can use <code>object</code> as the <code>dtype</code>, which will allow arbitrary Python objects. I don't think there's any way of specializing a numpy array to accept only one particular class of Python object.</p> | python|matrix|numpy | 8 |
11,655 | 53,183,433 | AttributeError: 'numpy.ndarray' object has no attribute 'iloc' | <p>I am trying to combine two machine learning algorithm using stacking to achieve greater results but am failing in some of the aspects.
Here's my code:</p>
<p>class Ensemble(threading.Thread):
"Stacking with three Classification Models to improve the accuracy of Predictions"
def <strong>init</strong>(self, X... | <p>As the comments suggest, <code>.iloc</code> is a Pandas dataframe method.</p>
<p>To filter a numpy array you just need: <code>array[indices]</code></p>
<p>In your case:</p>
<pre><code>x_train,x_val=train[train_indices],train[val_indices]
y_train,y_val=y[train_indices],y[val_indices]
</code></pre> | pandas|numpy | 18 |
11,656 | 53,152,243 | Keras metric based on output of an intermediate layer | <p>Problem:
I want to monitor my model better during training. Because in some cases the loss suddenly turn to nan during training, and I want to know what the model is doing when this happens.
Besides that, I want to see if a certain layer obeys a specific condition (rows and columns should sum to one).</p>
<p>Approa... | <p><em><strong>The <code>model.metrics_tensors.append</code> does not work in <code>TensorFlow 2.x</code></strong></em></p>
<p>So if you're using the <code>add_loss</code> method, you can also use the <code>model.add_metric</code> method in <code>Keras / TensorFlow 2.x</code>.</p>
<p>For example, if we want to track th... | python|tensorflow|keras | 2 |
11,657 | 65,905,901 | Error training tensorflow model: can't find '__main__' module in 'Tensorflow' | <p>I am trying to train a tensorflow model on windows in jupyter notebook. Environment and object detection API installed correctly.</p>
<p>I run this command after configuring my paths:</p>
<pre><code>print("""python {}/research/object_detection/model_main_tf2.py --model_dir={}/{} --pipeline_config_path... | <p>you need to go to this path "tensorflow/models/research" and put this lines in command line:</p>
<pre><code>cd /path-to/models-master/research/
python setup.py build
python setup.py install
</code></pre>
<p>Then do this to avoid extra errors</p>
<pre><code>cd /path-to/models-master/research/slim
python set... | python|tensorflow|machine-learning|computer-vision|object-detection-api | 0 |
11,658 | 65,771,548 | Too many indices for array | python | <p>I'm trying to copy arrays to a pandas Dataframe and get the error "too many indices for array".</p>
<pre><code>temp = pd.date_range(date_from, date_to)[:len(pr_daily)]
for index in range(len(a_id)):
if index == 0:
finalDataframe['date'] = temp
finalDataframe[f'pr_{a_id[index]}'] = pr_dail... | <p>This error is thrown when you try to access an array element by providing too much indices.</p>
<p>e.g You try to access the second dimension of a 1-dimension array.</p>
<p>Check the shape of <code>pr_daily</code> and <code>rad_daily</code> if they indeed are 2D arrays.</p>
<pre><code>a = np.random.rand(5,)
b = np.r... | python|dataframe|numpy | 2 |
11,659 | 65,728,227 | Tensorflow or array based bitwise OR/AND in Javascript | <p>It seems the python implementation of TensorFlow has <a href="https://www.tensorflow.org/api_docs/python/tf/bitwise/bitwise_or" rel="nofollow noreferrer">bitwise_or implementation</a>, however, the <a href="https://js.tensorflow.org/api/latest/" rel="nofollow noreferrer">TensorFlow.js</a> does not.</p>
<p>I need to ... | <p>EDIT: for large arrays and performant code, <a href="https://stackoverflow.com/a/65758597/12728698">I used WebAssembly</a></p>
<p>Well, I have something, going to test the performance but it seems like <a href="https://mathjs.org/" rel="nofollow noreferrer">mathjs</a> does have the functionality necessary</p>
<p>Tur... | javascript|arrays|tensorflow|bitwise-operators | 0 |
11,660 | 65,533,207 | Python converting dictionary to dataframe and exporting it to a csv file | <p>I am trying to convert a dictionary to a dataframe and then exporting it to a csv file but for some reason when the program exports the dataframe it changes the columns and rows.</p>
<pre><code>df = pd.read_csv('test.csv')
for i in range(len(df['name'])):
names.append(df['name'][i])
balances.append(df['balan... | <p>The issue you are facing is <code>names</code> and <code>balances</code> have different lengths. When you call <code>acc_creation(name)</code> you add an extra element to <code>names</code> (<code>names.append(name)</code>), but not to <code>balance</code>, so there is a length mismatch. Something you could do is:</... | python|pandas|dictionary | 1 |
11,661 | 63,480,288 | A squarred variable is outside the index | <p>A variation of this post, without the detailed traceback, had been posted in the SO about two hours ago. This version contains the whole traceback.)</p>
<p>I am running StatsModels to get parameter estimates from ordinary least-squares (OLS). Data-processing and model-specific commands are shown below. When I use im... | <p>The syntax you used insists that a list of strings is a legal index into <code>eg</code>. If you <code>print(eg)</code>, you'll see that it has no such element. I think what you meant was to make a list of elements, each indexed by a single string.</p>
<pre><code>X = [
eg["p_c_inc_18"],
eg[&q... | python|pandas | 0 |
11,662 | 63,478,214 | Converting inconsistently formatted string dates to datetime in pandas | <p>I have a pandas dataframe in which the date information is a string with the month and year:</p>
<pre><code>date = ["JUN 17", "JULY 17", "AUG 18", "NOV 19"]
</code></pre>
<p>Note that the month is usually written as the 3 digit abbreviation, but is sometimes written as the ful... | <p>If you are not sure of the many spellings that can show up then a dictionary mapping would not work. Perhaps your best chance is to split and slice so you normalize into year and month columns and then build the date.</p>
<p>If <code>date</code> is a list as in your example.</p>
<pre><code>date = [d.split() for d in... | python|pandas|datetime | 1 |
11,663 | 63,603,160 | Output folder name to a column in dataframe? | <pre><code>source_files = sorted(Path('path/folder/subfolder1').glob('**/*.csv'))
dataframes = []
for file in source_files:
df = pd.read_csv(file, names=['date', 'cost', 'percent'])
df['Instance Number'] = file.name[:-4]
df['Source'] = folder.name
dataframes.append(df)
all = pd.concat(dataframes)
all... | <p>Try this:</p>
<pre><code>os.path.basename(os.path.dirname(file))
</code></pre>
<p><code>os.path.dirname(file)</code> returns the directory name of the file. <code>os.path.basename</code> returns a string value which represents the base name of the specified path.</p> | python|pandas|dataframe|csv | 0 |
11,664 | 21,593,376 | Printing matrix with numpy, python | <p>I just want to return a matrix. What am I missing?</p>
<pre><code>import numpy
print matrix([[0,1],[1,1]])
</code></pre>
<p>I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "fib.py", line 2, in <module>
print matrix([[0,1],[1,1]])
NameError: name 'matrix' is not def... | <pre><code>print numpy.matrix([[0, 1], [1, 1]])
</code></pre>
<p><code>matrix</code> is defined in the <code>numpy</code> module. <code>import</code> won't dump the contents of the module into the current namespace; you need to refer to <code>numpy.whatever_thing_you_want_from_the_module</code>.</p> | python|numpy|matrix | 0 |
11,665 | 24,807,644 | Pandas lookup values from different columns | <p>I'm looking for the best way of solving the following problem in Pandas. Given a dataframe <code>df</code>, e.g.</p>
<pre><code>import pandas as pd
dt = pd.date_range('1/1/2014', periods=10, freq='H')
df = pd.DataFrame({'A':[0.,0.,0.,1.,0.,0.,1.,0.,0.,0.],'B':[0.,0.,0.,0.,1.,0.,0.,0.,0.,1.]},index=dt)
df
... | <p>Here's one idea - there may be something better.</p>
<p>Populate a a column <code>C</code> with index values where <code>A</code> is 1.</p>
<pre><code>df['C'] = np.where(df['A'] == 1, df.index, '')
</code></pre>
<p>Forward fill the missing values, so it represents that last time <code>A</code> was one.</p>
<pre>... | python|pandas | 1 |
11,666 | 24,922,663 | Assigning a value to a single row for a Pandas DataFrame column | <p>I am trying to reassign a value in a single row of a column in a Pandas DataFrame.</p>
<pre><code>import pandas as pd
import numpy as np
</code></pre>
<p>Here's the DataFrame:</p>
<pre><code>test_df = pd.DataFrame({'range_total' : [3000,3000,3000,3000,3000,3000,0,2000,2000,1000,1000,1000,1000,1000,1000],
'hig... | <p>Sometimes you can get copy of (part of) original dataframe <code>test_df</code>.</p>
<p>Especially if you select elements using <code>[...][...]</code></p>
<p>So you changed one value in copy, not in oryginal <code>test_df</code></p>
<p>Try for example this:</p>
<pre><code>test_df["dist_num"].ix(test_df.high_bo... | python|pandas | 1 |
11,667 | 24,641,662 | add rows to groups in pandas dataframe | <p>I've got a pandas dataframe <code>df</code>. Created like this:</p>
<pre><code>a = np.array([0,0,0,1,1,1,2,2,2]).T
bcd = np.array([np.arange(1,10)]*3).T
df = pd.DataFrame(bcd, columns=["b","c","d"])
df["a"] = a
</code></pre>
<p>Looks like this:</p>
<pre><code> b c d a
0 1 1 1 0
1 2 2 ... | <p>What you want to do is not really an insert operation, as the data structure behind the <code>DataFrame</code> does not allow simple inserting. So, in essence, you will have to build a new <code>DataFrame</code> from the pieces of your old <code>DataFrame</code>.</p>
<p>So, your code should:</p>
<ol>
<li>Create a ... | python|pandas|group-by|dataframe | 4 |
11,668 | 53,769,189 | Rearrange rows of Dataframe alternatively | <p>I have a dataframe looks like this:</p>
<pre><code>df = pd.DataFrame({'col1': [i+1 for i in range(10)] + [-i-1 for i in range(10)],
'col2': ['random string'] *20})
print(df)
col1 col2
0 1 random string
1 2 random string
2 3 random string
3 4 random string
4 ... | <p>Sort after create helper key with <code>abs</code> </p>
<pre><code>newdf=df.assign(key=df.col1.abs()).sort_values('key').drop('key',1)
newdf
Out[60]:
col1 col2
0 1 random string
10 -1 random string
1 2 random string
11 -2 random string
2 3 random string
12 -3 random stri... | python|pandas|sorting|dataframe|indexing | 2 |
11,669 | 53,780,270 | Pythonic way to fill rows with date range | <p>I am working on a problem statement that requires me to fill the rows of missing dates (i.e dates in between two dates in columns of a pandas dataframe). Please see the example below. I am using Pandas for my current approach (mentioned below).</p>
<p><strong>Input Data Example (which has around 25000 rows)</strong... | <p>It looks to me like the best tool to use here is <code>PeriodIndex</code> (to generate the months and years between dates).</p>
<p>However, PeriodIndex can only operate on one row at a time. So, if we are going
to use PeriodIndex, every row has to be processed individually. That
unfortunately means looping throug... | python|python-3.x|pandas|date|dataframe | 8 |
11,670 | 72,067,160 | Pandas Randomly Data Choosing | <p>I'm a beginner in Pandas. I have a data file containing 10000 different information of users. This data contain 5 columns and 10000 rows. One of these columns is the district of the users and it divides users according to their living place(It defines just 7 different locations and in each of locations some number o... | <p>You can also <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.sample.html" rel="nofollow noreferrer">sample from groups generated with <code>groupby</code></a>:</p>
<pre><code>df.groupby('district').sample(n=5)
</code></pre>
<p>To restrict the sampling to those districts you... | python|pandas|database|dataframe|numpy | 1 |
11,671 | 71,957,962 | str.replace with special character "(*)" | <p>I have some column s in a dataframe with (*) on some of the data headers. When I do</p>
<pre><code>data.columns = data.columns.str.replace('(*)','')
</code></pre>
<p>I get the following error.</p>
<pre><code> File "C:\Users\ED397JT\Anaconda3\lib\site-packages\pandas\core\strings\object_array.py", line 156... | <p>str.replace takes a regular expression and * is a metacharacter it is trying to interpret. Try escaping it like so:</p>
<pre><code>data.columns.str.replace('(\*)', '')
</code></pre>
<p>or indicate that you aren't using regex:</p>
<pre><code>data.columns.str.replace('(*)', '', regex=False)
</code></pre> | python|pandas | 1 |
11,672 | 71,912,607 | cannot import name 'BatchNormalization' from 'keras.layers.normalization' | <p>I'm learning ObjectDetection from <a href="https://www.javatpoint.com/object-recognition-using-python" rel="nofollow noreferrer">this website</a></p>
<p>I have installed ImageAI,Tensorflow and Keras.</p>
<p>Then when I run this in python</p>
<pre><code> from imageai.Detection import ObjectDetection
</code></pre>
... | <p>Tensorflow v2.8.0 support tf.keras.layers.BatchNormalization()</p>
<pre><code>import tensorflow as tf
tf.keras.layers.BatchNormalization()
</code></pre> | python|tensorflow|keras|batch-normalization | 0 |
11,673 | 22,382,023 | Shrink down row numbers in a Pandas Dataframe when removing rows in Python | <p>Essentially this is the same question as in this link:<a href="https://stackoverflow.com/questions/12361471/how-to-automatically-shrink-down-row-numbers-in-r-data-frame-when-removing-rows">How to automatically shrink down row numbers in R data frame when removing rows in R</a>. However, I want to do this with a pand... | <p>What you call "row number" is part of the index in pandas-speak, in this case a integer index. You can rebuild the index using </p>
<pre><code>df = df.reset_index(drop=True)
</code></pre> | python|pandas|dataframe | 2 |
11,674 | 22,003,242 | adding columns in numpy - still confused | <p>I know there have been plenty of questions asked and answered concerning columns in <code>NumPy</code>, but I'm still stuck. Unfortunately, <code>np.append</code> isn't working for me as it says that there is no module.</p>
<p>I'm working with the <code>boston</code> dataset which has the median values stored separ... | <p>Firstly, you should set axis=1, not 0.
You are attempting to add a column, not row. That is why numpy is giving the error about the different number of dimensions for the arrays.</p>
<pre><code>import numpy as np
A = np.append(boston.data, boston.target.reshape(-1, 1), axis=1)
</code></pre>
<p>Another way to add a... | arrays|numpy|jupyter-notebook | 0 |
11,675 | 4,152,817 | *.npy reader for windows | <p>Does exist any *.npy files reader/visualizer ? (for Windows)</p> | <p>There is a IDE for scientific python call <a href="http://code.google.com/p/spyderlib/" rel="nofollow">spyder</a>. It has the ability to import all the data from a .npy file into the workspace. All the variables in the workspace are shown in a nice user interface, so this may do what you need. </p> | python|numpy | 4 |
11,676 | 55,315,677 | How to calculate the percentage for a dataset by using groupby function | <p>I am the new beginner of using Python and I have some questions about how to use python to calculate the percentage for the certain of the columns by using groupby function.
I would be grateful if you could help me to solve this problem.
Thanks a lot!!!</p>
<p>I already tried the code like this:</p>
<pre><code>i... | <p>This should do it:</p>
<pre><code>map_key = dataset.groupby(['Fruit_Types']).size().to_dict()
df = dataset.dropna().groupby(['Fruit_Types', 'Location']).size()
df = df.reset_index().rename(columns={0:'Count'})
df['Total'] = df['Fruit_Types'].map(map_key)
df['Percentage'] = df.Count / df.Total
df = df.set_index(['F... | python|pandas | 0 |
11,677 | 56,776,919 | Add 95% confidence intervals as error bars to pandas bar plot | <p>I want to add 95% confidence interval error bars to a pandas bar plot, like <a href="https://stackoverflow.com/questions/42985553/calculate-and-plot-95-confidence-interval-for-a-given-dataframe">here</a>. This is what my data looks like:</p>
<p><code>ciRatings.head(20)</code></p>
<pre><code> ... | <p>The given link suggests:</p>
<pre><code>fig, ax = plt.subplots(figsize=(12,8))
(df['mean'].unstack(level=1)
.plot.bar(yerr=df['std'].unstack(level=1) * 1.96,
ax=ax, capsize=4)
)
plt.show()
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/Igv5c.png" rel="nofollow n... | python|pandas|plot|confidence-interval|errorbar | 1 |
11,678 | 56,481,716 | Slow working converting DataFrame to dict | <p>I am doing batching process. From dataset like: </p>
<p><strong>data</strong> = </p>
<pre><code>[
'{"CustomerId": "f796bce5-f416-502c-a1c5-6e7c57a3676d", "Email": "fname@emailreaction.com", "FirstName": "fname", "Surname": "lname", "DateOfBirth": "1970-02-01"}',
'{"CustomerId": "f796bce5-f416-502c-... | <p>You don't need pandas for so simple a groupby:</p>
<pre class="lang-py prettyprint-override"><code>from collections import defaultdict
def get_batched_list_by_id_no_pandas(data, batch_by="CustomerId"):
dicts = json.loads("[" +', '.join(data) + "]")
# Create a defaultdict of lists
temp = defaultdict(lis... | pandas|python-3.7 | 0 |
11,679 | 56,522,602 | When I tried to run tensorflow, I noticed that the GPU was not being used, though I was using tensorflow GPU version. Any work around for this? | <p>My installation had no issues, but the warning that</p>
<p>"This graphics driver could not find compatible graphics hardware. You may continue installation. but you may not be able to run CUDA applications with this driver. This may occur with graphics hardware that is newer than this toolkit. In that case, it is s... | <p>I would strongly recommend that you use Anaconda distribution. Once Anaconda is installed you can create a new environment where Tensorflow with GPU support will be installed by typing:</p>
<pre><code>conda create -n tensorflow_gpuenv tensorflow-gpu # this installs it
conda activate tensorflow_gpuenv # this switche... | python|tensorflow|nvidia | 0 |
11,680 | 56,782,394 | Truncate decimal places of values within a pandas df | <p>I can <code>truncate</code> individual floats using the <code>truncate</code> function in <code>math</code>. But when trying to pass the same function to a <code>pandas</code> <code>df</code> column I'm getting an error.</p>
<pre><code>import math
import pandas as pd
X = 1.1236
X = math.trunc(1000 * X) / 1000;
#... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html" rel="noreferrer"><code>applymap</code></a></p>
<pre><code>trunc = lambda x: math.trunc(1000 * x) / 1000;
df.applymap(trunc)
</code></pre> | python|pandas|math|truncate | 7 |
11,681 | 56,612,667 | having problemns while using dask map_partitions with string matching algorithm | <p>I'm having some probems apllying a text search algorithm with parallelized dask insfrastructure. </p>
<p>I'm tryng to find the best match for 40,000 stirngs in a series object against a 4000 string list.</p>
<p>I could have done it using pandas.apply but it's to time expensive, so i decided try parallelization wit... | <p>Doing the MCVE I realized that it was a naive syntax problem: I can't use the map_partitions on a dask dataframe without specifying the column that im using even if there is only one column. So I should had used sd[0].map_partitions insted of sd.map_partitions</p> | python|pandas|search|dask|fuzzywuzzy | 0 |
11,682 | 56,707,084 | Pandas: replace values in one dataframe with values from another dataframe based on two columns | <p>I have two dataframes:</p>
<pre><code>d1 = {'id_': ['a','b','c','d'],
'year':['2018','2019','2017','2019']}
d2 = {'id_': ['a','c','e'],
'year':['2015',NaN,'2012']}
test1 = pd.DataFrame(d1)
test2 = pd.DataFrame(d2)
id_ year
0 a 2018
1 b 2019
2 c 2017
3 d 2019
id_ year
0 a 201... | <p>Using <code>update</code> </p>
<pre><code>test1=test1.set_index('id_')
test1.update(test2.set_index('id_'))
test1.reset_index(inplace=True)
test1
Out[582]:
id_ year
0 a 2015
1 b 2019
2 c 2017
3 d 2019
</code></pre> | python|python-3.x|pandas | 4 |
11,683 | 26,014,375 | Fourier coefficients for NFFT - non uniform fast Fourier transform? | <p>I am trying to use the package pynfft in python 2.7 to do the non-uniform fast Fourier transform (nfft). I have learnt python for only two months, so I have some difficulties.</p>
<p>This is my code:</p>
<pre><code>import numpy as np
from pynfft.nfft import NFFT
#loading data, 104 lines
t_diff, x_diff = np.loadtx... | <p>Here is a working example, taken from <a href="https://github.com/ghisvail/pyNFFT/issues/26" rel="nofollow noreferrer">here</a>:</p>
<p>First we define the function we want to reconstruct, which is the sum of four harmonics:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
np.random.seed(12345)
... | python-2.7|numpy|fft | 0 |
11,684 | 66,933,239 | How to pair line numbers making surfaces in a regular grid | <p>I have a bunch of points in 3D space that are connected by lines. I want to create 4-sided surfaces by detecting which lines can create such surfaces.</p>
<p>I have coordinates of my points, numbered lines, and also the point pairs which create lines. I uploaded a drawing to visualize it:</p>
<p><a href="https://i.s... | <p>As the comments show, there are a lot of things that need clarification, so my answer could still not be what you need.</p>
<p>I am making several assumptions about the problem:</p>
<ul>
<li>The z-coordinate is irrelevant for locating the squares</li>
<li>There are only horizontal lines and vertical lines</li>
<li>T... | python|list|algorithm|numpy|geometry | 2 |
11,685 | 47,308,984 | How to use Python with pandas exporting Data to GeoJSON for Google Map | <p>I am doing a project about web crawler. <br>
I will got some point location include (Name, longitude, latitude) <br>
Then point all of them in Google Map(use Google Map API) <br></p>
<hr>
<p>First <br>
I got some data from the website API. -- (300points locaiton) <br>
Then use Python pandas DataFrame to export Jso... | <blockquote>
<p>How can I change my json file to the GeoJson?</p>
</blockquote>
<p><strong>You could use <a href="https://pypi.python.org/pypi/geojson" rel="noreferrer">geojson</a></strong></p>
<p>Here's an example:</p>
<p>Import:</p>
<pre><code>import json
import pandas as pd
from geojson import Feature, Feature... | python|json|pandas|google-maps | 13 |
11,686 | 47,486,898 | pandas - load matrix style csv directly to pivottable object | <p>I have serialized a <code>pivotTable</code> object using pandas <code>.to_csv</code> function. now i want to load it back to a <code>pivotTable</code> object. </p>
<p>The CSV looks something like this, the first column and row are id's</p>
<pre><code> 49033 49967 50221 52301
41619
41665... | <p>use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_fwf.html" rel="nofollow noreferrer">pd.read_fwf()</a> if you have fixed width format file.</p>
<p>Demo:</p>
<pre><code>In [28]: fn = r'D:\temp\.data\1.fwf'
In [29]: pd.read_fwf(fn).fillna('')
Out[29]:
Unnamed: 0 49033 49967 50221... | python|pandas|csv|numpy | 2 |
11,687 | 68,320,914 | np.mean(phDF.ram) raise eror | <pre><code>phoneinfo=np.array([['galaxy s8','android',64,4,140,'samsung',6],['lumia','windows',32,3,150,'microsoft',6],
['xperia l1','android',16,2,180,'sony',5],['iphone7','ios',128,2,138,'apple',4],
['u ultra','android',64,4,170,'htc',5],['galaxy s5','android',16,2,145,'samsung... | <p>As the dtype of your <code>ram</code> column is in <code>object</code> type, <code>np.median</code> can't work on it.</p>
<pre><code>phDF.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 9 entries, 1 to 9
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ ------------... | python|pandas | 0 |
11,688 | 68,114,631 | Python Pandas Dataframe challenge: how do I avoid Iterrows() for this scenario? | <p><strong>Context</strong></p>
<p>I've heard it often said "you should avoid iterating through a Dataframe", or "using iterrows is bad/slow/etc." or "there is nothing you can do with iterrows that you can't do with apply/applymap/map". I'm trying to shed the habit of using iterrows but ha... | <p>Looks like what you want is a groupby into list?</p>
<pre><code>In [1]:
...: import pandas as pd
...:
...:
...: df = pd.DataFrame(
...: {
...: "JobNumber": [1,1,3,4,5,5],
...: "RunNumber": [1,2,3,4,5,6],
...: }
...: )
...:
...: df.groupby('... | python|python-3.x|pandas|dataframe | 1 |
11,689 | 59,210,117 | Why is a copy of a pandas object altering one column on the original object? (Slice copy) | <p>As I understand, a copy by slicing copies the upper levels of a structure, but not the lower ones (I'm not sure when).</p>
<p>However, in this case I make a copy by slicing and, when editing two columns of the copy, one column of the original is altered, but the other is not.</p>
<p>How is it possible? Why one col... | <blockquote>
<p>As I understand, a copy by slicing copies the upper levels of a structure, but not the lower ones.</p>
</blockquote>
<p>This is valid for Python lists. Slicing creates shallow copies. </p>
<pre><code>In [44]: lst = [[1, 2], 3, 4]
In [45]: lst2 =... | python-3.x|pandas|copy | 1 |
11,690 | 59,344,664 | Can't install Rasa on Ubuntu 18.04 + Python 3.7.5? | <p>I have succeed to install Rasa NLU on my Win 10 with python 3.7 but couldn't do this on Ubuntu 18.04.
Please help.</p>
<p>Here is the error I get:</p>
<pre><code>pip3 install rasa-x --extra-index-url https://pypi.rasa.com/simple
</code></pre>
<blockquote>
<p>Could not find a version that satisfies the requireme... | <p><strong>I had followed these following steps and it's working fine for me for ubuntu 18.04 + Python3</strong></p>
<p>Firstly create directory name of your choice and get inside of it</p>
<pre><code>mkdir rasaprojects #directory name of your choice in place of rasaprojects
cd rasaprojects #get inside that direct... | tensorflow|ubuntu-18.04|rasa|rasa-nlu|rasa-x | 2 |
11,691 | 59,161,453 | How to install PyTorch on Python 3.7 / Windows 10 with pip | <p>I am trying to install <strong>PyTorch 1.3</strong> using pip :</p>
<pre><code>pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html
</code></pre>
<p>I got the command line from this page :
<a href="https://pytorch.org/get-started/locally/#start-locally" rel="no... | <p>You error is being triggered because the version 1.3.1+cpu doesn't exist.</p>
<p>If you go to pytorch.org you will be able to select a version of pytorch and your OS, where it will give you a command to install pyTorch correctly, for Python 3.7 and PIP use the following:</p>
<pre><code>pip3 install --find-links ht... | python|pip|pytorch | 1 |
11,692 | 59,072,057 | Filter a Panda Series By Date Or Anonymous Function | <p>I have an object of type: 'pandas.core.series.Series'</p>
<p>That looks like this:</p>
<pre><code>1997-09-10 0.000000
1997-09-11 0.000000
1997-09-12 0.000000
...
2019-10-15 348153.430102
2019-10-16 348153.265395
2019-10-17 348153.100689
Freq: B, Length: 5767... | <p>Use:</p>
<pre><code>rng = pd.date_range('2004-12-28', periods=10)
s = pd.Series( range(10), index=rng)
print (s)
2004-12-28 0
2004-12-29 1
2004-12-30 2
2004-12-31 3
2005-01-01 4
2005-01-02 5
2005-01-03 6
2005-01-04 7
2005-01-05 8
2005-01-06 9
Freq: D, dtype: int64
</code></pre>
<p>U... | pandas|numpy|matplotlib | 1 |
11,693 | 59,310,131 | Contrast stretching in OpenCV or Numpy with limits and blanking | <p>I've been doing my due diligence on contrast stretching, but have a special case.</p>
<p>If you have an image that has pixel values from 3 to 248, but you only want to stretch, say, pixels of range 105 to 135, to 10 to 255, and zero out whatever is below 10, what might be the most efficient way to do this? </p>
<p... | <p>You certainly don't need to do this in so many lines. You also don't need to use all these numpy functions on your array if it's already a numpy array. Using operators like + and - already imply array addition and subtraction with a scalar. Try this:</p>
<pre><code># this scales the image values between 105 and 135... | python|numpy|opencv | 1 |
11,694 | 59,371,056 | Efficient way to pivot table dynamically | <p>I have a table named monthly_agg which contains monthly aggregated data.</p>
<pre><code>+------------+-----+----------+-----------+---------------+--------------+-------------+----------+---------+
| yyyy_mm_dd | id | app | ex_status | active_status | active_count | active_base | ex_count | ex_base |
+-------... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a> for percentages and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.piv... | python|python-3.x|pandas | 1 |
11,695 | 59,136,101 | How to do numpy logical_and with a margin? | <p>I have two numpy vector arrays, one contains binary values so either 1 or 0 and the other float values so anything in between 0 and 1. </p>
<p>I want to use the <code>numpy.logical_and</code> operator and have it return true if the binary value is in the range of the float plus or minus 0.2. So i.e. a float of 0.1 ... | <p>I think what you want is <code>np.isclose</code>. In this case implementation would be:</p>
<pre><code>bin_arr = np.random.randint(2, size = 100)
float_arr = np.random.rand(100)
out = np.isclose(bin_arr.astype(float), float_arr, atol = .2)
</code></pre>
<p>Note that while <code>logical_and</code> is a <a href="ht... | python|numpy|multidimensional-array|vector|data-science | 1 |
11,696 | 59,326,551 | Cannot pickle Tensorflow object in Python - TypeError: can't pickle _thread._local objects | <p>I want to pickle the history object after running a keras fit on tensorflow. But I am getting an error.</p>
<pre><code>import gzip
import numpy as np
import os
import pickle
import tensorflow as tf
from tensorflow import keras
with gzip.open('mnist.pkl.gz', 'rb') as f:
train_set, test_set = pickle.load(f, enc... | <p>As Karl suggested, the history object cannot be pickled. But it's dictionary can:</p>
<pre><code>with open('models/basic_history.pickle', 'wb') as f:
pickle.dump(history.history, f)
</code></pre> | python|tensorflow|pickle | 6 |
11,697 | 44,979,467 | Dimensions must be equal, but are 1 and 128 for 'SparseSoftmaxCrossEntropyWithLogits | <p>I tried to read an images as png format using conventional neural network in tensorflow. I faced a problem that I cannot deal with label in read data step, so, it gives me an error.</p>
<p>First thing I thought the problem is happened when I create <em>batch queue and shuffle</em>.
which was the problem in <strong>... | <p>I can't view your code (link doesn't work or the dropbox file isn't public) but based on the error, your labels are the wrong shape. For SparseSoftmaxCrossEntropyWithLogits the labels should be shaped [None,], where None is the batch dimension - i.e. your labels should be integers, not one-hot encoded vectors. </p> | image-processing|machine-learning|tensorflow|deep-learning | 0 |
11,698 | 44,879,577 | How to save and load tensor flow model after using tf.contrib.learn.LinearClassifier? | <p>Here is the code: <a href="https://github.com/tensorflow/tensorflow/blob/r1.2/tensorflow/examples/tutorials/input_fn/boston.py" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/r1.2/tensorflow/examples/tutorials/input_fn/boston.py</a></p>
<p>After model is saved in this part: </p>
<pre><code... | <p>Lets say there are two functions <code>train()</code> and <code>test()</code> and your model is <code>AnyClassifier</code>. In train you call <code>AnyClassifier(..., model_dir)</code> and then call the <code>fit()</code> method. In your test case you call <code>AnyClassifier(..., model_dir)</code> and then can call... | machine-learning|tensorflow | 1 |
11,699 | 56,975,783 | pandas: write dataframe to excel file *object* (not file)? | <p>I have a dataframe that I want to convert to excel file, and return it using HTTP. Dataframe's <code>to_excel</code> method accepts either a path, or an <code>ExcelWriter</code>, which, in turn, refers to a path.</p>
<p>Is there any way to convert the dataframe to a file object, without writing it to disk?</p> | <p>This can be done using the <a href="https://docs.python.org/3/library/io.html#io.BytesIO" rel="noreferrer"><code>BytesIO</code></a> Object in the standard library:</p>
<pre><code>import pandas
from io import BytesIO
# Create Random Data for example
cols = ["col1", "col2"]
df = pandas.DataFrame.from_records([{k: 0.... | python|pandas | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.