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 |
|---|---|---|---|---|---|---|
8,200 | 47,507,799 | Selecting a subset of columns without copying | <p>I would like to select a subset of columns from a DataFrame without copying the data. From <a href="https://stackoverflow.com/questions/23296282/what-rules-does-pandas-use-to-generate-a-view-vs-a-copy">this answer</a> it seems that it's impossible, if the columns have different dtypes. Can anybody confirm? For me, i... | <p>This post is only applicable for dataframes having same dtypes across all columns.</p>
<p>It is possible if the columns to be selected are at regular strides from each other using slicing within <code>.iloc</code>. As such selecting any two columns is always possible, but for more than two columns, we need to have ... | python|pandas|dataframe|indexing | 2 |
8,201 | 47,440,077 | Checking if particular value (in cell) is NaN in pandas DataFrame not working using ix or iloc | <p>Lets say I have following <code>pandas</code> <code>DataFrame</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"A":[1,pd.np.nan,2], "B":[5,6,0]})
</code></pre>
<p>Which would look like:</p>
<pre><code>>>> df
A B
0 1.0 5
1 NaN 6
2 2.0 0
</code></pre>
<h2>First option</h2>
<p>I k... | <p>Try this:</p>
<pre><code>In [107]: pd.isnull(df.iloc[1,0])
Out[107]: True
</code></pre>
<hr>
<p><strong>UPDATE:</strong> in a newer Pandas versions use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.isna.html" rel="noreferrer">pd.isna()</a>:</p>
<pre><code>In [7]: pd.isna(df.iloc[1,0]... | python|pandas|dataframe|nan | 127 |
8,202 | 68,180,717 | A fast alternative to pandas groupby + apply? | <p>I have a pandas dataframe which looks like the following (with ~ 1 Million lines):</p>
<pre><code>Column_1 Column_2 Column_3 Column_4 Column_5 Column_6 Column_7 Column_8 Column_9 Column_10
… … … … … … … … … ... | <p>Looks like you want to compare the values of 2 different columns in each row and then tally the results of the row by row comparisons, then do math on the tallies. If so, make 2 new columns that have the results of the comparisons, then sum those new columns and compare the numbers. Vectorization rather than itera... | python|pandas|numpy|vectorization | 0 |
8,203 | 59,138,585 | Plotting Vasicek Model. Only size -1 arrays can be converted to python scalars | <p>Attempting to the plot Vasiceks Portfolio loss distribution and when I want to build an array of numbers for x between 0 and 1 for each time step I am having problems. </p>
<pre><code>x.astype(int)
x = np.arange(0.000001, 1, 0.000001)
a1 = math.sqrt((1-rho)/rho)
a2 = -1/(2*rho)*((math.sqrt(1-rho)*norm.ppf(x)-norm.... | <p>math.exp works only on scalar inputs but you're passing an array as an input. You should use numpy.exp since it accepts an array as input. </p>
<p>Reference : <code>https://docs.scipy.org/doc/numpy/reference/generated/numpy.exp.html</code></p> | python|numpy|plot | 0 |
8,204 | 59,395,680 | GPU memory doesn't get freed up after evaluating data on PyTorch model in parallel process | <p>For my optimization algorithm, I need to evaluate a few hundred images every iteration. To speed up the process, I wanted to take full advantage of my 3 GPUs.</p>
<p>My process:</p>
<ul>
<li>Load an instance of my deep learning model on each one of my GPUs</li>
<li>Then split the workload into as many parts as I h... | <p>I found this similar <a href="https://stackoverflow.com/questions/46561124/python-multithreading-in-infinite-loop">thread</a> where the memory leakage occurs due to the instantiation of the Pool() in the loop, rather than outside.</p>
<p>The above problem also instantiates the Pool() inside the function without usi... | python-3.x|pytorch|python-multiprocessing | 0 |
8,205 | 45,042,005 | Python/Pandas return column and row index of found string | <p>I've searched previous answers relating to this but those answers seem to utilize numpy because the array contains numbers. I am trying to search for a keyword in a sentence in a dataframe ('Timeframe') where the full sentence is 'Timeframe for wave in ____' and would like to return the column and row index. For exa... | <p>EDIT:</p>
<p>For check index need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>contains</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean inde... | python-3.x|pandas | 4 |
8,206 | 57,169,473 | why does groupby function returns duplicated data | <p>I am testing pandas.groupby function and have generated a random dataframe</p>
<p><code>df = pd.DataFrame(np.random.randint(5,size=(6,3)), columns=list('abc'))</code></p>
<p>in a random case df is:</p>
<pre><code> a b c
0 2 2 2
1 1 4 2
2 3 0 1
3 2 1 3
4 0 2 2
5 2 1 4
</code></pre>
<p>when I... | <p><code>DataFrame.groupby.apply</code> evaluates the first group twice to determine whether a <em>fast path for calculation</em> can be followed for the remaining groups. This behavior has changed in recent versions of <code>pandas</code> as discussed <a href="https://github.com/pandas-dev/pandas/pull/24748" rel="nof... | python|pandas|pandas-groupby | 2 |
8,207 | 56,923,659 | Stacking np.tril and np.triu together | <p>I have two correlation matrices, one which has the lower triangle as <code>NaN</code> values, and the other one that has its upper triangle as 'NaN' values.</p>
<p>I would like to stack them together, so I would end up with a NxN matrix with correlation coefficients.</p>
<p>I tried using <code>pd.concat()</code>, ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>DataFrame.fillna</code></a> for replace missing values by another <code>DataFrame</code>:</p>
<pre><code>df = df1.fillna(df2)
</code></pre>
<p>Or use <a href="http://pandas.pydata.or... | python|pandas|numpy|dataframe | 2 |
8,208 | 23,200,524 | Propagate pandas series metadata through joins | <p>I'd like to be able attach metadata to the series of dataframes (specifically, the original filename), so that after joining two dataframes I can see metadata on where each of the series came from.</p>
<p>I see github issues regarding <code>_metadata</code> (<a href="https://github.com/pydata/pandas/issues/6323" re... | <p>I think something like this will work (and if not, pls file a bug report as this, while supported is a bit bleading edge, iow it IS possible that the join methods don't call this all the time. That is a bit untested).</p>
<p>See this <a href="https://github.com/pydata/pandas/issues/6923" rel="nofollow">issue</a> fo... | python|pandas|metadata | 5 |
8,209 | 35,343,795 | How get ranges of one column gruop by class column? In Pandas | <p>I'm practicing with Pandas and i want to get the ranges of a column from a dataframe by the values of another column.</p>
<p>An example dataset: </p>
<pre><code> Points Grade
1 7.5 C
2 9.3 A
3 NaN A
4 1.3 F
5 8.7 B
6 9.5 A
7 7.9 ... | <p>You can first filter <code>df</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="nofollow"><code>notnull</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.groupby.html" rel="nofollow"><code>groupby</code></a> and ... | python-3.x|pandas|data-analysis | 1 |
8,210 | 51,081,439 | Is the usage of on-line data augmentation a fair comparison between CNN models | <p>I am using on-line data augmentation of images I feed into my Convolutional Neural Network. I am using the Keras ImageDataGenerator for this. The images are augmented in each batch and then the model is trained on these images.</p>
<p>I am comparing different models, but since the images are augmented on the fly, i... | <p>If I understand you correct you are wondering whether the randomness caused by the data augmentation affects the result?</p>
<p>The randomness of the augmentation does not affect the result (at least not to a degree that makes a difference anyway) if you train long enough. The other options you have are (as I think... | python|tensorflow|machine-learning|keras|convolutional-neural-network | 2 |
8,211 | 50,721,847 | Tensorflow: cannot extract filename from tfrecord | <p>I have written an image, label and filename to a tfrecords file. When I try to decode the file, I cannot convert the filename to a string from tf.string.</p>
<p>The code I wrote to convert it to a tfrecords file:</p>
<pre><code>num_batches = 6
batch_size = math.ceil(X_training.shape[0] / num_batches)
for i in ran... | <p>Calling <code>.decode().replace('\x00', '')</code> on your bytestring produces 'P_00148_RIGHT_MLO.jpg'.</p>
<p>Adding the decode and replace in the function return should solve your problem.</p> | python|string|tensorflow|machine-learning|deep-learning | 1 |
8,212 | 50,767,043 | Dask Dataframe - multiple rows from each row | <p>I have this dask dataframe that has two columns, one of which contains tuples (or arrays). What I want is to have a new dataframe that has a row for each element of the tuple in each row.</p>
<p>An example dataframe can be constructed like this:</p>
<pre><code>import pandas as pd
import dask.dataframe as dd
tmp = ... | <p>You can transform the dataframe <code>tmp</code> in the shape you want by doing:</p>
<pre><code>tmp_2 = (tmp.set_index('name')['content']
.apply(pd.Series).stack().astype(int)
.reset_index().drop('level_1',1).rename(columns={0:'content'}))
</code></pre>
<p>and then create your ddf the same... | python|pandas|dataframe|dask | 1 |
8,213 | 50,915,906 | Pandas dataframe `apply` to `dtype` generates unexpected results | <h1>Example</h1>
<p>Toy dataframe:</p>
<pre><code>>>> df = pd.DataFrame({'a': ['the', 'this'], 'b': [5, 2.3], 'c': [8, 11], 'd': ['the', 7]})
</code></pre>
<p>yields:</p>
<pre><code>>>> df
a b c d
0 the 5.0 8 the
1 this 2.3 11 7
</code></pre>
<p>and:</p>
<pre><code>>... | <p>You can use <code>result_type='expand'</code> in <code>.apply()</code> With that, list-like results will be turned into columns. You can read more in the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer">docs</a>:</p>
<pre><code>df.apply(lambda x:... | python|pandas|dataframe | 2 |
8,214 | 50,990,523 | How to design a Tensorflow Js model for a single output MLP? | <p>I am trying to implement and test a single output MLP using Tensorflow Js where my data looks like this:</p>
<p><code>dataset = [[x_1, x_2, ..., x_n, y], ...]</code></p>
<p>Here is my code:</p>
<pre><code> for (var i = 0; i < dataset.length; ++i) {
x[i] = dataset[i].slice(0, inputLength);
... | <p>The dimension of the x/y-tensors used in <code>model.fit()</code> has to be one more than the shape of the first/last layer of the model to represent multiple training data sets so GPU-accelerated batch training is possible.</p>
<p>Another problem of your model is the high <code>learningRate</code> (in relation to ... | node.js|neural-network|tensorflow.js | 1 |
8,215 | 66,726,183 | How do I stop decimals changing to integers when replacing the numbers of a row in an array? | <p>I'm trying to replace the 0th row of array "A" with 0.5 times the 1st row plus the original 0th row with the code below:</p>
<pre><code>A = np.array([[ 9, 6, 7, 8, 1, 7, 2], [ 8, 2, 6, 5, 1, 5, 3], [ 7, 3, 1, 4, 5, 10, 1],
[10, 5, 7, 5, 4, 6, 2], [ 5, 5, 2, 6, 4, 2... | <p>The problem is <code>A</code>'s original <code>dtype</code> is <code>int</code>, then every value in it is and will be an <code>int</code>. To fix it, you can specify <code>dtype = float</code> from the beginning:</p>
<pre><code>A = np.array([[ 9, 6, 7, 8, 1, 7, 2],
[ 8, 2, 6, 5, 1, 5, 3],
... | python|numpy | 2 |
8,216 | 66,379,396 | pandas data frame plotting in subplots | <p>I have the following pandas data frame and would like to create <code>n</code> plots horizontally where n = unique labels(l1,l2,.) in the <code>a1 row</code>(for example in the following example there will be two plots because of <code>l1 and l2</code>). Then for these two plots, each plot will plot <code>a4</code> ... | <p>I do not see any way of avoiding a for loop when plotting this data with pandas. My initial thought was to reshape the dataframe to make <code>subplots=True</code> work, like this:</p>
<pre><code>dfp = df.pivot(columns='a1').swaplevel(axis=1).sort_index(axis=1)
dfp
</code></pre>
<p><a href="https://i.stack.imgur.com... | python|pandas|dataframe|matplotlib|plot | 1 |
8,217 | 16,110,252 | Need to compare very large files around 1.5GB in python | <pre><code>"DF","00000000@11111.COM","FLTINT1000130394756","26JUL2010","B2C","6799.2"
"Rail","00000.POO@GMAIL.COM","NR251764697478","24JUN2011","B2C","2025"
"DF","0000650000@YAHOO.COM","NF2513521438550","01JAN2013","B2C","6792"
"Bus","00009.GAURAV@GMAIL.COM","NU27012932319739","26JAN2013","B2C","800"
"Rail","0000.ANU@G... | <p>make sure you have 0.11, read these docs: <a href="http://pandas.pydata.org/pandas-docs/dev/io.html#hdf5-pytables" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/dev/io.html#hdf5-pytables</a>, and these recipes: <a href="http://pandas.pydata.org/pandas-docs/dev/cookbook.html#hdfstore" rel="nofollow n... | python|csv|numpy|pandas|large-data-volumes | 8 |
8,218 | 57,677,834 | How to combine input with output tensors to create a recurrent layer? | <p>I'm trying to change a layer that calculates an output with ny outputs to a layer that calculates a recurrent output so the output has the same shape as the input. For example, consider the following</p>
<pre><code>nt = 1000
nx_in = 8
ny = 2
x_train = np.array(shape=(nt, nx_in))
input = keras.Input(shape=(1, None,... | <p>The Tensorflow "graph" is a Directed Acyclic Graph of computations. The backpropagation algorithm walks this graph backwards, and prediction walks it forwards.</p>
<p>My understanding is that you are trying to introduce a cycle into the graph. This will not work.</p>
<p>If you start from a basic implementation of ... | python|tensorflow|keras|recurrent-neural-network|tensor | 0 |
8,219 | 57,404,966 | Pandas column names begin from index column when running on visual code jupyter environment | <p><a href="https://i.stack.imgur.com/HZhwL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HZhwL.png" alt="enter image description here"></a></p>
<p>I have written a very simple code that creates a pandas data frame. The issue is when I do my column naming ['X','Y'], my column heading X passes itse... | <p>It's the default of the plugin and affects only visually... does not affect the functionallity</p>
<p><img src="https://i.imgur.com/gO37X1l.png" alt="example"></p> | python-3.x|pandas|visual-studio-code|jupyter-notebook | 1 |
8,220 | 57,401,767 | Assigning new column value to data frame based on if time series data matches functional constraint | <p>I have the time series of a set of data for different samples. I would like to add a new column stating if the sample falls within a minimum and maximum constraint. If it does, I will assign the value 1 to the column, otherwise 0.</p>
<p>The example data frame I am using is below. The minimum constraint has the for... | <p>First, tidy your data.</p>
<pre><code>tidy = pd.wide_to_long(df, stubnames='time', i='sample', j='x', sep='=') \
.reset_index().rename(columns={'time': 'value', 'x': 'time'})
# I made the choice to do some renaming to make it clearer what vars are what
</code></pre>
<p>Yield this sort of DataFrame (truncated):... | python|pandas | 0 |
8,221 | 57,638,682 | question how to deal with KeyError: 0 or KeyError: 1 etc | <p>I am new in python and this data science world and I am trying to play with different datasets. </p>
<p>In this case I am using the housing price index from quandl but unfortunately I get stuck when when I need to take the abbreviations names from the wiki page always getting the same Error KeyError.</p>
<pre><cod... | <p>Note that <code>fifty_states</code> is a <strong>list</strong> of DataFrames, filled with
content of tables from the source page.</p>
<p>The first of them (at index <em>0</em> in <em>fifty_states</em>) is the table of US states.</p>
<p>If you don't know column names in a DataFrame (e.g. <em>df</em>),
to get column... | python|pandas|quandl | 0 |
8,222 | 57,591,096 | Reshaping data and seperation by multiple delimiters | <p>Sorry but I need some help with pandas data wrangling.
I have a large dataset in excel. Each cell contains data from several days. I have loaded the data with pandas, but I haven't found a desirable way of separating it into individual cells.
The format is "Date" space dash space "value" Pipe and repeated as such ... | <p>Basic idea is to parse the information in your <code>WBC</code> column and then create the new columns as required:</p>
<pre><code>import pandas as pd
data={'ID': ['1'],
'WBC': ["20100205 - 0.10 |20100205 - 0.16 |20100205 - 0.21 |20100305 - 71.69 |20100306 - 0.27 |20100306 - 0.42 |20100306 - 1.42"]
... | python|pandas | 1 |
8,223 | 24,234,034 | Pandas: import csv with user corrected faulty values | <p>I try to import a csv and dealing with faulty values, e.x. wrong decimal seperator or strings in int/double columns. I use converters to do the error fixing. In case of strings in number columns the user sees a input box where he has to fix the value. Is it possible to get the column name and/or the row which is act... | <p>I would take a different approach here.<br>
Rather than at read_csv time, I would read the csv naively and <strong>then</strong> fix / convert to float:</p>
<pre><code>In [11]: df = pd.read_csv(csv_file, sep=';')
In [12]: df['elevation']
Out[12]:
0 -10
1 10,0
2 35.5
3 30x
Name: elevation, dtype: obje... | python|csv|pandas|user-input|converters | 0 |
8,224 | 43,698,479 | pandas dataframe merge overlapping keys | <p>I have two dataframes, left and right. The keys (columns) of right are a subset of those in left. I want to to keep the column data from right and put in left, and I don't care about the overlapping key data in the left:</p>
<pre><code>left = pd.DataFrame({'key1': ['Knan', 'Knan', 'Knan', 'Knan'],
... | <p>IIUC, you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow noreferrer"><code>combine_first</code></a>:</p>
<pre><code>df_out = right.combine_first(left)
print(df_out)
</code></pre>
<p>Output:</p>
<pre><code> A B key1 key2
0 A0 B0 K0 ... | python|pandas|dataframe | 0 |
8,225 | 43,481,710 | select first occurance of minimum index from numpy array | <p>I am trying to find out the index of the minimum value in each row and I am using below code.</p>
<pre><code>#code
import numpy as np
C = np.array([[1,2,4],[2,2,5],[4,3,3]])
ind = np.where(C == C.min(axis=1).reshape(len(C),1))
ind
#output
(array([0, 1, 1, 2, 2], dtype=int64), array([0, 0, 1, 1, 2], dtype=int64))
<... | <p>If you want to use comparison against the minimum value, we need to use <code>np.min</code> and keep the dimensions with <code>keepdims</code> set as <code>True</code> to give us a boolean array/mask. To select the first occurance, we can use <code>argmax</code> along each row of the mask and thus have our desired o... | python|python-2.7|python-3.x|numpy|scipy | 3 |
8,226 | 73,035,536 | Pytorch CUDA not available with correct versions | <p>I really need help setting up CUDA for development with Pytorch. I have a Nvidia graphics card and am using Python 3.8. To install pytorch with the correct CUDA integration I ran <code>conda install pytorch torchvision cudatoolkit=10.1 -c python</code>. The problem is that <code>torch.cuda.is_available()</code> alwa... | <p>As in the <a href="https://pytorch.org/" rel="nofollow noreferrer">PyTorch</a> website, install with <code>conda install pytorch torchvision cudatoolkit=11.3 -c pytorch</code> or <code>conda install pytorch torchvision cudatoolkit=11.6 -c pytorch</code></p> | python|pytorch|gpu | 0 |
8,227 | 73,048,449 | Python: Read Json and create chart | <p>I have a json file:</p>
<pre><code>{
"code":"200000",
"data":[
{
"price":"1001",
"sequence":"1636607335665",
"side":"sell",
"size":"0.00000544",
"time":1... | <p>You can read the dictionary data into a dataframe.</p>
<pre><code>df = pd.DataFrame(data_dict)
df = df['data'].apply(pd.Series)
</code></pre>
<h4>Filtering data</h4>
<pre><code>df_plot = pd.concat([df.loc[df.side.eq('buy'), ['price']].reset_index(drop=True), df.loc[df.side.eq('sell'), ['price']].reset_index(drop=Tru... | python|json|pandas|matplotlib | 1 |
8,228 | 73,133,796 | Removing pandas rows based on existence of values in certain columns | <p>I have a df like so:</p>
<pre><code>A B C
f s x
a b c
n
p l k
i
s j p
</code></pre>
<p>Now, I want to remove all the records that have the value in column A but are empty on the rest of df's columns, how can I achieve such a thing? The expected result would be a df like:</p>
<pre><code>A B C
f s x
a b c
p l k
s j p
... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferrer"><code>DataFrame.replace</code></a> in order to set blanks to NaN, then you can remove rows with NaN with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dropna.html" rel="nofollow ... | python|pandas|dataframe | 1 |
8,229 | 10,545,957 | creating pandas data frame from multiple files | <p>I am trying to create a pandas <code>DataFrame</code> and it works fine for a single file. If I need to build it for multiple files which have the same data structure. So instead of single file name I have a list of file names from which I would like to create the <code>DataFrame</code>.</p>
<p>Not sure what's the ... | <p>The pandas <code>concat</code> command is your friend here. Lets say you have all you files in a directory, targetdir. You can:</p>
<ol>
<li>make a list of the files </li>
<li>load them as pandas dataframes </li>
<li>and concatenate them together</li>
</ol>
<p>`</p>
<pre><code>import os
import pandas as pd
#l... | python|pandas | 38 |
8,230 | 10,625,096 | Extracting first n columns of a numpy matrix | <p>I have an array like this:</p>
<pre><code> array([[-0.57098887, -0.4274751 , -0.38459931, -0.58593526],
[-0.22279713, -0.51723555, 0.82462029, 0.05319973],
[ 0.67492385, -0.69294472, -0.2531966 , 0.01403201],
[ 0.41086611, 0.26374238, 0.32859738, -0.80848795]])
</code></pre>
<p>Now... | <p>If <code>a</code> is your array:</p>
<pre><code>In [11]: a[:,:2]
Out[11]:
array([[-0.57098887, -0.4274751 ],
[-0.22279713, -0.51723555],
[ 0.67492385, -0.69294472],
[ 0.41086611, 0.26374238]])
</code></pre> | python|numpy | 93 |
8,231 | 70,696,514 | Add IDs to dataframe with random Noise | <p>My initial dataframe looks as follows:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
"id":[1,1,1,1,2,2],
"time": [1,2,3,4,5,6],
"x": [1,2,3,4,9,11 ],
"y": [5,6,7,8,3,2],
})
</code></pre>
<p>So I have two IDs (1 and 2) or two different time series.
Now I wan... | <p>You can build a new dataframe and concat them:</p>
<pre><code>df1 = pd.concat([df['id'] + df['id'].max(),
df['time'] + df['time'].max(),
df['x'] + np.random.normal(0, 1, len(df)),
df['y'] + np.random.normal(0, 1, len(df))], axis=1) \
.set_index(df.index + le... | python|pandas|dataframe|numpy | 1 |
8,232 | 70,529,611 | Anytree to Pandas or tuple conversion with node members as indices | <p>I'd like to build a pandas dataframe or tuple from an anytree object, where each node has a list attribute of members:</p>
<pre><code>from anytree import Node, RenderTree, find_by_attr
from anytree.exporter import DictExporter
from collections import OrderedDict
import pandas as pd
import numpy as np
tree = Node('T... | <p>The answer turned out easier than I thought.
First grab all the end nodes using anytree's <code>findall()</code></p>
<pre><code>endnodes = anytree.findall(tree, filter_=lambda node: len(node.children)==0)
</code></pre>
<p>This returns a list of nodes, easier to work with in this case than anytree's OrderedDict con... | python|pandas|anytree | 0 |
8,233 | 70,703,038 | NoneType Object is not callable - Python/CNN | <p>Friends, I am new at this. Can you please help me understand why this code:</p>
<pre><code>#Construct the model
model_simple = Sequential()
model_simple.add(Conv2D(strides = 1, kernel_size = 3, filters = 12, use_bias = True, bias_initializer = tf.keras.initializers.RandomUniform(minval=-0.05, maxval=0.05) , padding ... | <p>you must build your model before training. E.g.</p>
<pre><code>batch = 32
height = 32
width = 32
channels = 3
inputShape = (batch, height, width, channels)
model_simple.build(inputShape)
model_simple.fit(imgs_for_input, imgs_for_output, epochs=3)
</code></pre> | python|tensorflow|keras|deep-learning|neural-network | 0 |
8,234 | 70,566,442 | Exchange certain values in different size vectors | <p>I got a problem where I cant exchange values in an array. I've got 2 arrays, one filled with <em>zeros</em> and <em>ones</em>, for example: <code>disp = [[0.], [0.], [0.], [1.], [1.], [1.], [1.], [0.], [0.], [0.]]</code> and the other one filled with values I would like to implement at the place where the <em>ones</... | <p>One way to do it:</p>
<pre><code>iterator = iter(to_replace_at_1)
[x if x[0] != 1 else next(iterator) for x in disp]
</code></pre> | python|numpy|replace | 1 |
8,235 | 70,643,623 | Python dataframe Renaming two columns into one | <p>The dataframe below has two names for one. The dataframe is of type "column.pandas.core.indexes.multi.MultiIndex"
This is what list for the data frame looks like</p>
<pre><code>[('caption', ''),
('', ''),
('tackles', 'TOT'),
('tackles', 'SOLO'),
('tackles', 'SACKS'),
('tackles', 'TFL'),
('misc', 'PD'),
('m... | <p>IIUC:</p>
<pre><code>df.columns = df.columns.to_flat_index().map('_'.join)
print(df.columns)
# Output
Index(['caption_', '_', 'tackles_TOT', 'tackles_SOLO', 'tackles_SACKS',
'tackles_TFL', 'misc_PD', 'misc_QB HTS', 'misc_TD',
'misc_Unnamed: 8_level_1', 'gameid_'],
dtype='object')
</code></pre>
<... | python|python-3.x|pandas | 2 |
8,236 | 70,716,325 | How do I loop variable names based on values in a list | <p>I have this list with five heights in it and I want to put it in a loop to create five separate dataframes indexed by these numbers. This would include creating a column name based on different height, reading a csv file and assigning the colNames to it, and finally dropping the unused columns. I have multiple block... | <p>Trying to name separate DataFrames in this way is a bit unwieldy in Python, but here is how I might go about writing a loop for the problem you pose:</p>
<pre class="lang-py prettyprint-override"><code>dflist = []
for num, height in enumerate(['0', '5', '15', '25', '50']):
dflist.append(pd.read_csv('test{}.csv'... | python|pandas|dataframe|while-loop | 2 |
8,237 | 70,550,806 | What is a good way to implement a function to make an array with inputted arguments? | <p>I would like to make a function that accepts any number of arguments and returns an array using those arguments as parameters. Here's the code example - I would like to do something like this, except it should work:</p>
<pre><code>import numpy as np
def getgoodarray(*args):
goodarray = np.round(np.arange(args)*... | <p>Use any method that builds an array, fill with zeros, ones or random</p>
<pre><code>def getgoodarray(*args):
return np.ones(args)
# return np.zeros(args)
# return np.random.randint(0, 10, args)
</code></pre>
<pre><code>x = getgoodarray(2, 3)
[[7 7 1]
[8 2 5]]
</code></pre>
<pre><code>x = getgoodarray(... | python|arrays|numpy | 2 |
8,238 | 70,697,704 | How to convert dataframe into numpy array? | <p>So I am currently making a neural network MLP (Multi-layer-Perceptron) on group classification on sea turtle speed between beach to sea on the seconds unit, and it looks somewhat like this.</p>
<p><a href="https://i.stack.imgur.com/UQgxe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UQgxe.png" a... | <p>Pandas dataframe is a two-dimensional data structure to store and retrieve data in rows and columns format.</p>
<p>You can convert pandas dataframe to numpy array using the <code>df.to_numpy()</code> method.</p>
<p>You can use the below code snippet to convert pandas dataframe into numpy array.</p>
<pre><code>numpy_... | python|arrays|pandas|numpy | 0 |
8,239 | 70,589,997 | Keras loss: 0.0000e+00 and accuracy stays constant | <p>I have 101 folders from 0-100 containing synthetic training images.
This is my code:</p>
<pre><code>dataset = tf.keras.utils.image_dataset_from_directory(
'Pictures/synthdataset5', labels='inferred', label_mode='int', class_names=None, color_mode='rgb', batch_size=32, image_size=(128,128), shuffle=True, seed=None, v... | <p>So turns out your loss might be the problem after all.
If you use SparseCategoricalCrossentropy instead as loss it should work.</p>
<pre><code>model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
</code></pre>
<p>Afte... | python|tensorflow|machine-learning|keras|deep-learning | 0 |
8,240 | 42,664,045 | Creating a 3d matrix with pandas panel | <p>My goal is to create a pandas panel, I currently have a csv, with the sample as follows:</p>
<pre><code>Year From country To country Points
2005 Albania Albania 0
2005 Albania Bosnia & Herzegovina 0
2005 Albania Croatia 2
2005 Albani... | <p>Format your dataframe where the index is a multiindex with two levels. Using the method <code>to_panel</code> will assume the <code>Items</code> is in the columns, <code>Major_axis</code> is in the first level of the index, and <code>Minor_axis</code> is in the second level of the index.</p>
<pre><code>df.set_inde... | python|csv|pandas | 0 |
8,241 | 26,922,284 | Filling gaps for cumulative sum with Pandas | <p>I'm trying to calculate the inventory of stocks from a table in monthly buckets in Pandas. This is the table:</p>
<pre><code>Goods | Incoming | Date
-------+------------+-----------
'a' | 10 | 2014-01-10
'a' | 20 | 2014-02-01
'b' | 30 | 2014-01-02
'b' | 40 | 2014-05-13... | <p>I think you want to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tools.pivot.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p>
<pre><code>In [11]: df.pivot_table(values="incoming", index="month", columns="goods", aggfunc="sum")
Out[11]:
goods a b c
month
1 0... | python|pandas|time-series|cumsum | 2 |
8,242 | 39,353,758 | pandas pivot table of sales | <p>I have a list like below:</p>
<pre><code> saleid upc
0 155_02127453_20090616_135212_0021 02317639000000
1 155_02127453_20090616_135212_0021 00000000000888
2 155_01605733_20090616_135221_0016 00264850000000
3 155_01072401_20090616_135224_0010 02316877000000
4 155_010... | <p><strong><em>Option 1</em></strong></p>
<pre><code>df.groupby(['saleid', 'upc']).size().unstack(fill_value=0)
</code></pre>
<p><a href="https://i.stack.imgur.com/6yvfj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6yvfj.png" alt="enter image description here"></a></p>
<p><strong><em>Option 2</... | python|csv|pandas|numpy | 3 |
8,243 | 39,255,211 | TensorFlow iOS memory warnings | <p>We are building an iOS app to perform image classification using the TensorFlow library.</p>
<p>Using our machine learning model (91MB, 400 classes) and the TensorFlow 'simple' example, we get memory warnings on any iOS device with 1GB of RAM. 2GB models do not experience any warnings, while < 1GB models complet... | <p>You can use memory mapping, have you tried that? Tensorflow provides documentation. You can also round your weight values to even less decimal places. </p> | ios|memory|machine-learning|tensorflow | 0 |
8,244 | 39,278,163 | How to use validation monitor in Softmax classifier in tensorflow | <p>I just edit the <a href="http://mnist_softmax_classifier" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/r0.10/tensorflow/examples/tutorials/mnist/mnist_softmax.py</a> to enable logging by using a validation monitor </p>
<pre><code>from __future__ import absolute_import
from __future__ import di... | <p>I don't think there's an easy way to do that, since <code>ValidationMonitor</code> is a part of <code>tf.contrib</code>, e.g. contribution code that is not supported by the TensorFlow team. So unless you are using some higher-level API from <code>tf.contrib</code> (like <code>DNNClassfier</code>), you might not be a... | machine-learning|tensorflow|computer-vision|deep-learning|softmax | 1 |
8,245 | 39,083,686 | Printing Beta(Coef) alone from statsmodels OLS regression | <p>I am running the linear regression function on a time series data of two stocks using statsmodels. While printing out the results using "summary", my code works fine. However I want to print only the beta(coef) of the two stocks. I tried using "params" instead of "summary" in the lines, but I keep getting the error ... | <p>Use the below code</p>
<pre><code>results.params
</code></pre>
<p>instead of</p>
<pre><code>results.params()
</code></pre>
<p>and it will work properly.</p> | python-3.x|numpy|time-series|linear-regression|statsmodels | 2 |
8,246 | 19,666,029 | Efficient way to decompress and multiply sparse arrays in python | <p>In a database I have a compressed frequency array. The first value represents the full array index, and the second value represents the frequency. This is compressed to only non-0 values because it is pretty sparse - less than 5% non-0's. I am trying to decompress the array, and then I need the dot product of this a... | <p>You could use <code>scipy.sparse</code> to handle all that for you:</p>
<pre><code>>>> import scipy.sparse as sps
>>> cfq = np.array([(1,4),(3,2),(9,8)])
>>> cfq_sps = sps.coo_matrix((cfq[:,1], ([0]*len(cfq), cfq[:,0])))
>>> cfq_sps
<1x10 sparse matrix of type '<type 'numpy... | python|arrays|numpy|scipy|sparse-matrix | 2 |
8,247 | 19,719,746 | How can one efficiently remove a range of rows from a large numpy array? | <p>Given a large 2d numpy array, I would like to remove a range of rows, say rows <code>10000:10010</code> efficiently. I have to do this multiple times with different ranges, so I would like to also make it parallelizable.</p>
<p>Using something like <code>numpy.delete()</code> is not efficient, since it needs to cop... | <p>Because of the strided data structure that defines a numpy array, what you want will not be possible without using a masked array. Your best option might be to use a masked array (or perhaps your own boolean array) to mask the deleted the rows, and then do a single real <code>delete</code> operation of all the rows... | python|numpy | 3 |
8,248 | 19,761,140 | Calling Functions with Multiple Arguments when using Groupby | <p>When writing functions to be used with groupby.apply or groupby.transform in pandas if the functions have multiple arguments, then when calling the function as part of groupby the arguments follow a comma rather than in parentheses. An example would be:</p>
<pre><code>def Transfunc(df, arg1, arg2, arg2):
retur... | <p>Passing arguments to <code>apply</code> just happens to work, because <code>apply</code> passes on all arguments to the target function.</p>
<p>However, <code>groupby</code> takes multiple arguments, see <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.groupby.html?highlight=groupby#pand... | python|lambda|pandas | 2 |
8,249 | 12,950,024 | Add a column with a groupby on a hierarchical dataframe | <p>I have a dataframe structured like this:</p>
<pre><code>First A B
Second bar baz foo bar baz foo
Third cat dog cat dog cat dog cat dog cat dog cat dog
0 3 8 7 7 4 7 5 3 2 2 ... | <p>There definitely is a weakness in the API here but I'm not sure off the top of my head to make it easier to do what you're doing. Here's one simple way around this, at least for your example:</p>
<pre><code>In [20]: df
Out[20]:
First A B
Second foo ba... | python|group-by|pandas | 7 |
8,250 | 28,886,439 | Built in function in numpy to interpret an Integer as a numpy array with index = integer value set | <p>I am new to numpy and I am trying to avoid for-loops. My requirement is as below:</p>
<pre><code>Input - decimal value (ex. 3)
Output - Binary numpy array ( = 00000 01000)
</code></pre>
<p>Another example : </p>
<pre><code>Input = 6
Output = 00010 00000
</code></pre>
<p>Note: I do not want the binary representat... | <p>Try this instead. This doesn't use any for loops and if you add some sanity checks it should work fine.</p>
<pre><code>def oneOfK(label):
rows = label.shape[0];
rowsIndex=np.arange(rows,dtype="int")
oneKLabel = np.zeros((rows,10))
#oneKLabel = np.zeros((rows,np.max(label)+1))
oneKLabel[rowsIndex... | python|numpy | 2 |
8,251 | 33,712,638 | How to generate the unique id from a list of ids containing duplicates | <p>I am using pandas package to deal with my data, and I have a dataframe looks like below. </p>
<pre><code>data = pd.read_csv('people.csv')
id, A, B
John, 1, 3
Mary, 2, 5
John, 4, 6
John, 3, 7
Mary, 5, 2
</code></pre>
<p>I'd like to produce the unique id for those duplicates but keep the same order of them. </p>
<p... | <p>In order to obtain the indices you may use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html#pandas.core.groupby.GroupBy.cumcount" rel="nofollow"><code>GroupBy.cumcount</code></a>:</p>
<pre><code>>>> idx = df.groupby('id').cumcount()
>>> idx
0... | python|python-2.7|pandas | 2 |
8,252 | 33,737,596 | External access to pythonanywhere MySQL database with pandas and SQLAlchemy | <p>I want to use <code>pandas</code> to read data from my pythonanywhere MySQL database. <code>pandas</code> uses <code>sqlalchemy</code>.</p>
<p>The following doesn't work:</p>
<pre><code>import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('mysql://user:pass@user.mysql.pythonanywhere-serv... | <p>PythonAnywhere dev here. Unfortunately you can't connect to your PythonAnywhere database from outside the service. If you had a paid plan (which comes with SSH access) then you could do it <a href="https://help.pythonanywhere.com/pages/SSHTunnelling" rel="nofollow">by using SSH tunnelling</a> but that won't work f... | python|mysql|pandas|sqlalchemy|pythonanywhere | 2 |
8,253 | 22,482,003 | Value error, truth error, ambiguous error | <p>When using this code</p>
<pre><code> for i in range(len(data)):
if Ycoord >= Y_west and Xcoord == X_west:
flag = 4
</code></pre>
<p>I get this ValueError</p>
<p>if Ycoord >= Y_west and Xcoord == X_west:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a... | <p>The variables <code>Ycoord</code> and <code>Xcoord</code> are probably <code>numpy.ndarray</code> objects. You have to use the array compatible <code>and</code> operator to check all its values for your condition. You can create a flag array and set the values to <code>4</code> in all places where your conditional i... | python|arrays|numpy|python-2.6 | 1 |
8,254 | 62,046,431 | Python Dataframe: Get number of week days present in last month? | <p>I have <code>df</code> with column <code>day_name</code>. I'm trying to get number of week_days present in last month?</p>
<p>I'm trying to get number of week_days present in last month.</p>
<p>For ex: There are <code>4 Fridays</code> and <code>5 Thrusdays</code> in April </p>
<p>df</p>
<pre><code> d... | <p>For last month:</p>
<pre><code>year, month = 2020, 4
start,end = f'{year}/{month}/1', f'{year}/{month+1}/1'
# we exclude the last day
# which is first day of next month
last_month = pd.date_range(start,end,freq='D')[:-1]
df['last_month_count'] = df['day_name'].map(last_month.day_name().value_counts())
</code></p... | python|pandas|numpy|dataframe | 2 |
8,255 | 62,379,530 | does validation_data in model.fit() method in Tensorflow Keras have to be a tuple? | <p>I'm implementing a complicated loss function so I use a custom layer to pass the loss. Something like:</p>
<pre><code>class SIAMESE_LOSS(Layer):
def __init__(self, **kwargs):
super(SIAMESE_LOSS, self).__init__(**kwargs)
@staticmethod
def mmd_loss(source_samples, target_samples):
return ... | <p>to write your own loss you need to inherit from class Loss and then implement your loss calculation in the init and call methods.
<a href="https://www.tensorflow.org/api_docs/python/tf/keras/losses/Loss" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/losses/Loss</a></p>
<p>so you dont ... | python|tensorflow|keras|loss-function | 0 |
8,256 | 62,043,788 | Add values above bars on a bar chart in python | <p>I have the following code below: </p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
plt.figure()
languages =['Python', 'SQL', 'Java', 'C++', 'JavaScript']
pos = np.arange(len(languages))
popularity = [56, 39, 34, 34, 29]
bars = plt.bar(pos, popularity, align='center', linewidth=0, color='lightsla... | <p>You are almost there; You only need to change the last for loop to be like so:</p>
<pre><code>...
...
for index, value in enumerate(popularity):
plt.text(index,value, str(value))
plt.show()
</code></pre>
<p>which will generate this plot:
<a href="https://i.stack.imgur.com/GpnR5.png" rel="nofollow noreferrer"><... | python|numpy|matplotlib|graph|visualization | 2 |
8,257 | 51,519,379 | Best way(run-time) to aggregate (calculate ratio of) sum to total count based on group by | <p>I'm trying to identify ratio of approved applications(identified by flag '1' and if not then '0') to total applications for each person(Cust_ID). I have achieved this logic by the following code but it takes about 10 mins to compute this for 1.6 M records. Is there a faster to perform the same operation?</p>
<pre><... | <p>I think need aggregate by <code>mean</code>:</p>
<pre><code>df = pd.DataFrame({'STATUS_Approved':[0,1,0,0,1,1],
'Cust_ID':list('aaabbb')})
print (df)
STATUS_Approved Cust_ID
0 0 a
1 1 a
2 0 a
3 0 b
4 ... | pandas|python-3.6|calculation | 1 |
8,258 | 51,547,168 | Pandas join two dataframes based on relationship described in dictionary | <p>I have two dataframes that I want to join based on a relationship described in a dictionary of lists, where the keys in the dictionary refer to ids from dfA idA column, and the items in the list are ids from dfB idB column. The dataframes and dictionary look something like this:</p>
<pre><code>dfA
colA colB... | <p>You can create a linking table (DataFrame) from your dictionary. Below full working example. It might need some row and column sorting at the end to produce exactly your output.</p>
<pre><code>import pandas as pd
import numpy as np
dfA = pd.DataFrame({'colA': ('a', 'b', 'b'),
'colB': ('abc', 'd... | python|pandas | 1 |
8,259 | 48,297,940 | Map values of multiple dataframes and fill columns | <p>Lets assume I have the following three dataframes:</p>
<p><strong>Dataframe 1:</strong></p>
<pre><code>df1 = {'year': ['2010','2012','2014','2015'], 'count': [1,1,1,1]}
df1 = pd.DataFrame(data=df1)
df1 = df1.set_index('year')
df1
year count
2010 1
2012 1
2014 1
2015 1
</code></pre>
<p><strong>Data... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.union.html" rel="nofollow noreferrer"><code>union</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a>:</p>
<pre><code>i... | python|pandas|dataframe | 3 |
8,260 | 48,376,704 | How to train a classifier that contain multi dimensional featured input values | <p>I am trying to model a classifier that contain Multi Dimensional Feature as input. Can any one knew of a dataset that contain multi dimensional Features?
Lets say for example: In mnist data we have pixel location as feature & feature value is a Single Dimensional grey scale value that varies from (0 - 255), But ... | <p>The same way.</p>
<p>If you plug the pixels into your network directly just reshape the tensor to have H*W*3 length.</p>
<p>If you use convolutions note the the last parameter is the number of input/output dimensions. Just make sure the first convolution uses 3 as input.</p> | tensorflow|machine-learning|dataset|feed-forward | 0 |
8,261 | 48,510,229 | reconstructing signal with tensorflow.contrib.signal causes amplification or modulation (frames, overlap_and_add, stft etc) | <p><strong><em>UPDATE</strong>: I've reimplemented this in librosa to compare, and the results are indeed very different to the results from tensorflow. Librosa gives the results I'd expect (but not tensorflow).</em></p>
<p>I've posted this as an <a href="https://github.com/tensorflow/tensorflow/issues/16465" rel="nor... | <p>You should use <code>tf.signal.inverse_stft_window_fn</code></p>
<pre><code>window_fn=tf.signal.inverse_stft_window_fn(frame_step)
tf_istfts=tf.signal.inverse_stft(tf_stfts, frame_length=frame_length, frame_step=frame_step, fft_length=fft_length, window_fn=window_fn)}
</code></pre>
<p>See more at <a href="https://... | python|tensorflow|time-series|signal-processing | 1 |
8,262 | 48,534,879 | Converting sparse IndexedSlices to a dense Tensor | <p>I got the following warning:</p>
<pre><code>94: UserWarning: Converting sparse IndexedSlices to a dense Tensor with 1200012120 elements. This may consume a large amount of memory.
</code></pre>
<p>For the following code:</p>
<pre><code>from wordbatch.extractors import WordSeq
import wordbatch
from keras.layers im... | <p>I've had the same issue with the Embedding layer in Keras. <a href="https://github.com/keras-team/keras/issues/4365#issuecomment-260482550" rel="nofollow noreferrer">The solution</a> is to explicitly use a TensorFlow optimizer, like here:</p>
<p><code>model.compile(loss='mse',
optimizer=TFOptimizer(t... | tensorflow|keras|word-embedding|gated-recurrent-unit | 1 |
8,263 | 48,669,373 | invalid column name error when writing pandas DataFrame to sql | <p>When I try to write a dataframe to ms sql server, like this:</p>
<pre><code>cnxn = sqlalchemy.create_engine("mssql+pyodbc://@HOST:PORT/DATABASE?driver=SQL+Server")
df.to_sql('DATABASE.dbo.TABLENAME', cnxn, if_exists='append', index=False)
</code></pre>
<p>I get the following error:</p>
<pre><code>ProgrammingErro... | <p>The problem was that I added the database name when executing the df.to_sql command, which was not needed since I had already established a connection to that database. This worked:</p>
<pre><code>df.to_sql('TABLENAME', cnxn, if_exists='append', index=False)
</code></pre> | python-3.x|pandas|sqlalchemy|pymssql | 3 |
8,264 | 48,812,737 | Advice for ignoring ds_store file when uploading files to jupyter | <p>I was wondering if anyone had some advice on how deal with the ds.store file that is automatically created by apple for each folder when uploading data. Does everyone just write an if statement:</p>
<pre><code> for i in files:
if file == '.DS_Store'
continue
upload file...
</code></pre>
<p>or is t... | <p>If you want to ensure you skip all hidden files use something like <code>filename.startswith('.')</code></p> | python|pandas | 2 |
8,265 | 48,448,385 | Convert multidimensional list to multidimensional numpy.array | <p>I am having trouble converting a python list-of-list-of-list to a 3 dimensional numpy array. </p>
<pre><code>a = [
[
[1,2,3,4], # = len 4
...
], # = len 58
...
] # = len 1245
</code></pre>
<p>when I call <code>a = np.array(a)</code> on it, it reports shape as <code>(1245,)</code> and I cannot r... | <p>Lists of the same level (the same numpy axis) need to be the same size. Otherwise you get an array of lists.</p>
<pre><code>np.array([[0, 1], [2]])[0] # returns [0, 1]
np.array([[0, 1], [2, 3]])[0] # returns array([1, 2])
</code></pre>
<p>You can get around this by calling [<code>pad</code>] on your lists befor... | python|arrays|numpy|multidimensional-array | 2 |
8,266 | 48,775,531 | how to convert a monthly period in a date? | <p>Consider this simple example</p>
<pre><code>df = pd.DataFrame({'mydate' : ['1985m3','1985m4','1985m5']})
df
Out[18]:
mydate
0 1985m3
1 1985m4
2 1985m5
</code></pre>
<p>How can I convert these monthly periods into a proper <code>datetime</code> (artificially using the first day of the month, such as <code>'... | <p>Try using <code>pandas.to_datetime</code> with Python <a href="http://strftime.org/" rel="nofollow noreferrer">time directives</a> where '%Y' for year, 'm' hard code for the letter m, and '%m' for month:</p>
<pre><code>pd.to_datetime(df.mydate, format='%Ym%m')
</code></pre>
<p>Output:</p>
<pre><code>0 1985-03-0... | python|pandas | 4 |
8,267 | 70,897,341 | pandas dataframe groupby and agg to obtain a value if conditions in another column | <p>I have a dataframe like this:</p>
<pre><code>df_test = pd.DataFrame({'ID1':['A','A','A','A','A','A','A','A','A','A'],
'ID2':['a','a','a','aa','aaa','aaa','b','b','b','b'],
'ID3':['c1','c2','c3','c4','c5','c6','c7','c8','c9','c10'],
'condition1':[1,... | <p>Your condition (1) generalises as (2), so you can always just look at the first row in the group according to <code>condition2</code>:</p>
<pre><code>(
df_test
.sort_values("condition2", ascending=False) # sort everything by condition2
.groupby(["ID1", "ID2", "conditio... | python|pandas | 1 |
8,268 | 70,928,576 | Python: fuzzywuzzy matching dataframe but returns unpredictable results | <p>I've been searching around for a while now, but I can't seem to find the answer to this small problem.</p>
<p>I created this function to match words with the wrong result in the column by mapping the main column containing the correct word</p>
<pre><code>data_provinsi = {'id':[11, 12, 13, 14, 15, 16],
'name'... | <p>Try:</p>
<pre><code>best_match = lambda x: pd.Series(process.extractOne(x, df_provinsi['name'].unique()))
df_sample[['mapped_names', 'ratio']] = df_sample['provinsi'].apply(best_match)
print(df_sample)
# Output:
province_id provinsi mapped_names ratio
0 11 PAPUA PAPUA 100
1 ... | python-3.x|pandas|mapping|matching|fuzzywuzzy | 0 |
8,269 | 70,825,604 | BERT error - module 'tensorflow_core.keras.activations' has no attribute 'swish' | <p>I am trying to execute the transformer model but ended up with error.</p>
<ul>
<li>Python version == 3.7</li>
<li>Tensorflow == 2.0</li>
<li>Transformers == 4.15.0</li>
</ul>
<p>Source : <a href="https://huggingface.co/cross-encoder/nli-deberta-base?candidateLabels=supply+chain%2C+scientific+discovery%2C+micro... | <p>I tried installing Tensorflow==2.3 and restarted the machine. Now the error gone....</p> | python|nlp|tensorflow2.0|bert-language-model|transformer-model | 0 |
8,270 | 70,955,340 | how to find Max_winning_streak (max number of consecutive +ve values) in pandas dataframe | <p>I have datafram like This:</p>
<p>dataframe_name-> p_and_l</p>
<pre><code>date pnl
1/2/17 15:14 -907.5
1/3/17 15:14 1685.75
1/4/17 15:14 817
1/5/17 15:14 -182.5
1/6/17 15:14 415.25
1/9/17 15:14 -339.75
1/10/17 15:14 -413
1/11/17 15:14 1137.5
1/12/17 15:14 127.25
1/13/17 15:14 ... | <p>Compare values for groups by less ot equal <code>0</code> with cumulative sum and then count values, <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>Series.value_counts</code></a> sorting by default, so first value is maximal count:<... | python|pandas|numpy|pandas-groupby|numpy-ndarray | 0 |
8,271 | 51,635,290 | Pandas - combine two columns | <p>I have 2 columns, which we'll call <code>x</code> and <code>y</code>. I want to create a new column called <code>xy</code>:</p>
<pre><code>x y xy
1 1
2 2
4 4
8 8
</code></pre>
<p><em>There shouldn't be any conflicting values, but if there are, y takes precedence. If it makes ... | <p>it could be quite simple if your example is accurate</p>
<pre><code>df.fillna(0) #if the blanks are nan will need this line first
df['xy']=df['x']+df['y']
</code></pre> | python|pandas|dataframe | 4 |
8,272 | 41,941,605 | Fill values from one dataframe to another with matching IDs | <p>I have two pandas data frames, I want to get the sum of items_bought for each ID in DF1. Then add a column to DF2 containing the sum of items_bought calculated from DF1 with matching ID else fill it with 0. How can I do this in an elegant and efficient manner? </p>
<p>DF1</p>
<pre><code>ID | items_bought
1 ... | <pre><code>df1.groupby('ID').sum().loc[df2.ID].fillna(0).astype(int)
Out[104]:
items_bought
ID
1 5
2 4
8 0
3 13
2 4
</code></pre>
<ol>
<li>Work on df1 to calculate the sum for each <code>ID</code>.</li>
<li>The resulting dataframe is no... | python|pandas | 3 |
8,273 | 41,896,995 | Multiple filters Python Data.frame | <p>I'm pretty new to python. I'm trying to filter rows in a data.frame as I do in R. </p>
<pre><code>sub_df = df[df[main_id]==3]
</code></pre>
<p>works, but </p>
<pre><code>df[df[main_id] in [3,7]]
</code></pre>
<p>gives me error</p>
<blockquote>
<p>"The truth value of a Series is ambiguous"</p>
</blockquote>
<... | <p>You can use pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow noreferrer"><code>isin</code></a> function. This would look like this:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'f']})
df[df['A'].isin([2, 3])]
</... | python|pandas|dataframe | 3 |
8,274 | 42,041,151 | numpy irfft by amplitude and phase spectrum | <p>How to compute irfft if I have only amplitude and phase spectrum of signal? In numpy docs I've found only irfft which use fourier coefficients for this transformation.</p> | <p>If you have amplitude and phase vectors for a spectrum, you can convert them to a complex (IQ or Re,Im) vector by multiplying the cosine and sine of each phase value by its associated amplitude value (for each FFT bin with a non-zero amplitude, or vector-wise).</p> | python|numpy|fft|ifft | 1 |
8,275 | 64,404,953 | The fastest way to check all values from the list of coordinates | <p>I have a list of coordinates <code>a = [(1,2),(1,300),(2,3).....]</code>
These values area coordinates of <code>1000 x 1000 NumPy</code> array.</p>
<p>Let's say I want to sum all the values under these coordinates. Is there a faster way to do it than:</p>
<pre><code>sum([array[i[0],i[1]] for i in a])
</code></pre> | <p>Apply a mask to <code>array</code> using <code>a</code> and then sum over the masked array. Example:</p>
<pre><code># Prepare sample array and indices
a = np.arange(10*10).reshape(10,10)
ind = [(1,0), (2, 4), (2,6), (7,7), (8,9), (9,3)]
# Cast list of coordinates into a form that will work for indexing
indx = np.sp... | performance|numpy | 0 |
8,276 | 64,458,459 | How to convert json dataframe to normal dataframe? | <p>I have a dataframe which has lots of json datas inside.</p>
<p>for example :</p>
<pre><code>{"serial": "000000001fb105ea", "sensorType": "acceleration", "data": [1603261123.328814, 0.171875, -0.9609375, 0.0234375]}
{"serial": "000000001fb105ea", &... | <p>If input data are in <code>json</code> file use:</p>
<pre><code>cols = ['Date','x','y','z']
df = pd.DataFrame(pd.read_json('json.json', lines=True)['data'].tolist(), columns=cols)
df['Date'] = pd.to_datetime(df['Date'], unit='s')
print (df)
Date x y z
0 2020-10-21 0... | python|json|pandas | 0 |
8,277 | 64,208,601 | Creating a 3-D (or larger) diagonal NumPy array from diagonals | <p>Is there an efficient 'Numpy'-based solution to create a 3 (or higher) dimensional diagonal matrix?</p>
<p>More specifically, I am looking for a shorter (and perhaps more efficient) solution to replace the following:</p>
<pre><code>N = 100
M = 4
d = np.random.randn(N) # calculated in the real use case from other p... | <p>Here's one with <a href="https://numpy.org/doc/stable/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a> diag-view -</p>
<pre><code>np.einsum('iij->ij',A)[:] = d
</code></pre>
<p>Looking at the string notation, this also translates well from the iterative part : <code>A[i... | python-3.x|numpy|numpy-ndarray | 0 |
8,278 | 64,509,613 | ValueError: No gradients provided for any variable: ['embedding/embeddings:0', '] | <p>I am new in Tensorflow 2 and I want to train a multi input neural network in keras/tensorflow. This is my sample code:</p>
<pre><code>First_inputs = Input(shape=(2000, ),name="first")
Second_inputs = Input(shape=(4, ),name="second")
embedding_layer = Embedding(3,3, input_length=2000,)(First_inpu... | <p>Your data is numpy arrays ,you have to give two separate arguments to fit() method ,list of np.arrays as inputs and np.array as label.(remove the tuple as input):</p>
<pre><code>First_inputs = Input(shape=(2000, ),name="first")
Second_inputs = Input(shape=(4, ),name="second")
embedding_layer = Em... | python|tensorflow|keras|deep-learning|tensorflow2.0 | 1 |
8,279 | 64,513,356 | How to find highest and lowest value and aggregate into a string in Pandas, Pysimplegui | <p>I have a dataframe in pandas</p>
<p>This code is part of a function in a GUI and I'm trying to create one line of string that would mention the highest count of COVID cases in a country within a continent whereas the continent is selected from the user.</p>
<p>This is the dataset I am using: <a href="https://raw.git... | <p>Understanding that the subject of this question is to display the maximum and minimum values on the x-axis labels for the selected continent, I created the following code.</p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
import requests
url = 'https://raw.githubusercontent.com/owid/covid-19-data/m... | python|pandas|matplotlib|pysimplegui | 0 |
8,280 | 47,609,730 | Why does this numpy attribute suddenly become shared between instances | <p>I stumbled upon odd behavior when using python 3.6 and numpy 1.12.1 under Linux.</p>
<p>I have an attribute <code>self.count</code> which I initialize with <code>np.array([0.0, 0.0, 0.0])</code>. I would expect that <code>self.count</code> would behave like any other attribute and have its own value per class insta... | <p>This is a common bug, most often seen when using a list as the default value for a function.</p>
<pre><code>count=np.array([0.0, 0.0, 0.0])
</code></pre>
<p>This array is created once, when the class is initialized. So all instances share the same <code>create</code> attribute, same array. They don't get a fresh... | python-3.x|numpy|attributes|shared-ptr|instantiation | 1 |
8,281 | 58,751,186 | python counting examples based on criteria | <p>I want to count in a dataframe how many examples have the same criteria. The criteria will be selected by me before counting the examples. </p>
<p>i want to use it with the groupby but i didn't find a solution</p>
<pre class="lang-py prettyprint-override"><code>df_education = df.groupby(['Education','Self_Employed... | <p>did you try:</p>
<pre class="lang-py prettyprint-override"><code>df_education = df.groupby(
["Education", "Self_Employed", "Loan_Status"],
axis=0
).size()
</code></pre> | python|pandas | 2 |
8,282 | 58,945,461 | Cannot work out why I am getting this error.|TypeError: unsupported operand type(s) for /: 'list' and 'int' | <p>I have a project for school and I need to get the historical data from Yahoo Finance and hen perform some calculations on it and write a report on it.</p>
<pre><code>import numpy as np
import csv
import pandas_datareader as pdr
def dataanalysis(stock1, comp1, comp2, comp3): # Function to download data from Yahoo... | <p><strong>One of the things you are passing to <code>np.corrcoef</code> is not what you think it is.</strong></p>
<p>For example, this throws the same error:</p>
<pre><code>import numpy as np
np.corrcoef([[[1,2,3,4]], [4,5,6,7]])
</code></pre>
<p>Notice that the first 'array' is actually a list of one list. Maybe t... | numpy|typeerror | 0 |
8,283 | 70,371,054 | Finding relevant points in the given curve | <p>Consider the following Python code which plots a curve and analyzes it to find some points:</p>
<pre><code>%matplotlib inline
import numpy as np
from numpy.polynomial.polynomial import Polynomial
from scipy.interpolate import UnivariateSpline
from scipy.signal import savgol_filter
import scipy.stats
import scipy.opt... | <p>I prefer to work on filtered (smoothed) rather than interpolated data.</p>
<p>First point I find by:</p>
<ul>
<li>finding maximum of the smoothed data</li>
<li>finding first point whose value is 90% of the maximum value</li>
<li>going back to find first point whose derivative is >= 0</li>
</ul>
<p>Second point I ... | python|numpy|machine-learning|scipy|signal-processing | 1 |
8,284 | 56,392,463 | Python | Reading JSON files and applying simple algorithm on each iteratively into a dataframe | <p>we have a large json file that takes too long to be read with pd.read_json. </p>
<p>What we want to do initially is : </p>
<pre><code># Load the file
df_view = pd.read_json('/path/to/file', lines=True)
# Create a new feature using the above dataframe
df_nb_view = df_view[['userid','itemid']]
df_nb_view = df_nb_vi... | <p>If I understand correctly, you want to read and process in file chunks.
If so, create a final result dataframe and append to it in each iteration</p>
<pre><code>final_df = pd.DataFrame()
for filename in files:
df_view = pd.read_json(filename, lines=True)
df_nb_view = df_view[['userid','itemid']]
df_nb_... | python|json|pandas|machine-learning | 0 |
8,285 | 56,042,548 | How to convert a pandas time series with hour (h) as index unit into pandas datetime format? | <p>I am working on time-series data, where my pandas dataframe has indices specified in hours, like this:</p>
<pre><code>[0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, ...]
</code></pre>
<p>This goes on for a few thousand hours. I know that the first measurement was taken on, let's say, <code>May 1... | <p>You can add hours to index by parameter <code>origin</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> for <code>DatetimeIndex</code>:</p>
<pre><code>idx = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2... | python|pandas|datetime|time-series | 2 |
8,286 | 55,827,792 | Pivoting a table partially in Pandas | <p>I have a table containing user reviews (numbers totally made-up):</p>
<pre><code>| user_id | vote | votes_for_user | average_user_vote | ISBN_categ |
213 4.5 12 3.4 1
563 3.7 74 2.3 2
213 1.2 12 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>DataFrame.pivot</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>DataFrame.fillna</code><... | pandas|dataframe|pivot | 1 |
8,287 | 55,670,244 | Why is an OOM happening on my model init()? | <p>A single line in my model, <code>tr.nn.Linear(hw_flat * num_filters*8, num_fc)</code>, is causing an OOM error on initialization of the model. Commenting it out removes the memory issue.</p>
<pre><code>import torch as tr
from layers import Conv2dSame, Flatten
class Discriminator(tr.nn.Module):
def __init__(sel... | <p><strong>Your linear layer is quite large</strong> - it does, in fact, need at least 18GB of memory. (Your estimate is off for two reasons: (1) a <code>float32</code> takes 4 bytes of memory, not 32, and (2) you didn't multiply by the output size.)</p>
<p>From the <a href="https://pytorch.org/docs/stable/notes/faq.h... | python-3.x|pytorch | 1 |
8,288 | 55,583,130 | Tensorflow 2.0 Keras Model subclassing | <p>I'm trying to implement a simple UNet-like model using the model subclassing method. Here's my code:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
from tensorflow import keras as K
class Enc_block(K.layers.Layer):
def __init__(self, in_dim):
super(Enc_block, self).__init_... | <p>Take a look at this line from <code>UNetModel</code> class:</p>
<pre><code>x, x_skip1 = self.encoder_block(32)(inputs)
</code></pre>
<p>where <code>self.encoder_block()</code> is defined by</p>
<pre><code>self.encoder_block = Enc_block(in_dim)
</code></pre>
<p><code>encoder_block</code> is an instance of class. ... | tensorflow|tf.keras | 3 |
8,289 | 64,633,264 | About epochs and images in Machine learning | <p>I have image 186 images in train_images and 174 images in valid_images when I pass to CNN model It only train 6 images. I did not create any batch size. The dataset name is <a href="https://www.kaggle.com/ihelon/lego-minifigures-classification" rel="nofollow noreferrer">Lego minifigure</a>.</p>
<pre><code> '''
p... | <p>batch_size equals to 32 on default</p> | python|tensorflow|machine-learning|keras|deep-learning | 0 |
8,290 | 41,029,287 | How to call only some files from a folder full of files using python? | <p>I have many files inside 1 folder.
This is a description of names:</p>
<p>AWA_s1_Fp1_features.mat</p>
<p>AWA_s1_C3_features.mat</p>
<p>AWA_s1_C4_features.mat</p>
<p>AWA_s1_Fp2_features.mat</p>
<p>Rem_s1_Fp1_features.mat</p>
<p>Rem_s1_C3_features.mat</p>
<p>Rem_s1_C4_features.mat</p>
<p>Rem_s1_Fp2_features.ma... | <p>Try this:</p>
<pre><code>read_files = glob.glob('/media/FeaturesX/AWA_s*_C3_features.mat')
</code></pre>
<p>The pattern matching in <code>glob</code> is fairly literal. By putting <code>_C3_features.mat</code> after the <code>*</code>, we require that part of the string to exist for the match to be valid.</p> | python-3.x|numpy | 1 |
8,291 | 40,924,025 | Pandas concatenate/join/group rows in a dataframe based on date | <p>I have a pandas dataset like this:</p>
<pre><code> Date WaterTemp Discharge AirTemp Precip
0 2012-10-05 00:00 10.9 414.0 39.2 0.0
1 2012-10-05 00:15 10.1 406.0 39.2 0.0
2 2012-10-05 00:45 10.4 406.0 ... | <p>I figured it out. I group the readings by time of day of reading. Each group is a dataframe in and of itself, so I just then need to concatenate the dataframes based on date. My code for the whole function is as follows. </p>
<pre><code>import pandas
def readInData(filename):
#read in files and remove missing ... | python|python-3.x|pandas|dataframe | 0 |
8,292 | 53,828,383 | Loading a CNN from checkpoints and feeding it in tensorflow | <p>Assuming that I have a simple network including a CNN with a specific name. We can save the checkpoints using tf saver and restore it with tf.saver.restore (checkoiints address). We also can get all tensors and operations in the graph using tf.graph_def().get_operations() and etc.
For my specific question, I load a... | <p>If the model is saved with <code>write_meta_graph=True</code>, it will create meta file which we can load to create the network, else you have to write python code to create each and every layer manually as the original model.</p>
<p>You can use <a href="https://www.tensorflow.org/api_docs/python/tf/train/import_me... | tensorflow | 0 |
8,293 | 53,996,802 | Using ctypes to call C++ function with pointer args | <p>Some background (might not be directly related to the problem): I need to perform an efficient matrix multiplication with a known sparsity.<br>
Because it's sparse, using normal matrix multiplication is wasteful, and because it's a known sparsity I can implement it in an efficient way rather than using sparse librar... | <p><code>astype</code> creates a copy of an array. Therefore the <code>out.astype(np.float64)</code> parameter gives a copy to <code>sparse_precision_mult</code> which is modified and then thrown away. Original <code>out</code> isn't modified.</p>
<p>Create <code>out</code> with type <code>np.float64</code> and (if ne... | python|c++|numpy|ctypes | 1 |
8,294 | 66,144,453 | Merging multiple columns on pandas dataframe ("Vlookup" on different columns) | <p>I have a dataframe called <code>reference</code> and it looks like this:</p>
<pre><code> wind P
0 15.5 300
1 16.0 333
2 16.5 421
3 17.0 498
4 17.5 544
</code></pre>
<p>and another one, called <code>vdb1</code> with all its columns with <code>wind</code> values. What I want to do is for each... | <p>Lets map accross the values using map. values not in the rep(small datframe will become null). Lets fill those using combine_first.</p>
<pre><code>vdb1.apply(lambda x: x.map(dict(zip(rep['wind'],rep['P'])))).combine_first(vdb1)
</code></pre> | python|pandas | 1 |
8,295 | 65,951,706 | How to take rows with continous time for more than 3 three rows python | <p>I have one data frame i want to get rows when time is continuous for three rows and delete other rows.</p>
<pre><code>df_input:
Value time
8970 2020-11-20 15:40:00
7602 2020-11-20 15:50:00
7603 2020-11-20 16:00:00
7604 2020-11-20 16:10:00
7757 2020-11-29 06:30:00
7758 2020-11-29 06:40:00
... | <p>by</p>
<pre><code>df['timeDiff'] = df['time'].diff()
</code></pre>
<p>you will get</p>
<pre><code>df_input
Value time
8970 2020-11-20 15:40:00
7602 2020-11-20 15:50:00
7603 2020-11-20 16:00:00
7604 2020-11-20 16:10:00
7757 2020-11-20 18:30:00
7758 2020-11-20 20:30:00
</code></pre>
<p>into... | python-3.x|pandas|numpy|pandas-groupby | 1 |
8,296 | 66,033,938 | Python/matplot "fill_between" stops just above y=7.5 where I want it to stop | <p>I am trying to get the shaded colors to stop at the y=7.5 bar, but the green one doesn't go far enough (i.e. to the line). Is anyone able to figure this out? Many thanks!</p>
<pre><code># sensitivity analysis
sensitivity = pd.DataFrame()
for x in exit_probabilities:
for y in exit_valuations:
sensitivity.... | <p>Your first fill (the blue one) goes fine.</p>
<p>The second fill should go:</p>
<ul>
<li>the top is <code>sensitivity['.3']</code></li>
<li>the bottom is <code>sensitivity['.2']</code>, but only where it is larger than <code>7.5</code>, so, take the maximum of <code>sensitivity['.2']</code> and <code>7.5</code></li>... | python|python-3.x|numpy|matplotlib|plot | 0 |
8,297 | 66,115,632 | Gunicorn worker, threads for GPU tasks to increase concurrency/parallelism | <p>I'm using Flask with Gunicorn to implement an AI server. The server takes in HTTP requests and calls the algorithm (built with pytorch). The computation is run on the nvidia GPU.</p>
<p>I need some input as to how can I achieve concurrency/parallelism in this case. The machine has 8 vCPUs, 20 GB memory and 1 GPU, 12... | <p>fast Tokenizers are not thread-safe apparently.</p>
<p>AutoTokenizers seems like a wrapper that uses fast or slow internally. their default is set to fast (not thread-safe) .. you'll have to switch that to slow (safe) .. that's why add the <strong>use_fast=False</strong> flag</p>
<p>I was able to solve this by:</p>
... | concurrency|parallel-processing|pytorch|gpu|gunicorn | 0 |
8,298 | 52,796,629 | How to save and use a trained neural network developed in PyTorch / TensorFlow / Keras? | <p>Are there ways to save a model after training and sharing just the model with others? Like a regular script? Since the network is a collection of float matrices, is it possible to just extract these trained weights and run it on new data to make predictions, instead of requiring the users to install these frameworks... | <p>PyTorch: As explained in <a href="https://stackoverflow.com/questions/42703500/best-way-to-save-a-trained-model-in-pytorch#43819235">this post</a>, you can save a model's parameters as a dictionary, or load a dictionary to set your model's parameters.
You can also save/load a PyTorch model as an object.
Both proced... | tensorflow|keras|pytorch | 1 |
8,299 | 52,901,546 | And operator on two rank-1 tensorflow tensors | <p>I have two rank-1 tensors, one of them contains X floats, the other is one-hot, also with X entries. </p>
<p>I want to create a new rank-1 tensor, with a single element: the float in the first tensor at the index where the one-hot vector is equal to 1.</p>
<p>Any help would be much appreciated.</p> | <p>It sounds like tf.boolean_mask is what you're looking for:
<a href="https://www.tensorflow.org/api_docs/python/tf/boolean_mask" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/boolean_mask</a></p> | python|tensorflow | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.