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 |
|---|---|---|---|---|---|---|
14,700 | 65,908,760 | How to select top n columns from list of dataframe in pandas? | <p>I have time-series data collected based on a weekly basis. I need to split given time series data into the specific year and find out top n columns for each sub dataframe. To do so, I tried to use <code>nlargest</code> but not getting the expected sub dataframe after filtering out the columns based on row sum. Can a... | <p>Using a dictionary of dataframes by year:</p>
<pre><code>d = {}
for g, n in df_new.groupby(level=0):
d[g] = n.loc[:,n.sum().rank(ascending=False,method='min')<5]
print(d[2018])
print(d[2019])
</code></pre>
<p>Still pretty unsure what exactly you want:</p>
<pre><code>df_new.loc[:,(df_new.groupby(level=0).... | python|pandas | 3 |
14,701 | 63,416,594 | Pandas sort three list columns in descending order with reference to one column | <p>I have a pandas dataframe like this:</p>
<pre><code>df =
userid item_id label score
1 [1, 2, 3] [0, 0, 1] [0.2, 0.3, 0.5]
... ... ...
</code></pre>
<p><code>item_id</code>, <code> label</c... | <p>try <code>sort_values</code> and <code>groupby</code> to convert to list again</p>
<pre><code>(df_original.sort_values(['userid', 'score'], ascending=[True,False])
.groupby('userid').agg(list)
.reset_index()
)
</code></pre>
<h2>Edit</h2>
<p>As <a href="https://stackoverflow.com/users/9274732/... | python-3.x|pandas|list|columnsorting | 2 |
14,702 | 63,493,051 | Normalize a dataframe column containing JSON | <p>I've got the following data set:</p>
<pre><code>Col 1 | Col 2 | JSONBlob
0 |A |{"$type":"XYZ, X.Domain","CategoryList":"PC","ListId":"GroceryStore","FactorDescription":"Groceries",
</code... | <p>Parse the JSON separately then join to the original frame:</p>
<pre><code>blobs = []
for index, row in df.iterrows():
b = row['JSONBlob']
blobs.append(pd.json_normalize(b))
blobs = pd.concat(blobs)
df = df.join(blobs)
</code></pre> | json|pandas | 0 |
14,703 | 63,583,799 | Using the last valid data index in one Dataframe to select data in another Dataframe | <h2>I want to find the last valid index of the first Dataframe, and use it to index the second Dataframe.</h2>
<p>So, suppose I have the following Dataframe (df1):</p>
<pre><code> Site 1 Site 2 Site 3 Site 4 Site 5 Site 6
Date
2000-01-01 13.0 2... | <p>This might be a bit more idiomatic:</p>
<pre><code>df2[df.notna()]
</code></pre>
<p>or even</p>
<pre><code>df2.where(df.notna())
</code></pre>
<p>Note that in these cases (and <code>df1*0 + df2</code>), the operations are done for matching index values of <code>df</code> and <code>df2</code>. For example, <code>df2... | python|python-3.x|pandas|numpy|indexing | 2 |
14,704 | 30,250,164 | change the format of a numpy array with no loops | <p>I have a numpy array with shape <code>a.shape = (1,k*d)</code>and i want to transform it to a numpy array with shape <code>b.shape = (k*d,k)</code> in each column</p>
<p><code>b[i,j] = a[i] if j<i+1</code></p>
<p><code>b[i,j] = 0 if not</code> </p>
<p>for example:</p>
<pre class="lang-py prettyprint-override"... | <p>This reproduces your example. It can be generalized to other <code>k</code> and <code>d</code></p>
<pre><code>In [12]: a=np.arange(6)
In [13]: b=np.zeros((6,3))
In [14]: b[np.arange(6),np.arange(3).repeat(2)]=a
In [15]: b
Out[15]:
array([[ 0., 0., 0.],
[ 1., 0., 0.],
[ 0., 2., 0.],
... | python|numpy|matrix|vectorization | 4 |
14,705 | 53,409,843 | Why am I getting a score of 0.0 when finding the score of test data using Gaussian NB classifier? | <p>I have two different data sets. One for training my classifier and the other one is for testing. Both the datasets are text files with two columns separated by a ",". FIrst column (numbers) is for the independent variable (group) and the second column is for the dependent variable.</p>
<p><strong>Training data set... | <p>First, the above data samples dont show how many classes are there in it. You need to describe more about it. </p>
<p>Secondly, you are calling <code>le.fit_transform</code> again on test data which will forget all the training samples mappings from strings to numbers. The <code>LabelEncoder</code> le will start en... | python-3.x|pandas|machine-learning|scikit-learn|gaussian | 0 |
14,706 | 53,391,412 | Keras: IndexError: tuple index out of range - Conv2D | <p>I'm new in Keras and Tensorflow. I am trying to run some specific code based on Keras and Tensorflow. In that code, I prepared dataset from tfrecordes files and reshape it with <code>tf.reshape(image, [32, 32, 3])</code>, in my model, I need to apply a Conv2D layer on this image output, I using Keras, in my code bel... | <p>I think you need a 9 * 9 kernel. Change <code>kernel_size=9</code> to <code>kernel_size=( 9 , 9 )</code>
Edited code line :</p>
<pre><code>conv1 = k.layers.Conv2D(filters = 256, kernel_size = ( 9 , 9 ), strides=1,padding='valid', activation='relu', name='conv1')(x)
</code></pre> | python|tensorflow|keras | 0 |
14,707 | 72,055,149 | Python find indices of subarrays which are continuous and increasing with difference of 1 | <p>The input is always strictly increasing. I could write this with a for loop and lots of if-else conditions, but is there some simple way? Here is an example:</p>
<pre class="lang-py prettyprint-override"><code>input: [2,3,4,6,8,9]
output: [[0,1,2],[4,5]]
input: [1,2,3,4]
output: [[0,1,2,3]]
input: [0,1,2,4,6,7,8,1... | <p>This can accept any iterable sequence:</p>
<pre><code>from itertools import pairwise
def get_mergable_indices(sent_order):
result = []
curr = []
for idx, (i, j) in enumerate(pairwise(sent_order)):
if j - i == 1:
curr.append(idx)
elif curr:
curr.append(idx)
... | python|arrays|numpy | 1 |
14,708 | 18,793,771 | How can I tell whether a numpy boolean array contains only a single block of `True`s? | <p>If I have a numpy array containing booleans, say the output of some math comparison, what's the best way of determining whether that array contains only a single contiguous block of <code>True</code>s, e.g.</p>
<pre><code>array([False, False, False, True, True, True, False, False, False], dtype=bool)
</code></pre... | <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html" rel="noreferrer"><code>numpy.diff</code></a> is useful in this case. You can count the number of -1's in the <code>diff</code>ed array.</p>
<p>Note, you'd also need to check the last element -- if it's True, there wouldn't be a -1 in the ... | python|numpy | 6 |
14,709 | 19,279,229 | pandas - pivot_table with non-numeric values? (DataError: No numeric types to aggregate) | <p>I'm trying to do a pivot of a table containing strings as results.</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'index' : range(8),
'variable1' : ["A","A","B","B","A","B","B","A"],
'variable2' : ["a","b","a","b","a","b","a","b"],
'variable3' : ["x","x","x","y","y","y","x","y"],
'result': ["on","off","off... | <p>My original reply was based on Pandas 0.14.1, and since then, many things changed in the pivot_table function (rows --> index, cols --> columns... )</p>
<p>Additionally, it appears that the original lambda trick I posted no longer works on Pandas 0.18. You have to provide a reducing function (even if it is min,... | python|pandas|pivot-table|dataframe | 26 |
14,710 | 19,062,926 | Plotting subplots with secondary continuous y-axis across all subplots | <p>I have a numpy arrays of temperature, wind speed, heat flux etc. Each of these arrays is assigned to its own subplot. The snow depth I would like to be plotted on the combined area of the subplots. As if the second y-axis is of one plot.</p>
<p>In the attached image is what I would like to create <img src="https://... | <p>You can use <code>twinx()</code> to create a second y-axis that shares the same x-axis</p>
<pre><code>ax1 = axes()
ax2 = ax1.twinx()
x = np.arange(100)
y1 = np.random.rand(100)
y2 = np.random.rand(100)
ax1.plot(x,y1,'-r')
ax1.set_ylim(-1,1)
ax2.fill_between(x,0,y2,color='b',alpha=0.5)
ax2.set_ylim(0,2)
ax1.set_y... | python|numpy|matplotlib|plot|subplot | 1 |
14,711 | 4,080,622 | Can you change the way numpy prints arrays? | <p>I have a 3d, 3x3x3 array of integers. Numpy will print these as a block of the first 3x3, then below it the 2nd 3x3, then below that the 3rd 3x3. </p>
<p>If I wanted to print these 3 3x3 blocks BESIDE each other, rather than underneath each other, how would I tell numpy to print differently?</p> | <pre><code>import numpy as np
arr=np.random.random((3,3,3))
print(arr)
# [[[ 0.05733376 0.00646892 0.96180769]
# [ 0.11560363 0.56058966 0.83942817]
# [ 0.5520361 0.17355794 0.87699437]]
# [[ 0.90999361 0.03036473 0.5064459 ]
# [ 0.76169531 0.48234618 0.56884999]
# [ 0.93220906 0.9460365 ... | python|numpy | 3 |
14,712 | 55,238,675 | Sklearn train_test_split() stratify strange behaviour with python 3.7 | <p>I used a 70-30 balanced dataset and try to split it in train / test with a stratification using train_test_split sklearn function.
It works as expected in python 3.5 but not really in 3.7. </p>
<p>There is the code I'm using to reproduce :</p>
<pre><code>import numpy as np
from sklearn.model_selection import trai... | <p>This kind of issue can be related to processor architecture.
Please check than both of your Python version have the same architecture (32bits or 64bits).</p> | python|python-3.x|numpy|scikit-learn | 0 |
14,713 | 55,316,169 | Change specific values within a column based on keyword | <p>I have the following column in a dataframe:</p>
<pre><code>'Marital-status'
'Never-married'
'Married-civ-spouse'
'Separated'
'Married-army-spouse'
'Divorced'
'Widowed'
</code></pre>
<p>I want to just lump together obs that are separated or divorced and married regardless of what comes after. (ie. I want 'Married-... | <p>You can split the cells on <code>'-'</code> and take the first part. First define a mask so you don't mess up other rows like <code>'Never-married'</code>. </p>
<pre><code>m = df['Marital-status'].str.contains('Married')
df.loc[m, 'Marital-status'] = df.loc[m, 'Marital-status'].str.split('-').str[0]
df['Marital-sta... | python|pandas|numpy | 2 |
14,714 | 55,217,412 | How to I convert discrete data into interval in python? | <p>I have input data below. And I would like to convert this data into output data. I am using python language and numpy and pandas. Please help me out to solve it.</p>
<p><strong>Input data:</strong></p>
<pre><code> Product year Total sale
0 Aviation Turbine Fuel 2000 63131
1... | <p>Try with <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.cut.html" rel="nofollow noreferrer"><code>pd.cut()</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>df.groupby()</code></a></p>
<pre><c... | python|pandas|numpy | 4 |
14,715 | 56,486,585 | How to fix trainer package not found in AI Platform GPU-distributed training job | <p>I'm attempting to train a Tensorflow Estimator on AI Platform. The model trains on local perfectly fine, albeit extremely slowly, but right when I try to run distributed-GPU training on AI Platform I run into this error:</p>
<pre><code>CommandException: No URLs matched: gs://path/.../trainer-0.1.tar.gz
</code></pre... | <p>I was actually able to fix my issue: it appears that if I don't set up a staging bucket then the model dir where checkpoints are stored will overwrite the trainer package before the worker replicas are able to download the trainer! I'm unsure how the checkpoints were even able to begin being stored when the worker r... | tensorflow|google-cloud-ml | 1 |
14,716 | 25,510,482 | Python Pandas Multiprocessing Apply | <p>I am wondering if there is a way to do a pandas dataframe apply function in parallel. I have looked around and haven't found anything. At least in theory I think it should be fairly simple to implement but haven't seen anything. This is practically the textbook definition of parallel after all.. Has anyone else trie... | <p>With multiprocessing, it's best to generate several large blocks of data, then re-assemble them to produce the final output. </p>
<h2>source</h2>
<pre><code>import multiprocessing
def worker(arg):
return arg*2
pool = multiprocessing.Pool()
# get list of pieces
res = pool.map(worker, [1,2,3])
pool.close()
p... | python|pandas|multiprocessing | 2 |
14,717 | 25,651,556 | Numpy multidimensional arrays and inverse accessing | <p>I have a numpy array with rank=4. Suppose it looks like this:</p>
<pre><code>np.shape(my_array)
(10,5,25,50)
</code></pre>
<p>I also have a list of 10 values, such as</p>
<pre><code>x = np.arange(10)
</code></pre>
<p>I would like to be able to plot <code>x</code> against the first axis of <code>my_array</code> f... | <p>Here is a simple example using broadcasting:</p>
<pre><code>y = randn(10,4)
x = arange(10)
plot(x[:,None],y)
</code></pre>
<p>I guess in your case you would have <code>x[:,None,None,None]</code>.</p> | python|arrays|numpy|multidimensional-array | 0 |
14,718 | 25,885,556 | python, dumping a pandas dataframe in a sql database | <p>What should be the best way to dump a pandas dataframe into a sql database?
Is it better to first convert the dataframe into a csv file then dump the csv file or write into the sql database line by line?</p> | <p>Check this:
<a href="http://pandas.pydata.org/pandas-docs/version/0.14.1/generated/pandas.DataFrame.to_sql.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/version/0.14.1/generated/pandas.DataFrame.to_sql.html</a>
The fastest way is you use it with sqlAlchemy and not with the legacy DBAPI2.</p> | python|sql|pandas|mysqldump | 0 |
14,719 | 26,349,116 | No binary operators for structured arrays in Numpy? | <p>Okay, so after going through the tutorials on numpy's structured arrays I am able to create some simple examples:</p>
<pre><code>from numpy import array, ones
names=['scalar', '1d-array', '2d-array']
formats=['float64', '(3,)float64', '(2,2)float64']
my_dtype = dict(names=names, formats=formats)
struct_array1 = one... | <p>On the <code>numpy</code> structured array doc pages, most of the examples involve mixed data types - floats, ints, and strings. On SO most of the structured array questions have to do with loading mixed data from CSV files. On the other hand, in your example it appears that the main purpose of the structure is to... | python|numpy|binary-operators|structured-array | 4 |
14,720 | 66,949,291 | Python Lookup - Mapping Dynamic Ranges (fast) | <p>This is an extension to a question I posted earlier: <a href="https://stackoverflow.com/questions/66947324/python-sum-lookup-dynamic-array-table-with-df-column">Python Sum lookup dynamic array table with df column</a></p>
<p>I'm currently investigating a way to efficiently map a decision variable to a dataframe. The... | <p>Here's how I would go about this, assuming your first DataFrame is called <code>df</code> and your second is <code>decision</code>:</p>
<pre><code>def map_func(x):
for i in range(len(decision)):
try:
if x < decision["ValueY"].iloc[i]:
return decision["Decisio... | python|pandas|numpy|bisect | 0 |
14,721 | 67,172,690 | Nested loops for comparing and grouping strings using fuzzywuzzy python | <p>I am struggling to make a faster code to group similar product names(column "prep") within same "person_id" and same "TNVED". So sample of my dataframe looks like this:
<a href="https://i.stack.imgur.com/vEvtw.png" rel="nofollow noreferrer">sample_of_dataframe</a></p>
<p>So I did dictio... | <p>You are using Fuzzywuzzy and since your suppressing warnings, I assume you are using the pure Python implementation. You should use <code>fuzzywuzzy[speedup]</code> or for even better performance <a href="https://github.com/maxbachmann/RapidFuzz" rel="nofollow noreferrer">RapidFuzz</a> (I am the author). in RapidFuz... | python|pandas|loops|dictionary|fuzzywuzzy | 0 |
14,722 | 67,072,660 | Tensorflow: how to retain file names in tf.data.Dataset from_generator? | <p>I am struggling with the following. I am creating a tf.data.Dataset using the from_generator method. It works great, but after prediction I would like to investigate which samples were misclassified and why. For that, I need to retrieve the file names in the same order they were fed to a model. How can I do it?</p>
... | <p>One possibility is to make your generator return the filename, and pass that as a debug input to your model.</p>
<h2>An end to end example.</h2>
<p>Lets train a simple Linear Regression, here is the definition of the model:</p>
<pre><code>model = tf.keras.models.Sequential([tf.keras.layers.Dense(1,input_shape=(1,))]... | python|tensorflow|dataset|generator|lazy-evaluation | 1 |
14,723 | 67,080,241 | Pandas unable to read SQL headers - Python | <p>I'm using the pyodbc driver and attempting to read an sql server database. The resulting dataframe has empty column headers like shown below</p>
<p><img src="https://i.stack.imgur.com/aW4pz.png" alt="screenshot of the ipython console" /></p>
<p>I've cast some fields to date / datetime type and those changes seem to ... | <p>When a bare column name is included in a SELECT statement its name is automatically used in the result set:</p>
<pre class="lang-none prettyprint-override"><code>1> SELECT create_date FROM sys.tables WHERE name='team';
2> go
create_date
-----------------------
2021-01-02 11:06:23.763
(1 rows affected)
</code>... | python|sql|pandas|pyodbc | 0 |
14,724 | 67,076,442 | Select mean of the values column wise | <p>I have a dataset in which I have 5 columns. Consider the below database:-</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">City</th>
<th style="text-align: center;">Vehicle</th>
<th style="text-align: center;">col3</th>
<th style="text-align: center;">col4</th>... | <p>Please try the following if you are to count on <code>col3</code> (but still grouped under <code>City</code>):</p>
<pre><code>df.groupby('City')['col3'].value_counts(normalize=True)
</code></pre>
<p>This will give you the desired relative portions (sum up to 1) instead of the real counts. You can repeat similarly fo... | pandas|data-science|data-analysis | 1 |
14,725 | 66,877,585 | Input values in a pandas Dataframe | <p>I'm trying to input some values in this dataframe:</p>
<p>I have a list of columns name:</p>
<pre><code>input: centro_oeste.columns
output: ['ADMINISTRAÇÃO', 'ANÁLISE E DESENVOLVIMENTO DE SISTEMAS',
'ARTES CÊNICAS', 'AUTOMAÇÃO INDUSTRIAL', 'CIÊNCIAS BIOLÓGICAS',
'CIÊNCIAS CONTÁBEIS', 'DIREITO', 'EDUCAÇ... | <p>I ran your code in this order and all worked well.</p>
<pre><code>list_of_columns = ['ADMINISTRAÇÃO', 'ANÁLISE E DESENVOLVIMENTO DE SISTEMAS',
'ARTES CÊNICAS', 'AUTOMAÇÃO INDUSTRIAL', 'CIÊNCIAS BIOLÓGICAS',
'CIÊNCIAS CONTÁBEIS', 'DIREITO', 'EDUCAÇÃO FÍSICA', 'ENFERMAGEM',
'ENGENHARIA AMBIENTAL', 'ENGENHARIA... | python|pandas|dataframe | 0 |
14,726 | 66,841,988 | how to use map function for multiindex dataframe using pandas? | <p>I have a data frame like as shown below</p>
<pre><code>df = pd.DataFrame({'source_code':['11','11','12','13','14',np.nan],
'source_description':['test1', 'test1','test2','test3',np.nan,'test5'],
'key_id':[np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]})
</code></pre>
<p>I also have ... | <p>This seems to be a fairly standard <code>merge</code> with some renaming:</p>
<pre><code>(df.merge(hash_file, left_on = ['source_code','source_description'], right_on = ['source_id','source_code'])
.drop(columns = ['key_id','source_id','source_code_y'])
.rename(columns = {'source_code_x':'source_code','hash_... | python|pandas|dataframe|dictionary|series | 1 |
14,727 | 68,433,271 | memmap arrays to pytorch and gradient accumulation | <p>I have A Large dataset (> 62 GiB) after processing saved as two NumPy.memmap arrays one of the data and the other for the labels the dataset has these shapes (7390,60,224,224,3) , and (7390) and is <strong>NOT</strong> shuffled so i need to shuffle it first.</p>
<p>now i use tensorflow2 and used this code with my... | <p>I will just address the shuffle question.</p>
<p>Instead of shuffling with tf.data.Dataset, do it at the generator level. This should work:</p>
<pre><code>class Generator(object):
def __init__(self, images, labels, batch_size):
self.images = images
self.labels = labels
self.batch_size = ... | tensorflow|pytorch|dataset|numpy-memmap|batchsize | 0 |
14,728 | 68,095,546 | How to combine the fuzzy function with apply(lambda x: ) function? | <p>I have 2 dataframes df1 and df2 like this:</p>
<p>df1:</p>
<pre><code>Id Name
1 Tuy Hòa
2 Kiến thụy
3 Bình Tân
</code></pre>
<p>df2:</p>
<pre><code>code name
A1 Tuy Hoà
A2 Kiến Thụy
A3 Tân Bình
</code></pre>
<p>Now when I use merge:</p>
<pre><code>out_df = pd.merg... | <p><strong>Update</strong>: the strategy is the same than my previous answer but the algorithm has been replaced from <strong>Levenshtein distance</strong> to <strong>Damerau–Levenshtein distance</strong>.</p>
<p>I slightly modified your input data to better understanding:</p>
<pre><code>>>> df1
Id ... | python|pandas|lambda|apply|fuzzywuzzy | 2 |
14,729 | 68,259,714 | Get the output of the last convolutional layer of a pre-trained architecture in subclassed Keras model for gradcam | <p>I'm trying to get the output of the final convolutional layer of a pre-trained model. I need it to calculate the grad-cam. In order to do this, I need to make a model that has two outputs, one classification, and the output of the convolutional layer, like in this <a href="https://keras.io/examples/vision/grad_cam/"... | <p>To achieve what you need, we can do something like as follows.</p>
<p><strong>Trainable Model</strong></p>
<pre><code>import tensorflow as tf
from tensorflow import keras as K
import numpy as np
height, width, channels = 224, 224, 3
class CustomMobileNet(K.Model):
def __init__(self):
super(CustomMobileN... | python|tensorflow|machine-learning|keras|deep-learning | 1 |
14,730 | 68,286,824 | how to convert groupby object which has no aggregate function applied on it, to a new dataframe | <p>Updated:</p>
<p>I have a huge dataframe, providing small version of it.</p>
<pre><code>header = [np.array([' ',' ',' ','X','X','Y','Y']),
np.array(['A','B','C','D','E','F','G'])]
df = pd.DataFrame(columns=header)
df[' ','A'] = ['n','n','m','m','m','p']
df[' ','B'] = ['q','r','s','t','u','v']
df[' ','C'] = [... | <h3>applicable answer</h3>
<p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer">reset_index</a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename_axis.html" rel="nofollow noreferrer">rena... | python|pandas|dataframe|pandas-groupby|pandas-styles | 0 |
14,731 | 68,426,022 | How to get single median in numpy masked array with even number of entires | <p>I have a numpy masked nd-array. I need to find the median along a specific axis. For some cases, I end up having even number of elements, in which case <code>numpy.ma.median</code> gives average of the middle two elements. However, I don't want the average. I want one of the median elements. Any one of the two is fi... | <p>For even number of elements, the median returns the average of two middle numbers. However, if you don't want the average, just want one any of the two middle numbers, you can <strong>drop an element from your collection</strong> while calling the median method which will make length of collection odd, and you will ... | python|numpy|median|masked-array | 1 |
14,732 | 68,298,342 | How to use list of sparse tensors in tf.data.Dataset? | <p>I'm trying to build a model which takes list of sparse tensors as input. (list length is equal to batch size)</p>
<p>The reason I use sparse tensor is that I have to pass adjacency matrix to my GNN model and it is very sparse. (~99%)</p>
<p>I'm familiar with using pytorch, and it is very easy to feed sparse tensor i... | <p>If the SparseTensors have the same <code>dense_shape</code> you can create a unique SparseTensor instead of a list and pass it to <code>from_tensor_slices</code>.</p>
<p>For example the following code produce separate SparseTensors from a large SparseTensor <code>s</code> splitting them along the first dimension</p>... | tensorflow|sparse-matrix|tf.keras|tf.data.dataset | 0 |
14,733 | 1,262,783 | How to find the compiled extensions modules in numpy | <p>I am compiling numpy myself on Windows. The build and install runs fine; but how do I list the currently enabled modules .. and modules that are not made available (due to maybe compilation failure or missing libraries)?</p> | <p>numpy does not have optional components. Either the build is successful, or it fails. You can run the test suite to see if the build works.</p>
<pre><code>$ python -c "import numpy;numpy.test()"
Running unit tests for numpy
NumPy version 1.4.0.dev
NumPy is installed in /Users/rkern/svn/numpy/numpy
Python version 2.... | python|windows|numpy | 2 |
14,734 | 59,146,095 | Cumulative Sum DataFrame (.groupby()) | <p>I am trying to get the cumulative sum of 'counter' over the years. Basically, adding the sums for each individual year while maintaining the multi index structure. Help is highly appreciated! :)</p>
<pre><code>df = pd.DataFrame(df_raw[['counter']])
df['listings_per_zip'] = df.groupby(level=[0,1]).sum()
df = df.mean... | <p>Issue is resolved by the following code:</p>
<pre class="lang-py prettyprint-override"><code>df['listings_per_zip'] = df.groupby(level=[0,1]).sum().groupby(level=[1]).cumsum()
</code></pre> | python|pandas|numpy|dataframe|pandas-groupby | 1 |
14,735 | 14,132,216 | zip(,) string to float? | <p>I am trying to compute a daily P&L, with 10 min prices in a .csv (there are 42 times for each date)---where number of buys and number of sells in a day could be unequal. If they are unequal, the program should use the closing price for that unique date df["price"][t] to subtract (from/by) depending on whether it... | <p>Don't use the zip, you can keep the data in pandas native datastructures.<br>
Here prices should have read correctly as floats in the DataFrame.</p>
<p>You can do something like <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.sub.html" rel="nofollow"><code>sub</code></a> then <a href="http... | python|pandas|time-series | 2 |
14,736 | 45,083,474 | How to update vaiables in tensorflow scan | <p>I would like to make a variable in tensorflow, and then update it in tf.scan. First I tried something like this:</p>
<pre><code>import tensorflow as tf
with tf.variable_scope('foo'):
tf.get_variable('bar', initializer=tf.zeros([1.0]))
def repeat_me(last, current):
with tf.variable_scope('foo', reuse=True)... | <p>The <a href="https://www.tensorflow.org/api_docs/python/tf/assign_add" rel="nofollow noreferrer">document</a> says:</p>
<blockquote>
<p>Returns:</p>
<p>Same as "ref". Returned as a convenience for operations that want to use the new value after the variable has been updated.</p>
</blockquote>
<p><code>bar.... | tensorflow | 1 |
14,737 | 45,210,172 | How to subtract month correctly in Pandas | <p>My dataframe has two columns. When I subtract them to get the month in between, I got some weird numbers. Here is an example:</p>
<pre><code>test = pd.DataFrame({'reg_date': [datetime(2017,3,1), datetime(2016,9,1)],
'leave_date':[datetime(2017,7,1), datetime(2017,6,1)]})
test['diff_month'] = test.... | <p>To get your result you can use <code>relativedelta</code> from <code>dateutil</code>:</p>
<pre><code>import datetime
from dateutil import relativedelta
a = datetime.datetime(2016, 12, 1)
b = datetime.datetime(2017, 5, 1)
relativedelta.relativedelta(b, a).months
#5
</code></pre> | python|pandas | 2 |
14,738 | 57,144,822 | Adding new columns to dataframe from other dataframe according to list of indices in other dataframe | <p>I have two dataframes, each row in dataframe <code>A</code> has a list of indices corresponding to entries in dataframe <code>B</code> and a set of other values. I want to join the two dataframes in a way so that each of the entries in <code>B</code> has the other values in <code>A</code> where the index of the entr... | <p>If you have pandas >=0.25, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer">explode</a>:</p>
<pre><code>C = A.explode('indices')
</code></pre>
<p>This gives:</p>
<pre><code> indices a1 a2
0 0 a 100
0 1 a 100... | python|pandas|dataframe | 5 |
14,739 | 57,014,101 | How to import data from a .txt file into arrays in python | <p>I am trying to import data from a .txt file that contains four columns that are separated by tab and is several thousands lines long. This is how the start of the document look like:</p>
<pre><code>Data info
File name: D:\(path to file)
Start time: 6/26/2019 15:39:54.222
Number of channels: 3
Sample rate: 1E6
Store... | <p>So it was an easy fix, just had to remove the braces from <code>skiprows=[19]</code>.</p>
<p>The cods now looks like this and works.</p>
<pre><code>fileNames = ["Test1_0001.txt", "Test2_0000.txt", "Test3_0000.txt",
"Test4_0000.txt", "Test5_0000.txt", "Test6_0001.txt", "Test7_0000.txt",
"Test8_0000.txt", "T... | python|arrays|pandas|numpy|scipy | 0 |
14,740 | 45,990,001 | Forcing pandas .iloc to return a single-row dataframe? | <p>For programming purpose, I want <code>.iloc</code> to consistently return a data frame, even when the resulting data frame has only one row. How to accomplish this?</p>
<p>Currently, <code>.iloc</code> returns a Series when the result only has one row. Example:</p>
<pre><code>In [1]: df = pd.DataFrame({'a':[1,2], ... | <p>Use double brackets,</p>
<pre><code>df.iloc[[0]]
</code></pre>
<p>Output:</p>
<pre><code> a b
0 1 3
print(type(df.iloc[[0]])
<class 'pandas.core.frame.DataFrame'>
</code></pre>
<p>Short for <code>df.iloc[[0],:]</code></p> | python|pandas|dataframe|indexing | 172 |
14,741 | 46,097,968 | TensorFlow: How to handle void labeled data in image segmentation? | <p>I was wondering how to handle not labeled parts of an image in image segmentation using TensorFlow. For example, my input is an image of height * width * channels. The labels are too of the size height * width, with one label for every pixel.</p>
<p>Some parts of the image are annotated, other parts are not. I woul... | <p>I'm not 100% familiar with TF. However, have you considered using the <code>weights</code> parameter of the loss?<br>
Looking at <a href="https://www.tensorflow.org/api_docs/python/tf/losses/sparse_softmax_cross_entropy" rel="noreferrer"><code>tf.loses.sparse_softmax_cross_entropy</code></a> it has a parameter <code... | python|tensorflow|neural-network|deep-learning|image-segmentation | 12 |
14,742 | 46,104,357 | Printing last column in python | <p>My h.csv file contains 7 columns of float data type and the delimiter is a white space</p>
<p>my program in python is as follows </p>
<pre><code>import pandas as pd
import csv
import numpy as np
h = np.array(pd.read_csv("h.csv", delim_whitespace=True))
print(h)
print("\n")
X = h[:,0:6]
print(X)
print("\n")
y = h... | <p>just add names to the columns and print by them, for example:</p>
<pre><code>h = pd.read_csv("h.csv", delim_whitespace=True, names = ["A", "B", "C", "X","Y","Z","P"])
print (h.A)
print (h.B)
print (h.Y)
print (h.P)
</code></pre> | python|pandas|csv|numpy | 0 |
14,743 | 50,753,522 | How to make the maximum of each column 1 and others 0 in pandas dataframe? | <p>I have a dataframe with float values. I would like to make the max of each column 1 and all others in the column 0. </p>
<p>Example:</p>
<pre><code>1 2 3
4 5 1
7 0 1
</code></pre>
<p>becomes</p>
<pre><code>0 0 1
0 1 0
1 0 0
</code></pre>
<p>Assume presence of headers and index also.</p>
<p>How do I use the... | <p>The best way to use <code>df.apply</code> is to not use <code>df.apply</code>.</p>
<pre><code>(df == df.max()).astype(int)
0 1 2
0 0 0 1
1 0 1 0
2 1 0 0
</code></pre> | python|pandas|dataframe | 3 |
14,744 | 33,101,410 | Why does this Theano code run successfully without any errors? | <p>I have the following piece of code borrowed from an online tutorial. I see that the below line written in the main method of the code</p>
<pre><code>c = broadcasted_add(a, b)
</code></pre>
<p>is adding the tensor 'a' of dimension (2,1,2,2) and tensor 'b' of dimension (2,2,2,2). How is it able to add correctly even... | <p>The reason this works is that new dimensions added by <code>dimshuffle</code> via the <code>'x'</code> parameter value are always broadcastable.</p>
<p>Notice that in <code>broadcasted_add</code> the only dimension that needs to be broadcasted is the dimension that was added to <code>a</code> via the <code>dimshuff... | python|numpy|theano|deep-learning | 2 |
14,745 | 33,065,785 | Conversion from Matlab Timestamp Date to Python Timestamp Date | <p>I have a timestamp Matrix with (72500, 1) dimension in MATLAB. I have written such a statement in MATLAB:</p>
<pre><code>returnMatrix = datestr(M(:,1)/86400 + datenum(1970,1,1)- 4/24);
</code></pre>
<p>And I successfully get the output date matrix back as a return Matrix.</p>
<pre><code>returnMatrix = ['29/06/201... | <p>What I understand from this question is that you have data in seconds which you want to add to the base date which is 1/1/1970 and get the new date. Python 'timedelta' method from 'datetime' module will be handy to solve this problem.</p>
<p>Here I present my solution to your problem</p>
<pre>
import datetime... | python|matlab|date|numpy|matrix | 1 |
14,746 | 9,243,004 | Storing large amount of boolean data in python | <p>I need to store sparse matrix data.
Size of data is <code>10^6 10^4</code> columns.
In each column I store a vector of 0's except of few values where it's <code>true</code>.</p>
<p>Then I need to sum over columns in each matrix, and multiply each row with a scalar.
I tried dictionaries, but they fail when I need t... | <p>How about two dicts? Assuming this is the matrix (<code>x</code> for <code>True</code>):</p>
<pre><code> 0 1 2 3 4 5 6 7
0 x x x
1 x
2 x
3 x
4
5
6 x x
7
</code></pre>
<p>You'd only need to store</p>
<pre><code>rows = {0: [0, 2, 5], 1: [1],... | python|arrays|numpy | 4 |
14,747 | 66,652,562 | How to read float values from binary data in Python? | <p>I have a binary file in which data segments are interspersed. I know locations (byte offsets) of every data segment, as well as size of those data segments, as well as the type of data points (float, float32 - meaning that every data point is coded by 4 bytes). I want to read those data segments into an array like s... | <p>If you want a <code>numpy.ndarray</code>, you can just use <a href="https://numpy.org/doc/stable/reference/generated/numpy.frombuffer.html" rel="nofollow noreferrer"><code>numpy.frombuffer</code></a></p>
<pre><code>>>> import numpy as np
>>> data = b'\xa5\x10[@\x00\x00\x88@a\xf3\xf7A\x00\x00\x88@&a... | python|python-3.x|numpy|binaryfiles | 3 |
14,748 | 66,482,194 | Clearing memory when training Machine Learning models with Tensorflow 1.15 on GPU | <p>I am training a pretty intensive ML model using a GPU and what will often happen that if I start training the model, then let it train for a couple of epochs and notice that my changes have not made a significant difference in the loss/accuracy, I will make edits, re-initialize the model and re-start training from e... | <p>It depends on exactly what GPUs you're using. I'm assuming you're using NVIDIA, but even then depending on the exact GPU there are three ways to do this-</p>
<ol>
<li><code>nvidia-smi -r</code> works on TESLA and other modern variants.</li>
<li><code>nvidia-smi --gpu-reset</code> works on a variety of older GPUs.</l... | python-3.x|tensorflow|gpu | 0 |
14,749 | 66,357,241 | Filter pandas columns based on row condition | <p>i have the following dataframe called df.</p>
<pre><code> x1 x2 x3 ....
row1 12 3.4 5 ...
row2 1 3 4 ...
row3 True False True ...
...
</code></pre>
<p>I want to display the columns where all the row3 values are True.</p>
<p>so like columns <code>x1</code> and <code>x3</code> will be ... | <p><code>iloc</code> asks you to pass (list of) integers. Try <code>loc</code>:</p>
<pre><code>df.loc[:,df.loc['row3']]
</code></pre> | python|pandas|filter | 2 |
14,750 | 66,467,846 | How to create df1 from df2 with different row and column indices? | <p>I want to fill df1 using df2 values, I could achieve it using nested loop but is very much time taking.
Is there any smart way to do this ?
P.S. The size of df is around 8000 rows , 8000 columns.</p>
<p>df1 initially is like this</p>
<pre><code> A B C D
A 0 0 0 0
B 0 0 0 0
C 0 0 0 ... | <p>You could try changing the row and col names in df1 (based on the correspondence with df2) and for the cases of multiple correspondence (like B) you could first name them B1, B2, etc... and then sum them together:</p>
<pre><code>
> di
{'Q': 'B1', 'P': 'A', 'S': 'D', 'R': 'C', 'T': 'B2'}
> df1 = df2.copy()
>... | python|pandas|dataframe|numpy | 1 |
14,751 | 57,504,557 | adding row from one dataframe to another | <p>I am trying to insert or add from one dataframe to another dataframe. I am going through the original dataframe looking for certain words in one column. When I find one of these terms I want to add that row to a new dataframe.</p>
<p>I get the row by using.
<code>entry = df.loc[df['A'] == item]</code>
But when tr... | <p>So the entry is a dataframe containing the rows you want to add?
you can simply concatenate two dataframe using concat function if both have the same columns' name</p>
<pre><code>import pandas as pd
entry = df.loc[df['A'] == item]
concat_df = pd.concat([new_df,entry])
</code></pre>
<p>pandas.concat reference:</p>
<... | python|pandas | 17 |
14,752 | 57,298,429 | Get_dummies produces more columns than its supposed to | <p>I'm using get_dummies on a column of data that has zeroes or 'D' or "E". Instead of producing 2 columns it produces 5 - C, D, E, N, O. I'm not sure what they are and how to make it do just 2 as its supposed to. </p>
<p>When I just pull that column shows 0's and D and E, but when I put it in get_dummies adds extra c... | <h2>Setup</h2>
<pre><code>dtype = pd.CategoricalDtype([0, 'C', 'D', 'E', 'N', 'O', 'PreferredContactTime'])
data = pd.DataFrame({2: [
'PreferredContactTime', 0, 0, 'D', 0, 0, 0, 0, 'D', 0, 0
]}).astype(dtype)
</code></pre>
<hr>
<p>Your result</p>
<pre><code>dummy = pd.get_dummies(data[2], dummy_na=False )
dumm... | pandas | 4 |
14,753 | 57,406,294 | tensorflow and torch.cuda can find GPU but Keras only can't | <p>I tried with <a href="https://stackoverflow.com/questions/44544766/how-do-i-check-if-keras-is-using-gpu-version-of-tensorflow">How do I check if keras is using gpu version of tensorflow?</a> answer. But I recognized only keras doesn't see GPU.</p>
<p>I re-installed whole requirements including tensorflow-gpu, keras... | <p>Solved!</p>
<p>It was surprisingly silly question.</p>
<p>The error had kept told me what it was.</p>
<p>I checked libcudnn.so.7 again and it was installed at wrong place.</p>
<p>Please verify this when you meet similar error!</p>
<pre><code>2019-08-08 16:16:57.086483: I tensorflow/stream_executor/platform/defa... | python|tensorflow|keras | 0 |
14,754 | 57,669,446 | Select rows from a DataFrame based on True or False in a column in pandas | <p>Select rows from a DataFrame based on True or False in a column in pandas:</p>
<p>For example,</p>
<pre><code>import pandas as pd
df = {'uid':["1", "1", "1", "1", "2", "2", "2", "2"],
'type': ["a", "a", "b", "a", "a", "b", "b", "a"],
'is_topup':["FALSE", "FALSE", "TRUE", "FALSE","FALSE", "TRUE", ... | <p>Not sure the most efficient way but using <code>idxmax</code>:</p>
<pre><code>new_df = df.groupby('uid').apply(lambda x: x[:(x['is_topup'] & x['label']).reset_index(drop=True).idxmax()+1])
print(new_df)
</code></pre>
<p>Output:</p>
<pre><code> uid type is_topup label
uid
1... | python|pandas | 1 |
14,755 | 57,658,046 | Convert a column of a text file to scientific notation | <p>I have a text file with one column and many raws (BBB.txt). I want to convert all the numbers to scientific notation. I am trying like below:</p>
<pre><code>z= loadtxt ('BBB.txt')
for i in z:
with open ('ff.txt','w') as h:
y=np.format_float_scientific(z)
h.write("\n".join(map(lambda z: '%f' % z,... | <p>You have confused about your namings in x,y,z,i. I always recommend to you to use long names for variables. Below script will help you</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
z = open('BBB.txt')
for i in z:
with open ('ff.txt','a') as h:
i=float(i)
y=np.format_floa... | python|numpy|text|scientific-notation | 0 |
14,756 | 24,396,732 | Method to split a SciPy minimum spanning tree based on greatest edge weight? | <p>Is there a way to split the output of a <a href="http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree.html#scipy.sparse.csgraph.minimum_spanning_tree" rel="nofollow">scipy.sparse.csgraph.minimum_spanning_tree</a> operation by dropping the greatest edge weight value in... | <p>I had the same problem and managed to figure out a solution using only <code>scipy</code>. All this does is take the MST, locate the maximum weighted edge, delete it (i.e. zero it out), and then use the <code>connected_components</code> method to figure out which nodes remain connected.</p>
<p>Here is the complete ... | python|numpy|scipy|minimum-spanning-tree | 2 |
14,757 | 24,245,139 | Installing pandas in django | <p>I have installed numpy and pandas in ubuntu 12.04. Also, I have added django_pandas in my INSTALLED_APPS but then also I am getting
ImportError: No module named django_pandas
how should i proceed now</p> | <p>There are no extra steps you need to take to install "Pandas in Django", just install Django and Pandas using pip:</p>
<pre><code>pip install django
pip install pandas
</code></pre> | django|python-2.7|pandas | 3 |
14,758 | 43,654,727 | Pandas - get row and column name for each element during applymap | <p>I am trying to compare one list of strings for similarity and get the results in a pandas dataframe for inspection; so I use one list as index and the other as column list. I then want to compute the "Levenshtein similarity" on them (a function that compares the similarity between two words).</p>
<p>I am t... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code></a> on the dataframe, and to access columns' values use <code>.name</code>:</p>
<pre><code>def lev(x):
#replace your function
return x.index + x.name
a ... | python|pandas | 16 |
14,759 | 43,486,559 | How to plot from .dat file with multiple columns and rows separated with tab spaces | <p>I have 12 columns in my .dat file. How can I plot the first column with 12th column and there are around 50 rows. Each value is separated by a tab space. I have tried this error as the wrong number of columns at line42 is coming. </p>
<pre><code> import numpy as np
from matplotlib import pyplot as plt
data=n... | <p>The code in the question is correct! If it doesn't work, it's because your data is not organized the way you think it is or because you have missing values somewhere in your data. </p>
<p>You may try to use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow noreferrer... | python|numpy|matplotlib|plot | 3 |
14,760 | 43,635,694 | Difference between dictionary and pandas series in Python | <p>I have a requirement to keep data in key value pairs. I search and found 2 ways in python:</p>
<ol>
<li><p>default data structure dictionary.</p>
<pre><code>x = {'key':value}
value = x['key']
</code></pre></li>
<li><p>series of pandas data structure.</p>
<pre><code>x = pandas.Series({'key':value})
value = x.key
<... | <p><strong>Always read the docs first</strong><br>
But since you asked:</p>
<ul>
<li><a href="https://docs.python.org/3.5/tutorial/datastructures.html#dictionaries" rel="noreferrer">Dictionaries</a> are one of python's default data structures which
allow you to store <code>key: value</code> pairs and offer some built-... | python|python-3.x|pandas|dictionary | 21 |
14,761 | 43,890,875 | Pandas to_numeric with option errors=ignore does not convert to float | <p>I wanted to convert pandas series from object to float but keep other strings as it is.</p>
<p>Here is the code snippet :-</p>
<pre><code>In [37]: df = pd.DataFrame(['-1.0', 'hello', '0.5'])
In [38]: df[0]
Out[38]:
0 -1.0
1 hello
2 0.5
Name: 0, dtype: object
</code></pre>
<p>What I want is this :-</p>
<p... | <p>To get the result you want:</p>
<pre><code>In [29]:
df1 = pd.to_numeric(df[0], errors='coerce')
df1
Out[29]:
0 -1.0
1 NaN
2 0.5
Name: 0, dtype: float64
In [32]:
df1 = df1.fillna(df[0])
df1.iloc[0]
Out[32]:
-1.0
In [33]:
df1.iloc[1]
Out[33]:
'hello'
In [34]:
df1.iloc[-1]
Out[34]:
0.5
</code></pre> | python|pandas | 0 |
14,762 | 72,855,936 | Looping through a second column using a probability input | <p>I have a similar question to one I posed here, but subtly different as it includes an extra step to the process involving a probability:</p>
<p><a href="https://stackoverflow.com/questions/72576406/">Using a Python pandas dataframe column as input to a loop through another column</a></p>
<p>I've got two pandas dataf... | <p>You could use pass a probabilities list to <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html" rel="nofollow noreferrer"><code>np.random.<b>choice</b></code></a>:</p>
<pre><code>In [1]: import numpy as np
...: import pandas as pd
In [2]: d_1 = {
...: 'Year': [1, 2, 3,... | python|pandas | 1 |
14,763 | 73,107,908 | how to generate company logo image mask using OpenCV? | <p>I am working on removing the company logo background image mask but I'm not getting the exact output. I try many ways to remove the company logo background but every model is trained in human categories just like model name mode net, u2net, etc. I plan to train the custom model so I need an image and mask I'm genera... | <p>Here is my code for remove company logo background using opencv it will be work for me. Here is my input image and output image of mask in below.</p>
<pre><code># import library
import cv2
import numpy as np
# Reading image
img = cv2.imread("sample_image/logo_1.png", cv2.IMREAD_GRAYSCALE)
# Cannny edge d... | python|numpy|opencv | 2 |
14,764 | 72,967,321 | Trying to split 3 different datastets from 1 column | <p>I currently have a CSV column that contains three different datasets (P,T,C) looking like: P= +0.456T=+12.659C=39.285</p>
<p>This is just one out of many records but all the data is separated the same with P,T,C. I have posted the dataframe head below:</p>
<p><a href="https://i.stack.imgur.com/L3g0y.png" rel="nofol... | <p>try this:</p>
<pre><code>s='P= +0.456T=+12.659C=39.285'
p = re.findall('[PTC]=\+?[0-9.]+',s.replace(' ', ''))
p
>['P=+0.456', 'T=+12.659', 'C=39.285']
[float(r.split('=')[1]) for r in p]
>[0.456, 12.659, 39.285]
</code></pre> | python|pandas|dataframe|split | -1 |
14,765 | 72,968,467 | How to sort column order by column name with dates | <p>I have a dataframe such as:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">data</th>
<th style="text-align: left;">more data</th>
<th style="text-align: left;">2010-01-01</th>
<th style="text-align: left;">2011-01-01</th>
</tr>
</thead>
<tbody>
<tr>
<td style="... | <p>I'm not pretty sure how you want to handle non-datetime columns. I assume that you prefer these columns to show at the beginning of the dataframe. With that in mind, I suggest you use <code>sorted</code> function:</p>
<pre class="lang-py prettyprint-override"><code>import time
import datetime
def sort_date(value):
... | python|pandas|sorting | 0 |
14,766 | 70,594,494 | Count how many times a row value exceeds a number in pandas? | <p>I have a dataframe like below:</p>
<pre><code>+-------+------+-----+------+------+
|ID |r |r1 |r2 |count |
+-------+------+-----+------+------+
|1 |0.3 |0.75 |0.86 |2 |
|34 |0.1 |0.15 |0.9 |1 |
+-------+------+-----+------+----+--
</code></pre>
<p>The last column 'count' is what ... | <p>The only difficult part here is to select the right columns:</p>
<p>You can <code>drop</code> undesirable columns:</p>
<pre><code>df.drop('ID',axis=1).ge(0.75).sum(axis=1)
</code></pre>
<p>You can <code>filter</code> wanted columns:</p>
<pre><code>df.filter(regex=r'^r\d*').ge(0.75).sum(axis=1)
</code></pre>
<p>You c... | python-3.x|pandas|dataframe | 2 |
14,767 | 70,540,337 | Loop to split a large dataframe to small dataframes | <p>DF is a dataframe with columns [A1,B1,C1,A2,B2,C2,A3,B3,C3]</p>
<p>I want to split that 'DF' data frame into small dataframes DF1,DF2,DF3</p>
<p>DF1 to have [A1,B1,C1] as columns</p>
<p>DF2 to have [A2,B2,C2] as columns</p>
<p>DF3 to have [A3,B3,C3] as columns</p>
<p>The number in the name of the dataframe DF'3' sho... | <p>You can't dynamically change an object's name.<br />
You can use a list comprehension with explicit definition of the dfs:</p>
<pre><code>df1,df2,df3=[df[['A{}'.format(i),'B{}'.format(i),'C{}'.format(i)]] for i in range(1,4)]
</code></pre>
<p><strong>Update based on ViettelSolutions' comment</strong><br />
Here is ... | python|pandas|dataframe | 2 |
14,768 | 70,682,602 | How to solve no such node error in pytables and h5py | <p>I built an hdf5 dataset using pytables. It contains thousands of nodes, each node being an image stored without compression (of shape 512x512x3). When I run a deep learning training loop (with a Pytorch dataloader) on it it randomly crashes, saying that the node does not exist. However, it is never the same node tha... | <p>Before accessing the dataset (node), add a test to confirm it exists. While you're adding checks, do the same for the attribute <code>'TITLE'</code>. If you are going to use hard-coded path names (like <code>'group_0'</code>) you should check all nodes in the path exist (for example, does <code>'group_0'</code> exis... | python-3.x|pytorch|h5py|pytables | 0 |
14,769 | 70,697,002 | Select row only if ID is in excel file | <p>I want to select rows from df only if their ID is in excel file. Why am I getting 0 rows?</p>
<pre><code>df = pd.read_excel('df.xlsx')
df_with_status = pd.read_excel('df_status.xlsx')
df2=df[df['EFF_ID'].isin([df_with_status['ID']])]
</code></pre>
<p>I have got 0 rows but I should get more records.</p> | <p>Not totally sure, but I think you have to remove the brackets at the isin() in this line</p>
<pre><code>df2=df[df['EFF_ID'].isin([df_with_status['ID']])]
</code></pre>
<p>i.e. it should read</p>
<pre><code>df2=df[df['EFF_ID'].isin(df_with_status['ID'])]
</code></pre>
<p>The reason is, that you are comparing the valu... | python|pandas | 1 |
14,770 | 70,486,650 | Why is my model giving different results in tensorflow.js and in Python Tensorflow? | <p>I'm trying to adapt the notebook "<a href="https://www.kaggle.com/nageshsingh/eda-predict-artist-from-artworks-imagenet" rel="nofollow noreferrer">Predict Artist from Artworks</a>" to my own dataset. The Keras model has been generated and converted to a Tensorflow model (using <code>tensorflowjs_converter ... | <p>It surely has to do with the way the image is processed before the prediction. In js, you are rotating the image before the prediction. You don't seem to be doing the same thing in python.</p>
<p>Additionnally, you don't need the extra library <code>sharp</code> to load your image</p>
<pre><code>const buf = fs.readF... | tensorflow|tensorflow.js | 1 |
14,771 | 70,593,426 | Library import in Python does not work as expected | <p>I am having a strange error executing this Python code.</p>
<pre><code>import tensorflow as tf
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(2,)),
tf.keras.layers.Dense(10, activation='sigmoid'),
])
model.compile(optimizer='adam',
loss='mae',
metrics=['mse'... | <p>It seems that there's a bug in the current version of tensorflow, particularly with the <code>_load()</code> method in the <code>LazyLoader</code> class defined in the module <code>tensorflow.python.util.lazy_loader</code>. I think we could just leave it until being fixed. I'd like to dig into another question raise... | python-3.x|tensorflow | 2 |
14,772 | 42,974,627 | How to check if a Tensorflow Session is still open (without catching an exception)? | <p>Is there a way in Tensorflow to find if a given <code>tf.Session()</code> is still open? The only way I have found so far is to try to use it, and catch the exception when it is not open.</p> | <p>Check if session._closed is True</p>
<pre><code>sess = tf.Session()
init_op = tf.global_variables_initializer()
sess.run(init_op)
print(sess._closed)
sess.close()
print(sess._closed)
</code></pre>
<p>Output</p>
<pre><code>False
True
</code></pre> | tensorflow | 11 |
14,773 | 42,777,086 | How to convert geospatial coordinates dataFrame to native x,y projection? | <p>I have a following dataframe, the lat and lon are the latitudes and longitudes in Geographic coordinates system. I am trying to convert these coordinate system into native (x, y) projection.</p>
<p>I have tried pyproj for single points, but how do I proceed for the whole dataframe with thousands of rows.</p>
<pre>... | <p>Unfortunately, <code>pyproj</code> only converts point by point. I guess something like this should work:</p>
<pre><code>import pandas as pd
from pyproj import Proj, transform
inProj = Proj(init='epsg:4326')
outProj = Proj(init='epsg:3857')
def towgs84(row):
return pd.Series(transform(inProj, outProj, row["la... | python|pandas|dataframe|coordinates|geospatial | 1 |
14,774 | 42,705,228 | how to read these json files | <p>My data folder has lots of json files of amazon product info, ratings, reviews and etc. Each json file contains info about one particular amazon product. I'm stuck in the first step of my project: loading data.
I tried:
json module: json.loads(...)</p>
<pre><code>JSONDecodeError: Expecting value: line 1 column 1... | <p>did you try this:</p>
<pre><code>import requests
import json
r = requests.get(url, timeout=1000)
data = json.loads(r.text)
</code></pre> | python|json|pandas | 0 |
14,775 | 27,323,848 | MPI for python broadcast | <p>Hi guys I am new here so please excuse me if I make any errors. I use python to write some code for my masters project and recently started using mpi4py to make my code parallel since I have available 12 cores and also for time purposes. I cannot for some reason get the bcast function to work. I want to work out <co... | <p>You have to use:</p>
<pre><code>T2 = comm.bcast(T2, root=0)
</code></pre>
<p>This is the correct usage of <code>bcast</code> according to the <a href="http://mpi4py.scipy.org/docs/usrman/tutorial.html#collective-communication" rel="nofollow">mpi4py tutorial.</a></p> | python|numpy|scipy | 0 |
14,776 | 27,130,602 | Selecting different values for inner dimension of hierarchical index in Pandas | <p>I have a big table with a hierarchical index, and am trying to select a subset of it. The real table in question has 3 levels to the axis-0 index, and I want all values on levels 1 and 2 and one choice of level 3.</p>
<p>For a small 2-level example of what I'm trying to do, here's the data frame setup:</p>
<pre><c... | <p>Your intuition to use <code>join</code> is good. That's the Pandas-esque way of doing that:</p>
<pre><code>sel = pd.DataFrame({'I1': [1,2,3], 'I2': ['foo', 'blatz', 'bar']}).set_index(['I1','I2'])
print df.join(sel, how = 'right')
V
I1 I2
1 foo 0
2 blatz 6
3 bar 9
</code></pre> | python|pandas | 1 |
14,777 | 30,646,786 | Python: Array(Matrix) to Pandas DataFrame | <p>I am stuck trying to convert my array into a pandas dataframe.</p>
<p>My output array looks like this:</p>
<pre><code>[[1,2,4,n],[1,2,3,n]]
</code></pre>
<p><strong>Example output:</strong></p>
<pre><code>[[0.04376367614879647, 0.04376367614879649, 0.043763676148796504, 0.043763676148796504, 0.043763676148796504... | <p>There is a <code>.T()</code> method does it:</p>
<pre><code>In [8]:
arr = [[1,2,3,5],[2,3,4,6]]
print pd.DataFrame(arr, index=['col1','col2']).T
col1 col2
0 1 2
1 2 3
2 3 4
3 5 6
</code></pre>
<p>If your input is <code>numpy</code> <code>array</code>:</p>
<pre><code>In [9]:
a... | python|arrays|pandas | 2 |
14,778 | 26,830,716 | Requesting rolled values on arbitrary dates and requesting ranges without specific start/end dates | <p>I have a couple of questions on date sampling within a dataframe. Here an example:</p>
<pre><code>import pandas as pd
dates = pd.bdate_range('2014-01-01', periods=10)
df = pd.DataFrame(range(10), index=dates)
</code></pre>
<p>yields this data frame:</p>
<pre><code>2014-01-01 0
2014-01-02 1
2014-01-03 2
201... | <p>There are at least two ways to do it:</p>
<p>1) Using slicing (with <code>.loc</code> or <code>.ix</code> if using MultiIndex or slicing on both axes):</p>
<pre><code>df[df.index < '2014-01-04'] # change '<' to '>' to have forward going dates.
0
2014-01-01 0
2014-01-02 1
2014-01-03 2
</cod... | python|pandas | 0 |
14,779 | 26,724,378 | Pandas SettingWithCopyWarning | <p>Python 3.4 and Pandas 0.15.0</p>
<p>df is a dataframe and col1 is a column. With the code below, I'm checking for the presence of the value 10 and replacing such values with 1000. </p>
<pre><code>df.col1[df.col1 == 10] = 1000
</code></pre>
<p>Here's another example. This time, I'm changing values in col2 based on... | <p>The issue here is that: <code>df.col1[df.col1 == 10]</code> returns a copy.</p>
<p>So I would say:</p>
<pre><code>row_index = df.col1 == 10
# then with the form .loc[row_indexer,col_indexer]
df.loc[row_index, 'col1'] = 100
</code></pre> | python|pandas|warnings|chained-assignment | 39 |
14,780 | 26,900,940 | Pandas Series : faster way of computing periods back to preceding high | <p>I have a timeseries of price data stored as Open, High, Low, Close values in a DataFrame</p>
<p>I want to make a new column in which each element records the count of how many days back you need to look to find a high higher in the source array.</p>
<p>So for a series like this</p>
<pre><code> import pandas as... | <p>You can do this by two for loop, but the worst time complexity maybe <code>O(N**2)</code>. Here is a method that can do this in <code>O(N*log(N))</code>:</p>
<p>The algorithm:</p>
<ul>
<li><code>argsort()</code> the array to get an <code>index</code> array</li>
<li>for every element in <code>index</code> at <code>... | python|numpy|pandas | 1 |
14,781 | 39,135,472 | Setting Order of Columns with matplotlib bar chart | <p>I produce a bar graph with the following code: </p>
<pre><code>Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CON'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index')
df.plot(kind = 'bar')
</code></pre>
<p>It produces the following bar chart: </p>
<p><a href="https://i.stack.imgur.com/4sWHw.png" rel="nof... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_index.html" rel="nofollow"><code>sort_index</code></a> and last <a hr... | python|pandas|numpy|matplotlib|bar-chart | 4 |
14,782 | 29,319,525 | Find occurrences of a value in a numpy array and assign it appropriate weights | <p>I have a text file of close to 1 million lines.It has 2 columns.Column 1 has numbers from 0-99 and column has 4 sizes ranging from S,M,L,XL. The numbers from 0 to 99 keep repeating themselves in the 1 million lines with a different sizes as follows:</p>
<pre><code>11 S
19 S
19 M
19 M
63 L
14 S
11 L
63 XL
14 S
11 L... | <p>We can do this by applying <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow"><code>numpy.unique</code></a> on reversed version of the first column received from the file. Reversing is required because other wise it(<code>return_index=True</code>) will return the indices o... | python|numpy|aggregate | 1 |
14,783 | 29,149,854 | Extract indices of intersecting array from numpy 2D array in subarray | <p>I have two 2D numpy square arrays, A and B. B is an array extracted from A where a certain number of columns and rows (with the same indices) have been stripped. Both of them are symmetric. For instance, A and B could be:</p>
<pre><code>A = np.array([[1,2,3,4,5],
[2,7,8,9,10],
[3,8,13,14... | <p>Consider the easy case when all the values are distinct:</p>
<pre><code>A = np.arange(25).reshape(5,5)
ans = [1,3,4]
B = A[np.ix_(ans, ans)]
In [287]: A
Out[287]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
In [... | python|arrays|numpy|intersection | 2 |
14,784 | 33,702,251 | tensorflow loss minimization type error | <p>I have a loss function implemented in TensorFlow that computes mean squared error. All tensors being used to compute the objective are of type float64 and therefore the loss function itself is of dtype float64. In particular,</p>
<pre><code>print cost
==> Tensor("add_5:0", shape=TensorShape([]), dtype=float64)
<... | <p>Currently the <code>tf.train.GradientDescentOptimizer</code> class only <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/optimizer.py#L325" rel="nofollow">supports</a> training on 32-bit floating-point variables and loss values. </p>
<p>However, it looks like the kernel is im... | tensorflow | 4 |
14,785 | 33,682,713 | How to use Pandas to create Dictionary from column entries in DataFrame or np.array | <p>So I have a <code>DataFrame</code>, I labeled the columns a - i. I want to make a <code>Dictionary of Dictionaries</code> where the outer key is column "a", the inner key is column "d", and the value is "e". I know how to do this by iterating through each row, but I feel like there is a more efficient way to do t... | <p>There's a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html" rel="nofollow"><code>to_dict</code></a> method:</p>
<pre><code>In [11]: DF.to_dict()
Out[11]:
{'a': {0: 'AAA', 1: 'ABA', 2: 'AAC', 3: 'AAB', 4: 'AAA'},
'b': {0: '86880690', 1: '86880690', 2: '86880690' 3: '86880... | python|numpy|dictionary|pandas|dataframe | 4 |
14,786 | 33,538,637 | How to rearrange a Series to DataFrame using pandas | <p>I have a <code>Series</code> as following:</p>
<pre><code>In [37]: ser
Out[37]:
Aa 0
Ab 1
Ac 2
Ba 3
Bb 4
Bc 5
Ca 6
Cb 7
Cc 8
dtype: int3
</code></pre>
<p>I want to rearrange it to a <code>DataFrame</code> as:</p>
<pre><code> a b c
A 0 1 2
B 3 4 5
C 6 7 8
</code></pre>
<p... | <p>Here you go:</p>
<pre><code>ser.groupby(lambda i: i[0]).apply(lambda x: x.rename({i: i[1] for i in x.index})).unstack()
</code></pre>
<p>You were close!</p> | python|pandas|dataframe|series | 4 |
14,787 | 29,576,430 | Shuffle DataFrame rows | <p>I have the following DataFrame:</p>
<pre><code> Col1 Col2 Col3 Type
0 1 2 3 1
1 4 5 6 1
...
20 7 8 9 2
21 10 11 12 2
...
45 13 14 15 3
46 16 17 18 3
...
</code></pre>
<p>The DataFrame is read from a CSV file. All rows whic... | <p>The idiomatic way to do this with Pandas is to use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html" rel="noreferrer"><code>.sample</code></a> method of your data frame to sample all rows without replacement:</p>
<pre class="lang-py prettyprint-override"><code>df.s... | python|pandas|dataframe|permutation|shuffle | 1,384 |
14,788 | 62,085,732 | Why builtin function abs() don't work with Python lists, but works correctly with NumPy arrays and pandas series (as it would be vectorized)? | <p>Why builtin function <code>abs()</code> don't work with Python lists, but work correctly with NumPy arrays and pandas series?</p>
<p>Applying built-in <code>abs()</code> function to Python list raises an exception</p>
<blockquote>
<p>TypeError: bad operand type for abs(): 'list'</p>
</blockquote>
<p>Nothing sur... | <p>The quoted documentation is obsolete.</p>
<p>The <a href="https://docs.python.org/3/library/functions.html#abs" rel="noreferrer">new documentation</a> (for Python 3.8.3) states:</p>
<blockquote>
<p>abs(x)<br>
Return the absolute value of a number. The argument may be an integer or a floating point number. ... | python|pandas|numpy | 5 |
14,789 | 62,194,100 | How to convert cumulative data to daily data for multiple-indexes in python? | <p>I have a dataset of following form - </p>
<pre><code>date code A B C
20-02-01 box1 1 2 1
20-02-02 box1 2 2 1
20-02-03 box1 3 2 1
20-02-01 box2 2 1 1
20-02-04 box3 4 2 1
20-02-05 box3 5 2 1
20-02-06 box3 7 2 1
</code></pre>
<p>The A,B,C columns represents cumulative val... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a> to group the dataframe by <code>code</code>, then using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.G... | python|pandas|numpy|dataframe | 1 |
14,790 | 62,170,233 | Combining two Pandas DataFrames to a three-dimensional np.array | <p>I need to concatinate two pandas DataFrames to a threedimensional np.array. For example these DataFrames </p>
<pre><code>df1 = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4,5,6]})
df2 = pd.DataFrame({'col1': [10, 20, 30], 'col2': [40,50,60]})
</code></pre>
<p>should be concatinated to the np.array <code>[[[1,10],[2... | <p>This should do the trick</p>
<pre><code>result = np.array([np.transpose(i) for i in zip(df1.to_numpy().T, df2.to_numpy().T)])
</code></pre> | python|arrays|pandas|numpy|dataframe | 1 |
14,791 | 62,351,943 | Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory | <p>I am doing a Docker build in mt computer where NVDIA GPU is not available. I use tensorflow/tensorflow Docker image as the base image with CPU.</p>
<p>Dockerfile</p>
<pre><code>FROM tensorflow/tensorflow
WORKDIR /project
COPY /app .
RUN python3 main.py
</code></pre>
<p>But it shows an error</p>
<pre><code>2020-... | <p>i am using tensorflow serving and meet this problem, and i find TFS dockerfile.gpu base on docker image nvidia/cuda,so, after install nvidia-docker, solved this problem. hope this may help you.</p> | docker|tensorflow | 0 |
14,792 | 62,245,074 | How to convert dict to dataframe correctly? | <p>This is the list of dictionary i've got guys :</p>
<pre><code>[{'id': 1816, 'name': 'Constantin Gâlcă', 'nickname': None, 'dob': '1972-03-08', 'country': {'id': 187, 'name': 'Romania'}}]
[{'id': 793, 'name': 'Luis Enrique Martínez García', 'nickname': 'Luis Enrique', 'dob': None, 'country': {'id': 214, 'name': 'Spa... | <p>Pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer">json_normalize</a> could help to reshape your data into your expected output : </p>
<pre><code>from pandas import json_normalize
json_normalize(data)
id name nic... | python|pandas|dataframe|series | 1 |
14,793 | 51,234,314 | Google BigQuery API Python | <p>I am trying to generate queries in python and querying with them. I am working with pandas_gbq. My code looks like this:</p>
<pre><code>def generate_query(
filter=['CENTRAL BANK','DRAGHI','FRANKFURT'],
date ='20171214',
datetimeformat='%Y%m%d',
weekly_data=True
):
filter = str(filter).replace('[... | <p>I believe your issue is with the date format. Unless you specify otherwise standard BQ expects yyyy-mm-dd format. Read more <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#date-functions" rel="nofollow noreferrer">here</a>. If you use <code>strftime("%Y-%m-%d")</code> t... | python|pandas|google-bigquery | 2 |
14,794 | 48,109,723 | Using TFLearn's Trainer causes a Recursion Error for Bidirectional RNN | <p>I followed the <a href="https://github.com/tflearn/tflearn/blob/master/examples/extending_tensorflow/trainer.py" rel="nofollow noreferrer">example</a> in using TFLearn's Trainer class to be able to train your own models not covered by TFLearn. Thus me having this code:</p>
<pre><code>import dataset_utils
import ten... | <p>I've addressed the recursion error. Apparently, the <code>label_error_rate</code> metric is causing the error, so I removed that one. Now I'm left with this error:</p>
<p><a href="https://stackoverflow.com/questions/48143243/tensorflow-typeerror-only-integer-scalar-arrays-can-be-converted-to-a-scalar-in">Tensorflow... | tensorflow | 0 |
14,795 | 48,027,341 | Getting iterator handle in MonitoredTrainingSession | <p>I want to try out <code>MonitoredTrainingSession</code>, but I also use several Dataset objects for train and validation sets. And to select the correct one, as the <a href="https://www.tensorflow.org/programmers_guide/datasets#creating_an_iterator" rel="nofollow noreferrer">manual</a> suggests I use string handles.... | <p>I found an answer to my question. The idea is that I have to give up with using handles and instead create several iterator initializers (per each dataset).</p>
<p>The solution can look as follows:</p>
<pre><code>import tensorflow as tf
dataset_a = tf.data.Dataset.range(10)
dataset_b = tf.data.Dataset.range(20, 2... | python|tensorflow | 0 |
14,796 | 48,364,407 | if False not in pandas series of Boolean values | <p>I'm new to python and I have found tons of my questions have already been answered. In 7 years of coding various languages, I've never actually posted a question on here before, so I'm really stumped this time.</p>
<p>I'm using python 3.6</p>
<p>I have a pandas dataframe with a column that is just Boolean values. ... | <p>It's not directly what you're asking but you can use .all() on a boolean series to determine if all values are true. Something like:</p>
<pre><code>if df["column_name"].all():
#do something
</code></pre> | python|pandas|if-statement|boolean|logic | 2 |
14,797 | 48,672,540 | Select rows with interval | <p>I have a wide Pandas dataframe with TimeIndexed values and I wanted to select with an Interval object that I made:</p>
<pre><code>inter = pd.Interval(pd.Timestamp('2017-12-05 16:36:17'),
pd.Timestamp('2017-12-05 22:00:00'), closed='left')
</code></pre>
<p>I tried loc and iloc method but they do... | <p><strong>Setup</strong> </p>
<pre><code>s = pd.Series(
pd.date_range('2017-12-05 16:00:00', '2017-12-05 23:00:00', freq='H')
)
s
0 2017-12-05 16:00:00
1 2017-12-05 17:00:00
2 2017-12-05 18:00:00
3 2017-12-05 19:00:00
4 2017-12-05 20:00:00
5 2017-12-05 21:00:00
6 2017-12-05 22:00:00
7 2017-12-0... | python|pandas|dataframe|intervals | 3 |
14,798 | 48,551,158 | Keras' predict_generator not returning correct number of samples | <p>I'm trying to implement a custom data generator that reads data from csv file(s) in chunks using <code>pandas.read_csv</code>. I tested it with <code>model.predict_generator</code> but the number of predictions returned is less than expected (in my case, 248192 out of 253457).</p>
<p>Custom generator</p>
<pre><cod... | <p>Well, this is tricky. So let's dive into the problem:</p>
<ol>
<li><p><strong>How <code>fit_generator</code> works when batch provided is less than <code>batch_size</code></strong>: As you may see - many batches you provide to <code>fit_generator</code> are of the size less than <code>batch_size</code>. This happen... | python|pandas|tensorflow|keras | 6 |
14,799 | 48,769,103 | Installing Tensorflow with Anaconda3 - Python 3 - Windows raises exception | <p>I am trying to install Tensorflow but I am getting an exception.</p>
<p>My PC runs Windows and has Python 3 installed through Anaconda 3.</p>
<p>The output is the following:</p>
<p><a href="https://i.stack.imgur.com/NworP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NworP.jpg" alt="enter image ... | <p>Thank you. I run the code as an administrator and the problem was resolved</p> | python|tensorflow|anaconda | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.