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 |
|---|---|---|---|---|---|---|
12,100 | 43,768,588 | Python - For loop | <p>I have tried a couple of solutions available here on stackoverflow but still incapable of solving the problem. Because I'm just starting with programming it might be a simple solution.</p>
<p><strong>The situation:</strong>
Currently working on a Pandas dataframe called 'dataset' which contains the column zscore. I... | <p>no need for loop.. just use the <code>clip()</code> method:</p>
<pre><code> dataset['zscore'] = dataset['zscore'].clip(-3.0, 3.0)
</code></pre> | python|pandas|for-loop | 6 |
12,101 | 43,569,756 | Vectorized dataframe look-up | <p>I have two dataframes:</p>
<pre><code>df = pd.DataFrame([['A', 'B'], ['B', 'A']], columns=['Mon', 'Tues'])
Mon Tues
0 A B
1 B A
lookup = pd.DataFrame([[0, 1], [2, 3]], index=['A', 'B'], columns=df.columns)
Mon Tues
A 0 1
B 2 3
</code></pre>
<p>For each day, for each key in the first data... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>replace</code></a> to exchange the values:</p>
<pre><code>>>> df.replace(lookup)
Mon Tues
0 0 3
1 2 1
</code></pre>
<p>When passed to the <code>replac... | python|pandas|dataframe|vectorization|lookup | 3 |
12,102 | 43,642,789 | How to read a .txt file using Scikit-learn Pandas | <pre><code>import pandas
from pandas.tools.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import Logisti... | <p>Default value for delimiter/separator argument is <code>,</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer">pd.read_csv</a>, so you have to set it explicitly:</p>
<pre><code>In [6]: dataset = pd.read_csv(url, names=names, delim_whitespace=True)
... | python|pandas|scikit-learn | 0 |
12,103 | 43,619,244 | Pandas groupby operation returned object, but no visual | <p>Very new to Pandas (2 days) and ran the following groupby command on my Academy Awards data set. </p>
<pre><code>df[(df.Award == 'Best Actress') & (df.Winner == 1.0)].groupby('Name')
</code></pre>
<p>I received the following output, which usually precedes a visualisation, but not this time. </p>
<pre><code>&l... | <blockquote>
<p>I received the following output, which usually precedes a visualisation, but not this time.</p>
</blockquote>
<pre><code><pandas.core.groupby.DataFrameGroupBy object at 0x1166b8cc0>
</code></pre>
<hr>
<p>This is <strong>not</strong> the same as what precedes a visualization.<br>
This <strong>... | python|pandas | 3 |
12,104 | 2,301,018 | Would you use numpy if you were just manipulating a sequence of binary values? | <p>Is there any advantage to using numpy when you're doing a large number of operations on lists of binary values? How about integers within a small range (like just the numbers 1,2, and 3?)</p> | <p>Eliminating the loops is the the source of the performance gain (10x):</p>
<pre><code>import profile
import numpy as NP
def np_test(a2darray) :
row_sums = NP.sum(a2darray, axis=1)
return NP.sum(row_sums)
def stdlib_test2(a2dlist) :
return sum([sum(row) for row in a2dlist])
A = NP.random.randint(1, 6, 1e7).... | python|numpy|scipy|bit-manipulation | 3 |
12,105 | 73,156,971 | Accessing indices in an array, containes nan elements in a certain range | <p>I have an array like:</p>
<pre class="lang-py prettyprint-override"><code>arr = np.array([[9,9,9,9,9,0,0,0,1,1,1,0,0,9,9],
[9,9,9,1,1,1,1,0,0,0,0,1,1,1,9],
[9,1,1,0,0,0,1,1,1,0,0,0,1,1,9],
[9,1,1,1,1,1,1,1,0,0,0,1,1,1,9]])
</code></pre>
<p>I tried with bisect.bisect_ri... | <p>It's unclear if one can have 9 show up in the middle of the arrays. This will return the desired output:</p>
<pre><code>[list(np.where(i!=9)[0]) for i in arr]
</code></pre> | python|numpy | 1 |
12,106 | 73,037,803 | Pandas Rolling With MultiIndex and GroupBy | <p>I am looking at creating a rolling sum of the <strong>past</strong> <code>n</code> results for a given <code>id</code>. The index of the DataFrame is the <code>id</code> and <code>date</code>.</p>
<p>The code below works for non-time-based rolling windows, i.e. integers. However, does not work for time-based interva... | <p>You should remove the <code>min_periods=1</code> argument from <code>rolling</code> and this will give you what you seek (for reference, the <code>min_periods</code> argument is documented as "Minimum number of observations in window required to have a value; otherwise, result is np.nan.")</p> | python|pandas|dataframe | 0 |
12,107 | 72,971,349 | 50MB file taking too long to read in python | <p>I am trying to analyse a simple but "large" (52MB) .ped file I generated from a 1000genomes project .vcf file: it has 107 lines and 248189 columns. I do not care for the first 6 cols, and the ones I am interested in contain only letters, 'A','C','G','T', for which I need to calculate their frequencies. It ... | <p>So all rows just contain 6 meta columns to skip, and then 248183 colums where every value can only be 'A','C','G' and 'T'? And the file is tab-separated?</p>
<pre><code>with open('filtered_conv.ped') as file:
# read line by line
for line in file:
# skip chars until 5 tabs were found
tab_count... | python|pandas|vcf-variant-call-format | 0 |
12,108 | 72,907,702 | How to improve performance of pandas.apply() to perform text cleaning operations on large sized pandas column? | <p>I'm working on a tweet dataset where one column is the text of the tweet. Following function performs the cleaning of tweet which involves removal of punctuations, stopwords, lower case conversion, removal of emojis and these are themselves a small utility functions.</p>
<pre><code>def clean_text(text):
text = t... | <p>if you don't want to tweak the function itself, you can use Pandarella to parrallize your apply <a href="https://github.com/nalepae/pandarallel" rel="nofollow noreferrer">https://github.com/nalepae/pandarallel</a>. It even gives you a nice progress bar :)</p> | pandas|numpy|performance|tweets|pandas-apply | 0 |
12,109 | 10,518,803 | Cannot export to CSV after data alignment | <p>I have two sets of data and only want to keep the data where both sets have common dates. I imported the data sets with <code>read_csv()</code>, calling them <em><code>df1</code></em>, <em><code>df2</code></em>.</p>
<p>Then run:</p>
<pre><code>DF=df1.align(df2, join='inner',axis=0)
</code></pre>
<p>After checking... | <p><code>align</code> returns aligned versions of the left and right DataFrames (as a tuple):</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#aligning-objects-with-each-other-with-align" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/basics.html#aligning-objects-with-each-other-with... | python|pandas | 2 |
12,110 | 70,484,019 | Tensorflow on M1 Mac: "Incorrect checksum for freed object" | <p>I've recently began using an Apple Silicon mac. I installed Tensorflow through Anaconda, version 2.6.2, which was the latest version I could find.</p>
<p>When I run the training code, the training seems to begin initializing, until it reaches some memory error. Then it hangs until I manually stop it.</p>
<p>The prin... | <p>Installing Tensorflow on Mac M1 is a real pain. My solution to your problem is to restart installing Tensorflow; I faced the same issue as you and was unable to fix it. First off, I'm going to assume that you are on Monterey (Mac 12); If you aren't, you'll have to refer to <a href="https://github.com/apple/tensorflo... | python|tensorflow|machine-learning|anaconda|apple-m1 | 2 |
12,111 | 70,471,278 | Question from pandas of resample from quantile function | <pre><code>import pandas as pd
new = pd.read_csv(r'C:\Users\cctsa\PycharmProjects\pythonProject\stock_2409.csv')
new['time'] = pd.to_datetime(new['time'])
new.set_index(new['time'], inplace=True)
print(new)
rule_type = '10T'
period_n = new[['ticket']].resample(rule=rule_type).quantile(0.75)
</code></pre>
<p>About quest... | <p>IIUC use if need processing numeric column <code>close</code>:</p>
<pre><code>print (new['close'].dtype)
period_n = new['close'].resample(rule=rule_type).quantile([0.25, 0.5, 0.75])
</code></pre>
<p>Or if need procesing <code>close</code> column per <code>ticket</code>s:</p>
<pre><code>period_n = new.groupby('ticke... | python|pandas|quantile | 0 |
12,112 | 70,458,211 | Python Conditional NaN Value Replacement of existing Values in Dataframe | <p>I try to transform my DataFrame witch i loaded from a CSV.
In that CSV are columns that have NaN / no Values. The goal is to replace them all!</p>
<p>For Example in column 'gh' row 45 (as shown in the picture: <a href="https://i.stack.imgur.com/kF2XN.png" rel="nofollow noreferrer">Input Dataframe</a>) is a value mis... | <p>Assuming all values can be found somewhere in the dataset, the easiest way is to sort your df by those columns ('latitude','longitude', 'time' ,'step','valid_time') and forward fill your NaN's:</p>
<p><code>df.sort_values(by=['latitude','longitude', 'time' ,'step','valid_time']).ffill()</code></p>
<p>However, <stron... | python|pandas|dataframe | 0 |
12,113 | 27,080,542 | Merging/combining two dataframes with different frequency time series indexes in Pandas? | <p>Using pandas 0.15.1. Suppose I have the following two dataframes:</p>
<pre><code>daily
2014-11-20 00:00:00 Rain
2014-11-21 00:00:00 Cloudy
2014-11-22 00:00:00 Sunny
</code></pre>
<p>.</p>
<pre><code>minutely
2014-11-20 12:45:00 51
2014-11-20 12:46:00 43
2014-11-20 12:47:00 44
...
2014-11-21 12:45:00 ... | <p>starting with:</p>
<pre><code>>>> left
minutely
2014-11-20 12:45:00 51
2014-11-20 12:46:00 43
2014-11-20 12:47:00 44
2014-11-21 12:45:00 44
2014-11-21 12:46:00 46
2014-11-21 12:47:00 48
2014-11-22 12:45:00 38
2014-11-22 12:46:00 3... | pandas|time-series | 8 |
12,114 | 30,509,476 | How to plot ylabel in panda MultiIndex Dataframe | <p>I need to plot a MultiIndex Dataframe with ylabels from level 0 of the columns. The Dataframe is as follows:</p>
<pre><code>PCs pc1 pc2 pc3 \
explained_variance_ratio 9.977643e-01 2.196399e-03 3.275875e-05
wavelength ... | <p>I usually do most of the formatting on the ax or axes itself after calling <code>plot</code>.
Try this:</p>
<pre><code>axes = pca_df.plot(subplots=True, sharex=True, title='Principle Components', legend=False)
for ax, label in zip(axes.ravel(), pca_df.columns.levels[0]):
ax.set_ylabel(label)
</code></pre>
<p... | pandas|plot|dataframe|multi-index | 4 |
12,115 | 39,099,711 | raise ValueError when producing a shape file with geopandas | <p>I have just recently started to work with shapefiles. I have a shapefile in which each object is a polygon. I want to produce a new shapefile in which the geometry of each polygon is replaced by its centroid. There is my code.</p>
<pre><code>import geopandas as gp
from shapely.wkt import loads as load_wkt
fname =... | <p>The issue is that you're populating the geometry field with a string representation of the geometry rather than a shapely geometry object.</p>
<p>No need to convert to wkt. Your loop could instead be:</p>
<pre><code>for i,r in shp.iterrows():
index.append(i)
centroid = r['geometry'].centroid
centroids.... | python|centroid|geopandas | 1 |
12,116 | 39,112,372 | Putting 2 dimensional numpy arrays into a 3 dimensional array | <p>I want to keep adding numpy arrays to another array in python.
let's say I have the following arrays:</p>
<pre><code>arraytotal = np.array([])
array1 = np.array([1,1,1,1,1])
array2 = np.array([2,2,2,2,2])
</code></pre>
<p>and I want to append array1 and array2 into arraytotal. However, when I use:</p>
<pre><code... | <p>Unfortunately, there is no way to manipulate arrays quite like that. Instead, make a list with the same name, and append the two arrays and change it to a numpy array like so:</p>
<pre><code>arraytotal[]
array1 = np.array([1,1,1,1,1])
arraytotal.append[array1]
np.array(arraytotal)
</code></pre> | python|arrays|python-2.7|numpy|multidimensional-array | 0 |
12,117 | 29,018,638 | Conditional replacement of multiple columns based on column values in pandas DataFrame | <p>I would like to simultaneously replace the values of multiple columns with corresponding values in other columns, based on the values in the first group of columns (specifically, where the one of the first columns is blank). Here's an example of what I'm trying to do:</p>
<pre><code>import pandas as pd
df = pd.Dat... | <p>How about</p>
<pre><code>df[['b1', 'b2']] = df[['b1', 'b2']].where(df[['b1', 'b2']] != '', df[['a1', 'a2']].values)
</code></pre>
<p>this returns</p>
<pre><code> a1 a2 b1 b2
0 m q m q
1 n r n r
2 o s a b
3 p t p t
</code></pre> | python|pandas | 6 |
12,118 | 29,249,330 | How can I extract this obvious event from this image? | <p>EDIT: I have found a solution :D thanks for the help.</p>
<p>I've created an image processing algorithm which extracts this image from the data. It's complex, so I won't go into detail, but this image is essentially a giant numpy array (it's visualizing angular dependence of pixel intensity of an object).</p>
<p>I... | <p>You can take a weighted dot product of successive columns to get a one-dimensional signal that is much easier to work with. You might be able to extract the patterns using this signal:</p>
<p><img src="https://i.stack.imgur.com/lYX25.png" alt="enter image description here"></p>
<pre><code>import numpy as np
A = np... | python|image-processing|numpy|statistics|signal-processing | 3 |
12,119 | 33,854,771 | convert separate 1D np.arrays into a list of 2D np.arrays | <p>I'm trying to convert three 1D arrays into a list of 2D arrays. I've managed to do this by creating an empty ndarray and populating it line by line. Could someone show me a more elegant approach?</p>
<pre><code>import numpy as np
import pandas as pd
one=np.arange(1,4,1)
two=np.arange(10,40,10)
three=np.arange(100,4... | <p>so first of all you can get array from <code>df</code> values by simply doing the following</p>
<pre><code>In [61]:
arr = df.values
arr
Out[61]:
array([[ 1, 10, 100],
[ 2, 20, 200],
[ 3, 30, 300]])
</code></pre>
<p>then add the first column in the array again</p>
<pre><code>In [73]:
arr_mod = ... | python|arrays|numpy|pandas|array-broadcasting | 2 |
12,120 | 33,793,700 | numpy genfromtxt date conversion error | <p>I am loading a file using <code>numpy.genfromtxt</code> and some of the fields are in a date format, however, when I setup a converter to process these items I get an error that I am not sure how to address (see below):</p>
<pre><code>strptime() argument 0 must be str, not <class 'bytes'>
</code></pre>
<p>At... | <p>The error is saying that <code>time.strptime</code> expects the first argument to be a <a href="http://eli.thegreenplace.net/2012/01/30/the-bytesstr-dichotomy-in-python-3" rel="nofollow"><code>str</code>, not <code>bytes</code></a>:</p>
<pre><code>>>> x = b'2013-08-16' # x is bytes
>>> import t... | python-3.x|numpy | 0 |
12,121 | 23,521,511 | Pandas: Creating DataFrame from Series | <p>My current code is shown below - I'm importing a MAT file and trying to create a DataFrame from variables within it:</p>
<pre><code>mat = loadmat(file_path) # load mat-file
Variables = mat.keys() # identify variable names
df = pd.DataFrame # Initialise DataFrame
for name in Variables:
B = mat[name... | <p>Here is how to create a DataFrame where <strong>each series is a row</strong>.</p>
<p>For a single Series (resulting in a single-row DataFrame):</p>
<pre><code>series = pd.Series([1,2], index=['a','b'])
df = pd.DataFrame([series])
</code></pre>
<p>For multiple series with identical indices:</p>
<pre><code>cols =... | python|pandas|mat | 75 |
12,122 | 22,562,540 | Pandas dataset into an array for modelling in Scikit-Learn | <p>Can we run scikit-learn models on Pandas DataFrames or do we need to convert DataFrames into NumPy arrays?</p> | <p>You can use <code>pandas.DataFrame</code> with <code>sklearn</code>, for example:</p>
<pre><code>import pandas as pd
from sklearn.cluster import KMeans
data = [(0.2, 10),
(0.3, 12),
(0.24, 14),
(0.8, 30),
(0.9, 32),
(0.85, 33.3),
(0.91, 31),
(0.1, 15),
... | python|pandas|scikit-learn | 8 |
12,123 | 22,869,893 | Assign value to subset of rows in Pandas dataframe | <p>I want to assign values based on a condition on index in Pandas DataFrame.</p>
<pre><code>class test():
def __init__(self):
self.l = 1396633637830123000
self.dfa = pd.DataFrame(np.arange(20).reshape(10,2), columns = ['A', 'B'], index = arange(self.l,self.l+10))
self.dfb = pd.DataFrame([[... | <p>You are chain indexing, see <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow">here</a>. The warning is not <em>guaranteed</em> to happen.</p>
<p>You should prob just do this. No real need to actually track the index in b, btw.</p>
<pre><code>In [44]: dfa =... | python|pandas | 2 |
12,124 | 15,121,377 | Should multi-index levels be updated after dropna() called on pandas DataFrame? | <p>After calling dropna on a multi index dataframe, the levels metadata in the index does not appear to be updated. Is this a bug?</p>
<pre><code>In [1]: import pandas
In [2]: print pandas.__version__
0.10.1
In [3]: df_multi = pandas.DataFrame(index=[[1, 2],['a', 'b',]],
data=[[... | <p>This is a known situtation archived here
<a href="https://github.com/pydata/pandas/issues/2655" rel="nofollow">https://github.com/pydata/pandas/issues/2655</a></p>
<p>People are currently contemplating how to deal with it.</p>
<p>My work-around is to use <code>index.get_level_values(level)</code>, because a <code... | python|pandas|multi-index | 1 |
12,125 | 13,354,295 | Python numpy masked array initialization | <p>I used masked arrays all the time in my work, but one problem I have is that the initialization of masked arrays is a bit clunky. Specifically, the ma.zeros() and ma.empty() return masked arrays with a <strong>mask that doesn't match the array dimension.</strong> The reason I want this is so that if I don't assign t... | <p>Well, the mask in <code>ma.zeros</code> is actually a special constant, <code>ma.nomask</code>, that corresponds to <code>np.bool_(False)</code>. It's just a placeholder telling NumPy that the mask hasn't been set.
Using <code>nomask</code> actually speeds up <code>np.ma</code> significantly: no need to keep track ... | python|arrays|numpy|initialization | 5 |
12,126 | 29,498,652 | Plot bar graph from Pandas DataFrame | <p>Assuming i have a <code>DataFrame</code> that looks like this:</p>
<pre><code>Hour | V1 | V2 | A1 | A2
0 | 15 | 13 | 25 | 37
1 | 26 | 52 | 21 | 45
2 | 18 | 45 | 45 | 25
3 | 65 | 38 | 98 | 14
</code></pre>
<p>Im trying to create a bar plot to compare columns <code>V1</code> and <code>V2</code> by th... | <p>To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:</p>
<pre><code>ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
</code></pre>
<p>What you tried was <code>df['V1','V2']</code> this will rai... | python|pandas|plot | 84 |
12,127 | 62,048,198 | Fastest way to find two minimum values in each column of NumPy array | <p>If I want to find the minimum value in each column of a NumPy array, I can use the numpy.amin() function. However, is there a way to find the two minimum values in each column, that is faster than sorting each column?</p> | <p>You can simply use <a href="https://numpy.org/doc/stable/reference/generated/numpy.partition.html" rel="nofollow noreferrer"><code>np.partition</code></a> along the columns to get smallest <code>N</code> numbers -</p>
<pre><code>N = 2
np.partition(a,kth=N-1,axis=0)[:N]
</code></pre>
<p>This doesn't actually sort t... | numpy|min | 2 |
12,128 | 51,245,946 | How to clean image urls in pandas dataframe? | <p>I have a dataframe in which I have some image urls stored in a column.
I need to clean the image urls for further processing and currently the image urls are in this format-</p>
<pre><code>df['image url'][1]
'https://www.example.com/newshop/images/backup/detailed/olivia.jpg#{[EN]:;}'
df['image url'][2]
'https://ww... | <p>Given your examples, you can use <a href="https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>pd.Series.str.split</code></a> to convert your strings to URLs. This assumes you don't have <code>#</code> in any part of your URL which matters.</p>
<... | python|string|python-3.x|pandas|url | 1 |
12,129 | 51,240,086 | How does Python Numpy save memory compared to a list? | <p>I came across the following piece of code while studying Numpy:</p>
<pre><code>import numpy as np
import time
import sys
S= range(1000)
print(sys.getsizeof(5)*len(S))
D= np.arange(1000)
print(D.size*D.itemsize)
</code></pre>
<p>The output of this is:</p>
<pre><code>O/P - 14000
4000
</code></pre>
<p>So Numpy ... | <p>NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access to reading and writing items is also faster with NumPy.</p>
<p>Maybe you don't care that much f... | python|python-3.x|numpy | 3 |
12,130 | 48,405,956 | Pandas read csv - dealing with mixed named/nameless columns | <p>I am trying to open a csv file using pandas.</p>
<p><a href="https://i.stack.imgur.com/q7xOL.png" rel="nofollow noreferrer">This </a> is a screenshot of the file opened in excel. </p>
<p>Some columns have names and some do not. When trying to read this in with pandas I get the "ValueError: Passed header names mis... | <p>In <code>names</code> you can provide column names:</p>
<p><code>df = pd.read_csv('pandas_dataframe_importing_csv/example.csv', names=['col1', 'col2', 'col3'], engine='python')</code></p> | python|pandas|csv | 2 |
12,131 | 48,240,476 | Python2.7: Not able to create null vales with np.where and np.nan methods | <p>I'm having difficulty resolving an issue whereby after using np.where to compare 2 row values within a column (position), with the result being assigned to a new column (null value is created if condition is false), i am unable to use fillna method to replace the null values with the values of the newly created colu... | <p>Let's try an experiment.</p>
<pre><code>>>> v = np.random.choice(2, 10)
>>> v
array([0, 0, 1, 1, 0, 0, 0, 1, 1, 0])
</code></pre>
<p></p>
<pre><code>>>> np.where(v, 'overtook', np.nan)
array(['nan', 'nan', 'overtook', 'overtook', 'nan', 'nan', 'nan',
'overtook', 'overtook', 'nan... | python|python-2.7|pandas|numpy | 1 |
12,132 | 48,694,436 | Cannot feed value of shape (64, 7) for Tensor 'targets/Y:0', which has shape '(?,)' | <p>I'm working on Kaggle's fer2013 dataset. Here's <a href="https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge/data" rel="nofollow noreferrer">a link</a> to the dataset. </p>
<p>I'm using TFLearn framework, I convert the Labels(7 class labels) to hot_shot and everyth... | <p>When you set <code>to_one_hot</code> to <code>True</code> in the regression function, it already converts your target to one-hot labels. So, it expects a value with shape (?,) and you should just provide the original data, <code>y_train</code> and <code>y_val</code>, to the fit function.</p>
<pre><code>model.fit({'... | python|tensorflow|deep-learning|tflearn|kaggle | 0 |
12,133 | 48,613,681 | How to get similar arrays in two lists using numpy? | <p>I have two lists characterized as such:</p>
<pre><code>circles_1 = [
array([[
[342. , 198. , 28.600698],
[ 58. , 166. , 28.600698],
[282. , 82. , 28.600698]]], dtype=float32),
array([[
[ 78. , 174. , 24.351591],
[3... | <p>Here is one brute-force way:</p>
<pre><code>from numpy import array, float32, vstack, array_equal
circles_1 = [
array([[
[342. , 198. , 28.600698],
[ 58. , 166. , 28.600698],
[282. , 82. , 28.600698]]], dtype=float32),
array([[
[ 78... | python|numpy | 0 |
12,134 | 48,515,725 | np.sum and np.add.reduce - in production, what do you use? | <p>As a background, please read this quick post and clear answer:
<a href="https://stackoverflow.com/questions/16420097/what-is-the-difference-between-np-sum-and-np-add-reduce">What is the difference between np.sum and np.add.reduce?</a></p>
<p>So, for a small array, using <code>add.reduce</code> is faster. Let's take... | <p>I don't think I've used <code>np.add.reduce</code> when <code>np.sum</code> or <code>arr.sum</code> would do just as well. Why type something longer for a trivial speedup.</p>
<p>Consider a 1 axis sum on a modest size array:</p>
<pre><code>In [299]: arr = np.arange(10000).reshape(100,10,5,2)
In [300]: timeit np.... | python|numpy | 3 |
12,135 | 48,523,773 | Substitute deep loops in Python | <p>Unfortunately, I often have while loops in my Python code that cause my programs to slow down significantly.</p>
<p>The following is an example of a while loop (<code>shape = (1000,1000,3)</code>):</p>
<pre><code>i = 0
j = 0
while i < arr.shape[0]:
while j < arr.shape[1]:
if arr[i,j,0] <= 5 an... | <p><strong>EDIT</strong>
In my hurry, my previous answer was incorrect. Thanks to @gboffi for pointing it out.</p>
<h2>Part 1</h2>
<pre><code>def original(arr):
i = 0
j = 0
while i < arr.shape[0]:
while j < arr.shape[1]:
if arr[i,j,0] <= 5 and arr[i,j,0] > 0:
... | python|numpy|while-loop | 1 |
12,136 | 51,702,669 | Make personnal Dataloader with PYTORCH | <p>I'm searching to create a personnal dataloader with a specific format to use Pytorch library, someone have an idea how can I do it ? I have follow Pytorch Tutorial but I don't find my answer!</p>
<p>I need a DataLoader that yields the tuples of the following format:
(Bx3xHxW FloatTensor x, BxHxW LongTensor ... | <p>You simply need to have a database derived from <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset" rel="nofollow noreferrer"><code>torch.utils.data.Dataset</code></a>, where <code>__getitem__(index)</code> returns a tuple <code>(x, y, y_cls)</code> of the types you want, pytorch will take c... | image-processing|deep-learning|computer-vision|pytorch|image-segmentation | 1 |
12,137 | 51,851,144 | Selecting date and time within a dataframe in pandas | <p>I have a dataframe that looks like this</p>
<pre><code> Date MBs GBs
0 2018-08-14 20:10 32.00 MB 0.00 GB
1 2018-08-14 20:05 4.00 MB 0.00 GB
2 2018-08-14 20:00 1000.99 MB 1.23 GB
</code></pre>
<p>Ive already done this : </p>
<pre><code>na_aus['Date'] = pd.to_datetime(na_au... | <p>use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow noreferrer"><code>.between</code></a>:</p>
<pre><code>na_aus.loc[na_aus['Date'].between('2018-08-14 19:50','2018-08-14 20:10')]
</code></pre>
<p>In your case, all rows satisfy the requirement:</p>
<pre><c... | python|pandas|dataframe | 1 |
12,138 | 51,818,081 | Running Image Matching service with FaceNet on GPU using GUNICORN and FLASK issue | <p>I'm trying to create an inference server using FLASK APIs for the Facenet model for an image matching task. I'm using Gunicorn for scaling the server and the server gets images from the client using a POST request in the form of a string sequence. The server gets that image and matches it with an image from a mongod... | <p>The problem of only the 1st GPU got used is that by default, even if Tensorflow can see all 4 GPUs, it will only use the 1st one.</p>
<p>Here although Gunicorn sent several calls and each call tries to invoke its Tensorflow, they all see 4 GPUs and use the 1st one.</p>
<p>I think one possible solutions is to have ... | tensorflow|flask|gpu|gunicorn|gevent | 0 |
12,139 | 41,809,850 | How to increase multi dimension of array in tensorflow? | <p>I have a txt file which has 8 columns and I am selecting 1 column for my feature extraction which gives me 13 features values, the shape of output array will be [1x13].
Similarly I have 5 txt files in a folder I want to run a loop so that the returned variable will have 5x13 data. </p>
<pre><code>def loadinfofromfi... | <p>each loop creates pool and poolfinal from sctratch. That's why you see only one data in poolfinal.
instead please try following:</p>
<pre><code>pools = []
for ...:
pools.append(...)
poolfinal = tf.concat_v2(pools, axis=0)
</code></pre> | python|arrays|multidimensional-array|tensorflow|concat | 0 |
12,140 | 64,446,920 | creating graph with raw data - Python - Pandas | <p>I am trying to show the Average Order Value across various months within a graph.
The raw data is stored within a variable called ikdf, and contains the following columns:</p>
<pre><code>Invoice Number, Invoice Date, Product Name, Invoice Quantity, Item Amount
11241, 24/07/2020, Batten Strip, 10, £29
11241, 24/07/20... | <p>You should use <code>datetime</code> type:</p>
<pre><code>df['month'] = pd.to_datetime(df['Invoice Date']).dt.month
plot_data = df.groupby(['Invoice Number', 'month'])['Item Amount'].sum().unstack('month')
plot_data.plot()
</code></pre> | python-3.x|pandas|dataframe|pandas-groupby | 1 |
12,141 | 64,534,762 | Divide a column with other columns except itself in pandas dataframe | <p><a href="https://i.stack.imgur.com/bmUov.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bmUov.png" alt="Attached image" /></a></p>
<p><code>df_top4</code> as below</p>
<p>I have a dataframe (<code>df_top4</code>) as below and I want to divide the entire row by total, without dividing it by itself... | <p>Use:</p>
<pre><code>mask = df.columns.str.contains('Student')
df.loc[:, mask] = df.loc[:, mask].div(df['Total'], axis=0)
</code></pre> | python|pandas|dataframe | 1 |
12,142 | 49,283,031 | Exporting trained TensorFlow models to C++ | <p>I am trying to export trained TensorFlow models to C++ using <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py" rel="nofollow noreferrer">freeze_graph.py</a>. I am trying to export the ssd_mobilenet_v1_coco_2017_11_17 model using the following syntax:</p>
<pre><co... | <p>in order to export object detection models I use the export_inference_graph.py code in research/object-detection. Here's an example of running the code:</p>
<pre><code>python3 export_inference_graph.py \
--input_type image_tensor \
--pipeline_config_path path/to/model.config \
--trained_checkpoint_prefix path/t... | python|c++|tensorflow|bazel | 0 |
12,143 | 59,025,293 | How to check if tfjs model is loaded to browser properly | <p>im trying to do text classification, loaded the model back to browser by </p>
<pre><code>async function loadFile(){ const jsonUpload = document.getElementById('json-upload');
model = await tf.loadLayersModel(tf.io.browserFiles([jsonUpload.files[0], weightsUpload.files[0]]));
model.summary();
</code></pre>
<... | <p>You can use the official Tensor Flow Vis API to check if the model is loaded.</p>
<p>Add this to your html code:</p>
<pre class="lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-vis@1.0.2/dist/tfjs-vis.umd.min.js"></script>
</code></pre>
<p>and in your j... | tensorflow.js | 0 |
12,144 | 58,805,427 | How to determine the highest value from multiple columns using Pandas | <p>The code below is example of how I have been attempting to find out what the highest value from multiple columns is, and then putting the highest value into a newly created column, using pandas.</p>
<pre><code>def Alphabet (row):
AlpFields = ["A", "B", "C", "D", "E", "F"]
Alp = len(AlpFields)
AlpCheck =... | <p>For your dataframe <code>df</code> you can call the <code>max</code> function for the column axis and assign the result to a new column.</p>
<p>Say that you need the maximum among only specific columns, then the code would be</p>
<pre><code>df['HighestAlphabetScore'] = df[["A", "B", "C", "D", "E", "F"]].max(axis=1... | python|pandas | 1 |
12,145 | 58,742,903 | Getting an error where float object is not iterable | <p>Hi I am new to <code>python and pandas</code>. Here I have the data in the following format </p>
<pre><code>A B
[2000.0, 2000.0] [2200.0, 0.0, 2200.0]
[2200.0, 0.0, 0.0] [2200.0, 2200.0, 2200.0]
[2200.0, 2200.0, 2200.0] [2200.0, 2200.0, 2200.0]
[200.0, 200.0, 200.0] ... | <p>I think you can replace missing values by empty lists before comparing:</p>
<pre><code>df_out[['A','B']] = df_out[['A','B']].applymap(lambda x: [] if x != x else x)
</code></pre>
<p>Or:</p>
<pre><code>df_out[['A','B']] = df_out[['A','B']].applymap(lambda x: x if isinstance(x, list) else [])
#alternative
#df_out[[... | python|python-3.x|pandas|numpy | 1 |
12,146 | 58,963,119 | Numpy array changing list element | <pre><code>import numpy as np
a = np.arange(20)
print('a:', a)
L1 = []
L1.append(a)
print('L1:', L1)
a[-8:17:1] = 1
print('a:', a)
L1.append(a)
print('L1:', L1)
</code></pre>
<p>And output of above is -</p>
<pre><code>a: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
L1: [array([ 0, 1, 2, 3, ... | <p>Variable <code>a</code> is not a simple data type (np.array), so when you assign or, in your case, append it to a variable, you are not appending a copy, but a reference to the object. Hence, any change on the object will be reflected everywhere it is referenced.</p>
<p>Using <code>a.copy()</code> should solve your... | python|arrays|list|numpy | 0 |
12,147 | 70,234,646 | What is the fastest way to create one a multilevel pandas dataframe made from multiple dataframes? | <p>Basically I am doing the following and I think there is probably a faster way than doing pd.concat and df.append in every loop?</p>
<pre><code>final_df = pd.DataFrame()
for (key, data, date) in data_tuples:
df = pd.DataFrame(data, columns=['Price', 'Quantity'])
timestamp = datetime.strptime(date, '%a, %d %b ... | <p>to avoid append and concat at each step you could:</p>
<ol>
<li>create iterator from your data of tuples</li>
<li>apply method on the iterator to parse dataframe and prepare it to the required format</li>
<li>apply pd.concat once on the list of dataframes.</li>
</ol>
<p>of course, you need to modify the logic to mee... | python|pandas|multi-index | 1 |
12,148 | 70,217,623 | Matplotlib: histogram with multiple bars | <p>I cannot seem to grasp how to draw multiple bar histograms. This is my code:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as mpl
tags = 'manual (4 serv.)', 'Cromlech (average, 4 serv.)', 'Cromlech (0.925, 4 serv.)', 'Cromlech (0.925 improved, 7 serv.)', 'Cromlech (15 serv.)', 'Pangae... | <p>It looks like you want to create a bar plot, not a histogram.</p>
<p>In this case, the grouping, the labels and the legend are easiest if you create a <a href="https://pandas.pydata.org" rel="nofollow noreferrer">pandas</a> <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html" rel="nofollow ... | python|pandas|matplotlib|data-visualization | 2 |
12,149 | 56,093,725 | How we can convert keras model .h5 file to tensorflow saved model (.pb) | <p>I have a keras model trained and saved it in h5 format. I want to host this model on google cloud ml engine for prediction.
How can i convert keras model .h5 file to saved model.</p> | <p>The post where I have seen this code(although I have seen this solution in many other posts) is this: <a href="https://www.dlology.com/blog/how-to-convert-trained-keras-model-to-tensorflow-and-make-prediction/" rel="nofollow noreferrer">https://www.dlology.com/blog/how-to-convert-trained-keras-model-to-tensorflow-an... | tensorflow | 0 |
12,150 | 64,994,765 | Finding Value in Table and Change Value for all Duplicates | <p>I have a dataframe like this</p>
<pre><code>Subject Special Mutated
dog Y N
dog Y N
dog N Y
dog N Y
cat Y N
cat N Y
cat N Y
bird N Y
bird N Y
</code></pre>
<p>I want to check if one of the <code>Subject</code> has the ... | <p>Let us try <code>transform</code></p>
<pre><code>df['Special'] = df.groupby(['Subject'])['Special'].transform('max')
Out[316]:
0 Y
1 Y
2 Y
3 Y
4 Y
5 Y
6 Y
7 N
8 N
Name: Special, dtype: object
</code></pre>
<p>Why it work</p>
<pre><code>'Y'>'N'
Out[317]: True
</code></pre> | python|pandas | 0 |
12,151 | 64,935,532 | Pandas stacked bar creating many individual plots with incorrect bottom values | <p>Given a Dataframe (this is generated from a csv that contains the names and orders and updated everyday):</p>
<pre><code># Note that this is just an example df and the real can have N names in n shuffled orders
df = pd.read_csv('names_and_orders.csv', header=0)
print(df)
names order
0 mike 0
1 jo ... | <p>I think you're overthinking this. Just <code>unstack</code> the groupby and plot:</p>
<pre><code>df_count = df.groupby(['order', 'names']).size().unstack('names')
df_count.plot.bar(stacked=True)
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/u3bdM.png" rel="nofollow noreferrer"><img src="https://... | python|pandas|matplotlib | 2 |
12,152 | 64,980,914 | Using SSIM loss in TensorFlow returns NaN values | <p>I'm training a network with MRI images and I wanted to use SSIM as loss function. Till now I was using MSE, and everything was working fine. But when I tried to use SSIM (tf.image.ssim), I get a bunch of these warining messages:</p>
<pre><code> /usr/local/lib/python3.7/dist-packages/matplotlib/image.py:397: UserWarn... | <p>In my experience this warning is typically related to attempting plotting a point with a coordinate at infinity. Of course you should really show us more code for us to help you effectively.</p> | python-3.x|tensorflow2.0|loss-function|ssim | 1 |
12,153 | 64,750,708 | Training loss or test loss? | <p>In order to manipulate metrics of my model , I would like to know, I saw loss on <code>federated_train_data</code> or loss on <code>federated_test_data</code> ?
I read this :</p>
<blockquote>
<p>Training loss looks much better than evaluation loss: when using Federated Averaging (the optimization algorithm used in t... | <p>There is nothing inherently good or bad about the options you outline. It computes the same metrics, based on different data. Which one is "better" really depends on what you need it for.</p>
<hr />
<p>The cited paragraph does not refer to the metrics from evaluation as you outline below, but to the metric... | tensorflow-federated | 1 |
12,154 | 64,944,272 | Summing values in a dataframe over row labels | <p>i have a dataframe of the following form</p>
<pre><code> index FACTOR1 FACTOR2 FACTOR3
0 ECON1 -0.068475 -0.000000 -0.000000
1 ECON2 0.000000 0.056963 0.000000
2 ECON2 0.000000 0.000000 0.041488
3 FOOD1 0.018582 0.000000 0.000000
4 FOOD2 -0.000000 -0.000000 ... | <p>IIUC you can <code>extract</code> the group names and <code>sum</code>:</p>
<pre><code>print (df.assign(group=df["index"].str.extract("([A-Z]+)"))
.groupby("group").sum())
</code></pre>
<p>Or using your list of labels:</p>
<pre><code>labels=['ECON', 'FOOD', 'ENV', 'HEA', 'PERS'... | python-3.x|pandas|numpy|sum|label | 2 |
12,155 | 64,828,120 | Pandas: Fill gaps in a series with mean | <p>Given df</p>
<p><code>df = pd.DataFrame({'distance': [0,1,2,np.nan,3,4,5,np.nan,np.nan,6]})</code></p>
<pre><code> distance
0 0.0
1 1.0
2 2.0
3 NaN
4 3.0
5 4.0
6 5.0
7 NaN
8 NaN
9 6.0
</code></pre>
<p>I want to replace the nans with the inbetween mean</p>... | <p>If you don't want <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.interpolate.html" rel="nofollow noreferrer"><code>df.interpolate</code></a> you can compute the mean of the surrounding values manually with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/panda... | python|pandas|dataframe | 2 |
12,156 | 64,978,365 | Flattening List of Lists Column Following Pandas Groupby | <p>I have a pandas dataframe containing IDs and Codes which are of type list:</p>
<pre><code>df = pd.DataFrame({'ID': [1, 1, 1, 2, 2, 3, 3, 4], 'Code': [['A', 'B'], ['A', 'B'], ['A', 'B', 'C'],
['A'], ['A'], ['A', 'C'], ['D', 'C'], ['A', 'D']]})
</code></pre>
<p>I would like to groupby ID and get a ... | <p>Try this.You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.hstack.html" rel="nofollow noreferrer">np.hstack</a> to Stack arrays in sequence horizontally.</p>
<pre><code>import numpy as np
df_groupby["Code"] = df_groupby["Code"].apply(lambda x: np.hstack(x))
</code></pre>... | pandas|pandas-groupby|flatten | 1 |
12,157 | 64,832,305 | Converting Date Difference to Integer | <p>I have a pandas dataframe which contains two date columns and I want to derive a column containing the difference between the two dates:</p>
<pre><code>cm['Duration'] = cm['EndDate'] - cm['StartDate']
</code></pre>
<p>This newly created column is actually of type datetime.timedelta whereas I just want it to be an in... | <pre><code>cm['Duration'] = (cm['EndDate'] - cm['StartDate']).apply(lambda s: s.days)
</code></pre> | python|pandas | 2 |
12,158 | 44,050,728 | Speedup address concatenation from pandas dataframe | <p>I have a dataframe with about 30 columns and several million rows. A subset of those columns are address items, e.g.</p>
<pre><code> premises address_line_1 address_line_2 locality region postal_code country
77 Compton Street NaN Bradford NaN BD4 9NE Unite... | <p>This will probably accept some further optimization, but should produce the same result if you do not have your separator in any of the fields listed in items, and it is much faster.</p>
<pre><code>df[items[0]].fillna('').astype(str).str.cat(others=[df[item].fillna('').astype(str) for item in items[1:]], sep=',').s... | python|pandas | 3 |
12,159 | 69,446,224 | Showing wrong axis in 2D array when value is out of range | <p>I have a 2D array (row*column)row means axis0 and column mean aixs1.</p>
<p>example:</p>
<pre><code>a=np.array([[10,20,30],[40,50,60]])
</code></pre>
<p>now when I am trying to access the value(out of range along axis 0)I am getting below Exception which is correct.</p>
<pre><code>print(a[-3][-1])
IndexError: i... | <p>This is because you first subset <code>a</code> to a vector, which is 1 dimensional.</p>
<pre><code>>>> a[-2]
array([10, 20, 30])
>>> np.array([10, 20, 30])[5]
IndexError: index 5 is out of bounds for axis 0 with size 3
</code></pre>
<p>However if you slice both dimension at once, you get the expe... | python|numpy|numpy-ndarray|numpy-slicing|numpy-indexing | 3 |
12,160 | 69,542,277 | How do I get API data into a Pandas DataFrame? | <p>I am pulling in betting data from an API and I would like to get it into a DataFrame. I would like the DataFrame to have the following columns: [away_team, home_team, spread, overUnder] I am using the following code:</p>
<pre><code>import cfbd
configuration = cfbd.Configuration()
configuration.api_key['Authorizatio... | <p>You could iterate over the json data, extracting the information that you need and creating a new structure to hold this data. After iterating over all your data, you can create a dataframe from what you extracted.
I made an example using a dataclass to store the data you need:</p>
<pre class="lang-py prettyprint-ov... | pandas|dataframe|api | 2 |
12,161 | 40,855,900 | pandas rename index values | <p>I have the following dataframe in pandas (python):</p>
<pre><code> B. X. Y.
A
alpha 3. 5. 5
beta 9. 9. 11
</code></pre>
<p>I want to change 'alpha' for another name, like 'mu'. What should I do?</p> | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html" rel="noreferrer"><code>rename</code></a> with parameter <code>index</code><br>
pass a dictionary to the <code>index</code> parameter</p>
<pre><code>df.rename(index={'alpha': 'mu'})
</code></pre>
<p><a href="https://i.s... | python|pandas | 48 |
12,162 | 66,032,671 | Is it possible to slice an array to sort of go backwards? | <p>I have an array of longitude values that goes from 0 to 360 in increments of 1.</p>
<p>As an example:</p>
<pre><code>longitude = np.arange(1,361,1)
print(longitude)
[ 1 2 3 4 5 6 7 8 9 ... 360]
</code></pre>
<p>Is there a way to slice the longitude array so that I only include 1:20 and 275:360 in... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.r_.html#numpy-r" rel="noreferrer">np.r_</a>:</p>
<pre><code> longitude[np.r_[1:10, 275:360]]
</code></pre>
<p>Output:</p>
<pre><code>array([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 276, 277, 278, 279,
280, 281, 282, 283, 284, 285, 286, 28... | python|arrays|numpy|jupyter | 5 |
12,163 | 66,145,129 | Individual values are summed instead of whole column | <p>I based my script largely off of <a href="https://stackoverflow.com/questions/59606758/beautifulsoup-requests-dataframe-saving-to-excel-arrays-error">the chitown88 answer of this question</a>. My script is meant to pull lock (i.e. lock and dam) data from XMLs on the Army Corps of Engineers website using BeautifulSou... | <p>I think change the position of where you are applying total, and convert to numeric datatype in order to sum correctly</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import pandas as pd
from pandas import ExcelWriter
from datetime import datetime
import os
#set the headers as a browser
headers = {'Use... | python|pandas|beautifulsoup | 1 |
12,164 | 66,088,290 | Use a categorical column to order the dataframe according to an array | <p>I have an array like this:</p>
<pre><code>['A 100', 'A 200', 'A 300', 'A 400', 'A 500', 'B 100', 'B 200', 'B 300', 'B 400']
</code></pre>
<p>I also have a dataframe like this:</p>
<pre><code>BIN CA SUM
100 B B 100
300 A A 300
300 B B 300
400 B B 400
400 A ... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.Categorical.html" rel="nofollow noreferrer"><code>pd.Categorical</code></a> to convert the <code>SUM</code> column to categorical column having order, then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pa... | python|pandas|dataframe|categorical-data | 3 |
12,165 | 66,027,353 | Tensorflow on Python 64bit version not working | <p>I have installed Python 3.9.1 and also installed a lot of packages, like sklearn, selenium, etc., but I am failing to install tensorflow. When I type in <code>pip install tensorflow</code> an error is thrown:</p>
<p>ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none)
ERROR... | <p>TensorFlow pip packages are compatible with <code>Python 3.5–3.8</code> and not with <code>Python 3.9</code> as of yet, this <a href="https://github.com/tensorflow/tensorflow/issues/44485" rel="nofollow noreferrer">thread</a> covers the discussion on the release date of a compatible version. Therefore you would have... | python|tensorflow | 2 |
12,166 | 66,096,801 | Can the input shape and the number of neurons be different in a Neural Network? | <p>In the book "Deep Learning with Python" by Francois Chollet, I found a piece of code which had input shape as 784 and units as 32?</p>
<p>I was wondering how they be can different.</p>
<p>Here's the exact piece of code:</p>
<pre><code>from keras import layers
from keras import models
model = models.Sequent... | <p>Input_shape is a shape of the Dense layer input. Units - is a shape of the Dense layer output. Basically - they are two different dimensions of the weights matrix.</p> | tensorflow|machine-learning|keras|neural-network | 1 |
12,167 | 52,596,540 | Pivoting a Pandas Dataframe on Categorical Variables | <p>I have a dataframe containing categorical variables:</p>
<pre><code>{'SysID': {0: '00721778',
1: '00721778',
2: '00721778',
3: '00721779',
4: '00721779'},
'SoftwareComponent': {0: 'AA13912',
1: 'AA24120',
2: 'AA21612',
3: 'AA30861',
4: 'AA20635'},
'SoftwareSubcomponent': {0: None,
1: 'AK21431',
2: None,
3: 'AK22116... | <p>You can use <code>pd.crosstab</code> after doing a bit of cleanup. We will stack (which will ignore all of the <code>None</code> values) and create the column names as you want to treat SofwareCom and SoftwareSub the same.</p>
<pre><code>import pandas as pd
df = df.set_index('SysID').stack().reset_index(level=1)
d... | python-3.x|pandas|pivot|categorical-data | 1 |
12,168 | 52,870,728 | Pandas: check if any of the values in a subset of a column respect condition | <p>I have a dataframe containing a datetime column, a condition, a counter of how many consecutive times such condition happens, and a value column. It looks like:</p>
<pre><code>date condition count Value
01,01,2018 08:00 A 1 9
01,01,2018 08:01 ... | <p>Try this:</p>
<pre><code>df.loc[(df['condition']=='B')&(df['count']<=3),'error']=1
</code></pre>
<p><strong>Demo (do as full code):</strong></p>
<pre><code>df = your data
df['error']=0
df.loc[(df['condition']=='B')&(df['count']<=3),'error']=1
print(df)
</code></pre>
<p>Output:</p>
<pre><code> ... | python|pandas | 1 |
12,169 | 46,630,171 | How to design the output layer of word-RNN model with use word2vec embedding | <p>I try to build a Word-RNN equivalent of Char-RNN, the net should generate next word in a sentence.</p>
<p>As input I use pre-trained word2vec 100-dim vectors, hidden layer size is 200. My main problem is output layer, how it should be designed?</p>
<p>In char-rnn, output it is vocabulary size(number of unique char... | <p>You can output an index of a word (per example), thus avoid one-hot word representation (which is indeed very big). Use <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/legacy_seq2seq/sequence_loss_by_example" rel="nofollow noreferrer"><code>tf.contrib.legacy_seq2seq.sequence_loss_by_example</code></a>... | python|tensorflow|neural-network|recurrent-neural-network|word2vec | 1 |
12,170 | 46,586,962 | Pandas filtering floating point to digit | <p>I'm using Pandas to analyze my data. I have this dataframe consisting elapsed_seconds and m(magnitude). Is there a way for me to group-by the five digit of the float number(elapsed_seconds) and find the mean of m?</p>
<p>Example:</p>
<pre><code>elapsed_seconds,m
10769.001,0.373637934043
10769.027,0.373403294813
10... | <p>You can convert <code>float</code> column to <code>int</code> and then <code>groupby</code> and aggregate <code>mean</code>:</p>
<pre><code>df = df.groupby(df['elapsed_seconds'].astype(int))['m'].mean().reset_index()
print (df)
elapsed_seconds m
0 10769 0.378549
</code></pre> | python|pandas|dataframe|mean|pandas-groupby | 1 |
12,171 | 58,547,571 | Tensorflow dependencies: tensorflow 1.15.0 has requirement tensorboard<1.16.0,>=1.15.0 : What's the solution? | <p>I have this list of dependencies:</p>
<pre><code>absl-py==0.7.0
bleach==1.5.0
click==6.7
cycler==0.10.0
decorator==4.2.1
futures==3.1.1
h5py==2.7.1
html5lib==0.9999999
imageio==2.2.0
Keras==2.1.5
Markdown==2.6.11
matplotlib==3.1.1
networkx==2.1
numpy==1.16.0
Pillow==5.0.0
pip-autoremove==0.9.0
protobuf==3.7
pyparsin... | <p>Uninstall conflicting dependencies. For <code>tensorflow</code> it would be:</p>
<pre><code>pip uninstall tensorflow tensorflow-tensorboard tensorflow-estimator
</code></pre>
<p>(maybe there are some more, not sure).</p>
<p>Secondly, reinstall <code>tensorflow</code> by issuing (change pinned version to whatever ... | python|tensorflow|dependencies|dependency-management | 5 |
12,172 | 58,402,114 | Columns rename: switching between numbers and letters | <p>My dataframe:</p>
<pre><code>X Y 123_Z 1234_Z 123_Z_R 1234_Z_R
. . . . . .
. . . . . .
</code></pre>
<p>I want to rename the columns in the data by switching the numbers and letters.</p>
<p>Expected result:</p>
<pre><code>X Y Z_123 Z_1234 Z_R_123 Z_R_1234... | <p>Maybe this works</p>
<pre><code>df.columns = map(lambda s: '_'.join(s[1:] + [s[0]]) if s[0].isdigit() else '_'.join(s), df.columns.str.split('_'))
</code></pre>
<hr>
<pre><code>Columns: ['X', 'Y', 'X_Y', 'Z_123', 'Z_1234', 'Z_R_123', 'Z_R_1234']
</code></pre> | python|pandas|dataframe | 3 |
12,173 | 58,201,161 | How to iterate through cells in excel from python | <p>I want to write the average between two columns(Max and Min) into another column(Mean) for each row.
Specifically, as it iterates through rows, determine the mean from first 2 cells and write this into the cell of the 3rd row.</p>
<pre><code>import pandas as pd
from pandas import ExcelWriter
from pandas import Exc... | <p>Try this:</p>
<pre><code>df = pd.read_excel('tempMean.xlsx', sheet_name='tempMeanSheet')
mean = [(row["Min"] + row["Max"]) / 2 for index, row in df.iterrows()]
df = df.assign(Mean=mean)
</code></pre> | python|excel|pandas | 0 |
12,174 | 69,277,385 | Remove rows from a data frame based on the value of another data frame | <p>I would like to know how can I do this,</p>
<p>I have a dataframe like this one:</p>
<p><strong>df1</strong></p>
<pre><code>Tweet Other columns ....
------- ----------- -----
"Hello world" ... ...
"Good morning" ... ...
"Hi" ... | <p>Maybe try <code>np.where</code>:</p>
<pre><code>df2['Tweet'] = np.where(df2['Tweet'].isin(df1['Tweet']), df1['Tweet'], df2['Tweet'])
</code></pre>
<p>Or shorter use <code>loc</code>:</p>
<pre><code>df2.loc[df2['Tweet'].isin(df1['Tweet']), 'Tweet'] = df1['Tweet']
</code></pre> | python|pandas|dataframe | 0 |
12,175 | 69,195,717 | How to create pandas dataframe out of two lists | <p>I have a dataset like below:</p>
<pre><code>campaign_name,campaign_team
edbol97,other
abc_de_dg,other
de_air,other
</code></pre>
<p>Out of this, I have to pick up the <code>campaign_name</code> where records contain <code>"_"</code>. Now, I want to split the underscore containing records into words. I was... | <p>You can use .explode() for this:</p>
<pre><code>df['campaign_name1'] = df['campaign_name'].str.split('_')
df.explode('campaign_name1')
</code></pre> | python|pandas | 1 |
12,176 | 69,061,819 | Retrieve most frequent value for each couple of values | <p>I'm working with a df having 3 columns: 'Latitude', 'Longitude' and 'street_type'.</p>
<p>The 'street_type' column has multiple values like 'rectilinear', 'roundabout' exc.</p>
<p>I would like to retrieve the most frequent value for each couple of values 'Latitude' and 'Longitude'.</p>
<p>I tried using the group by ... | <p>Use custom lambda function for first <code>mode</code>:</p>
<pre><code>df = (df.groupby(['Latitude', 'Longitude'])['street_type']
.agg(lambda x: x.mode().iat[0])
.reset_index())
</code></pre> | python|pandas|dataframe|pandas-groupby | 0 |
12,177 | 69,220,221 | Use of torch.stack() | <pre><code>t1 = torch.tensor([1,2,3])
t2 = torch.tensor([4,5,6])
t3 = torch.tensor([7,8,9])
torch.stack((t1,t2,t3),dim=1)
</code></pre>
<p>When implementing the torch.stack(), I can't understand how stacking is done for different dim.
Here stacking is done for columns but I can't understand the details as to how it is... | <p>Imagine have <code>n</code> tensors. If we stay in 3D, those correspond to volumes, namely <em>rectangular cuboids</em>. Stacking corresponds to combining those <code>n</code> volumes on an additional dimension: here a 4th dimension is added to host the <code>n</code> 3D volumes. This operation is in clear contrast ... | python|pytorch|tensor | 5 |
12,178 | 44,718,833 | unorderable types: str() < tuple() when train pet detector by google object detection api | <p>I train pet detector by google object detection api and get error as fellow:Does it mean sorted fun does not support the dict's key type is tuple and the object detection api still does not support python3? </p>
<pre><code>Traceback (most recent call last):
File "D:\Program Files\JetBrains\PyCharm 2017.1.1\helper... | <p>I ran into the same problem. I traced the issue down to a python 3 compat issue in TensorFlow. I have submitted a fix for it here: <a href="https://github.com/tensorflow/tensorflow/pull/11039" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/pull/11039</a></p> | tensorflow|detection | 1 |
12,179 | 61,160,487 | A custom layer in Keras returns NaN as a gradient. What are some potential issues causing this? | <p>I work on a project where we try to reconstruct a 2D image from geometric primitives. To this end, I have developped a custom Keras layer which outputs an image of a cone given its geometric charcteristics.</p>
<p>Its input is a tensor of shape batch_size * 5, where the five numbers are the xy coordinates of the ap... | <p>First of all, I answer my own question and leave it there in case it may help someone in the future. I don't know if this is the generally agreed upon etiquette at StackOverflow.</p>
<p>By commenting the successive steps of the call function, I found out that the issue was with <code>tf.math.acos</code>. In the cod... | tensorflow|keras|neural-network|gradient|tensorflow2.0 | 0 |
12,180 | 71,462,468 | Altering pytorch resnet head from sigmoid to Softmax | <p>I'm new to pytorch. I wrote the below code to do predication using Resnet with Sigmoid for binary classification. I just need to change it to softmax because I might have more than 2 classes.</p>
<p>I understood that pytorch, unlike, Keras, the softmax is in the <em><strong>CrossEntropyLoss</strong></em>. So I'm not... | <p>You can try this:</p>
<pre><code>model.fc[1] = torch.nn.Softmax(10)
</code></pre>
<p>where 10 are the number of classes, you can put value based on your needs.</p> | python|keras|deep-learning|pytorch | 1 |
12,181 | 71,581,197 | What is the loss function used in Trainer from the Transformers library of Hugging Face? | <p>What is the loss function used in Trainer from the Transformers library of Hugging Face?</p>
<p>I am trying to fine tine a BERT model using the <strong>Trainer class</strong> from the Transformers library of Hugging Face.</p>
<p>In their <a href="https://huggingface.co/docs/transformers/main_classes/trainer" rel="no... | <p>It depends!
Especially given your relatively vague setup description, it is not clear what loss will be used. But to start from the beginning, let's first check how the default <code>compute_loss()</code> function in the <code>Trainer</code> class looks like.</p>
<p>You can find the corresponding function <a href="h... | python|machine-learning|nlp|artificial-intelligence|huggingface-transformers | 3 |
12,182 | 71,534,299 | Pandas: How to merge the ith elements of lists from different DataFrame columns? | <p>I have a Panadas dataframe that looks like this:</p>
<pre><code>df = pd.DataFrame({
'a':[['Often'],['Not Often','Not Often','Often'],['Somewhat Often','Never']],
'b':[['j0003'],['j0002','j0005', 'j0006'],['j0009','j0010']],
'c':[['jump'],['skip', 'throw', 'stab'],['walk','sleep']]
})
</code></pre>
<p><strong>I want ... | <p>This can be done very easily with <code>explode</code>. Just explode all the columns, then convert each row into a tuple, then re-combine the tuples into lists:</p>
<pre><code>merged_df = df.explode(df.columns.tolist()).apply(tuple, axis=1).groupby(level=0).agg(list).to_frame('Merged_Column')
</code></pre>
<p>Output... | python|pandas|dataframe | 1 |
12,183 | 71,669,952 | Prepare for Binary Masks used for the image segmentation | <p>I am trying to prepare the masks for image segmentation with Pytorch. I have three questions about data preparation.</p>
<ol>
<li><p>What is the appropriate data format to save the binary mask in general? PNG? JPEG?</p>
</li>
<li><p>Is the mask size needed to be set square such as (224x224), not a rectangle such as ... | <ol>
<li>PNG, because it is lossless by design.</li>
<li>It depends. More convenient is to use standard resolution, (224x224), I would start with that.</li>
<li>Use resize without interpolation <code>transforms.Resize((300, 300), interpolation=InterpolationMode.NEAREST)</code></li>
</ol> | pytorch|computer-vision|image-segmentation | 1 |
12,184 | 42,518,744 | Making a list and appending to it in TensorFlow | <p>I am new to TensorFlow. I'm not able to understand how to create a dynamic "pythonic" list in TensorFlow. Basically, I perform some computation on a tensor object (<code>train_data[i]</code>) and append it to a "list" <code>X</code>, which I want to be a tensor with shape <code>(100,)</code></p>
<p>I want to do som... | <p>If you want to convert <code>X</code> to a (100,) tensor you could add <code>X = tf.stack(X)</code> after your for loop:</p>
<pre><code>X = []
for i in range(100):
q = tf.log(train_data[i])
print(q) #Tensor("Log:0", shape=(), dtype=float32)
X.append(q)
X = tf.stack(X)
</code></pre>
<p>This is a useful c... | python|tensorflow | 13 |
12,185 | 70,005,612 | How do you modify columns in Pandas via method chaining? | <p>What is the best pandas method to apply specific functions to specific columns?</p>
<p>Let</p>
<pre><code>df = pd.DataFrame({'A':[1,2,3], 'B':[1,2,3], 'C':[1,2,3]})
</code></pre>
<p>Suppose I want to double the values in column <code>'A'</code> and halve the values in column <code>'B'</code>, and keep column <code>'... | <p>The latter code you propose is absolutely not an abuse: <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>assign</code></a> accepts a callable and there is even an example in the documentation.</p>
<pre><code>>>> df.assign(temp_f=lambda x: x.... | pandas | 3 |
12,186 | 69,744,155 | Transform a section within a nested Json in a Pandas dataframe column into another dataframe | <p>I'm working on a Pandas dataframe where I find this Json in a column:</p>
<pre><code>quote
{'BTC': {'price': 1, 'volume_24h': 1e-08, 'percent_change_1h': 0, 'percent_change_24h': 0, 'percent_change_7d': 0, 'market_cap': 11071985.881444559, 'fully_diluted_market_cap': None, 'last_updated': '2013-04-29T00:00:01.000Z'}... | <p>As your JSON is nested, you will get only 2 columns of the highest level sections <code>BTC</code> and <code>USD</code> even when we expand the JSON into dataframe. As such, we have to specifically get access to the part of the data you are interested first, i.e. the <code>USD</code> section.</p>
<p>Optional Step: i... | python|json|pandas|dataframe | 1 |
12,187 | 72,284,428 | How to find next position of a value and count of values between them in pandas dataframe? | <p>I have a dataframe</p>
<pre><code>df = pd.DataFrame({'Position' : [1,2,3,4,5,6,7,8,9,10],
'Decimal' : [3,1,5,1,5,2,3,3,7,2]})
df
</code></pre>
<p><a href="https://i.stack.imgur.com/JSgCZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JSgCZ.png" alt="enter image description here... | <p>What about:</p>
<pre><code>df['nextPosition'] = df.groupby('Decimal', sort=False)['Position'].diff(-1).abs().sub(1).fillna(-1)
print(df)
</code></pre>
<pre><code> Position Decimal nextPosition
0 1 3 5.0
1 2 1 1.0
2 3 5 1.0
3 4 ... | python|pandas|dataframe | 2 |
12,188 | 72,469,258 | Adding a pretrained model outside of AllenNLP to the AllenNLP demo | <p>I am working on the interpretability of models. I want to use AllenAI demo to check the saliency maps and adversarial attack methods (implemented in this demo) on some other models. I use the tutorial <a href="https://github.com/allenai/allennlp-demo#contributing-a-new-allennlp-model-to-the-demo" rel="nofollow noref... | <p>If you are simply interested in getting the output from various saliency interpreters, this <a href="https://guide.allennlp.org/interpret" rel="nofollow noreferrer">guide chapter</a> explains how to use the API (you will not need the front-end demo code for this). If you want to apply the interpreters to your custom... | pytorch|demo|allennlp|interpretation|huggingface | 0 |
12,189 | 50,485,754 | Convert Pandas Dataframe to Dictionary with Tuple Keys for Ternary plot | <p>I am plotting ternary diagrams with <a href="https://github.com/marcharper/python-ternary" rel="nofollow noreferrer">python-ternary</a></p>
<p>My data is in a pandas dataframe. I need to convert it to a dictionary mapping (i, j) to a float as input for the <code>heatmap</code> function in ternary.</p>
<p>My dataf... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_dict.html" rel="nofollow noreferrer"><code>to_dict</code></a>:</p>
<pre><code>... | python|pandas|dictionary|tuples | 4 |
12,190 | 50,418,963 | TensorFlow - How to perform operations without adding them to graph? | <p>I have not been able to find a satisfactory answer to this: How do I perform operations without bloating the graph?</p>
<p>Specifically I want to display some of my output tensors as images. This requires calling session.run() to convert the tensors in numpy arrays. However the session.run() operation gets added to... | <p>This is exactly what placeholders are for. You can make a placeholder for the image and then every time you want to print the best prediction then you feed in the image to that placeholder and calculate whatever it is that you want to calculate. That way it only gets added the graph once.</p> | python|tensorflow | 1 |
12,191 | 45,341,392 | extract the dimensions from the head lines of text file | <p>Please see following attached image showing the format of the text file. I need to extract the dimensions of data matrix indicated by the first line in the file, here 49 * 70 * 1 for the case shown by the image. Note that the length of name "gd_fac" can be varying. How can I extract these numbers as intege... | <p>Specification is not very clear. I am assuming that the information you want will always be in the first line, and always be in parenthesis. After that:</p>
<pre><code>with open(filename) as infile:
line = infile.readline()
string = line[line.find('(')+1:line.find(')')]
lst = string.split('x')
</code></... | python|numpy | 1 |
12,192 | 62,660,828 | How to remove rows from pandas dataframe with an initial date condition | <p>I have a pandas dataframe, one of the columns of which contains dates.</p>
<p>My objective is to set an initial date, <strong>and discard all the rows of the dataframe that are previous to this date</strong>.
Snippet of dataframe:</p>
<pre class="lang-py prettyprint-override"><code> ID fecha
519457 ... | <p>May be something like this:</p>
<pre><code>Date_initial='25/02/2020 10:07:00'
df=df[df["fecha"]>=Date_initial]]
</code></pre>
<p>Also, I recommend using <code>datetime</code> type:</p>
<pre><code>df = pd.read_excel(xls, 'Hoja1', parse_dates=['fecha'], dayfirst=True)
Date_initial = pd.to_datetime('25/02... | python|pandas|dataframe|date|valueerror | 1 |
12,193 | 62,680,455 | How to get Value Counts in Date Time Python | <p>I have the following data frame from where I want to get the value counts for each weekday, i.e., no. of observations on Monday(1), Tuesday(2), etc. I wrote a code but I am getting an error.</p>
<p><strong>DataFrame</strong></p>
<pre><code>rowId UserId Name Date Class TagBased
1 1 ... | <p>You can do:</p>
<pre><code>df.Date.dt.day_name().value_counts()
</code></pre>
<p>Your sample data would give:</p>
<pre><code>Wednesday 5
Name: Date, dtype: int64
</code></pre> | python-3.x|pandas|datetime|group-by|time-series | 1 |
12,194 | 62,853,983 | Pandas extract str in column with regex | <p>I have a dataframe, in one column I want to extract a specific information. Using split it can be done easily but with Pandas I cannot figure out how to do it.</p>
<pre><code>s = pd.Series(['T:15.0(1.71%),B:7.4(0.03%),P:1e-21'])
</code></pre>
<p>I want to extract only 1e-21</p>
<p>I tried</p>
<pre><code>s.str.extrac... | <p>You can try this:</p>
<pre><code>print(s.str.extract('(\d+e-\d+)'))
0
0 1e-21
</code></pre> | python|pandas | 2 |
12,195 | 62,802,917 | Loading PNG files into TensorFlow | <p>I'm trying to load custom made png files I generated to train my model. Following the instruction from TensorFlow guide <a href="https://www.tensorflow.org/guide/data" rel="nofollow noreferrer">here</a>, I used this code:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import numpy as np
... | <p>I suggest reading the png files with tensorflow's builtin io methods. The code snippet below will generate a list of files with .png extension and then iterate over them. During each iteration it reads the file and then decodes the png encoded image</p>
<pre><code>image_dir = 'hypothesis/temp'
image_root = pathlib.P... | python|tensorflow|tensorflow2.0|tensorflow-datasets | 3 |
12,196 | 54,435,100 | Need little support in trimap generation for alpha masking | <p>I am trying to extract out hair from a portrait image. For this I have done following till now:</p>
<ol>
<li>Convert the image into grayscale then to binary</li>
<li>Morphological operation to separate out the hair.</li>
<li>Find contours, sort it, top to bottom, draw the topmost contour only as mask (hair obviousl... | <p>The black line between <code>unknown</code> and <code>sure_fg</code> is because the <code>unknown</code> is eroded at the end with the line</p>
<p><code>unknown = cv2.erode(unknown, kernel, iterations=1)</code></p>
<p>After removing that line, here's the mask created:</p>
<p><a href="https://i.stack.imgur.com/UTt... | python|numpy|opencv|image-processing | 1 |
12,197 | 54,465,230 | Python: DataFrame.melt - How to select a range of columns as the identifier variables? | <p>I'm trying to change the structure of my dataset</p>
<p>Currently have:</p>
<pre><code>RE id Country 0 1 2 ... n
1001 CN,TH CN TH nan ... nan
1002 UK UK nan nan ... nan
</code></pre>
<p>I've split the Country column out, hence the additional columns. Now I am try... | <p>I think the problem was that you were referencing the column names incorrectly. Also, I believe you had <code>id_vars</code> (should be <code>Re id</code>, I think) and <code>value_vars</code> (column names <code>0</code> and <code>1</code>) inverted in your code.</p>
<p>Here is how I approached this</p>
<p>Import... | python|pandas|dataframe|pivot | 0 |
12,198 | 54,688,828 | Optimal way to find index of first occurrence of subarray in each frame of batch data without for loop | <p>I have to find the index of first occurrence of a sub array in each frame.The data is of size (batch_size,400). i need to find the index of occurrence of three consecutive ones in each frame of size 400.
Data-> <code>[0 0 0 1 1 1 0 1 1 1 1 1][0 0 0 0 1 1 1 0 0 1 1 1] [0 1 1 1 0 0 0 1 1 1 1 1]</code></p>
<p>output s... | <p>There is no simple numpy solution for this. However what you can do if you really need it to be fast is the following using <a href="http://numba.pydata.org/" rel="nofollow noreferrer">numba</a>:</p>
<p>The function <code>find_first</code> does basically what you would do with the for loop. But since you are using ... | numpy|for-loop|tensorflow|math|batch-processing | 0 |
12,199 | 73,753,452 | Convert Tensor of hex strings to int | <p>I have a dataset of <code>tf.RaggedTensor</code>s with strings representing hexadecimal numbers that look like this:</p>
<pre><code>[
[[b'F6EE', b'BFED', b'4EEA', b'00EE', b'77AE', b'1FBE', b'1A6E',
b'5AEB', b'6A0E', b'212F'],
...
[b'FFEE', b'FFED', b'FEED', b'FDEE', b'FAAE', b'FFBE', b'FA8E',
b'FAEB', ... | <p>I think you're looking for something like this.</p>
<p>I first create an example tensor with 3D shape, as the one that you have.</p>
<pre><code>import tensorflow as tf
>> a = tf.convert_to_tensor(['F6EE', 'BFED', '4EEA', '00EE', '77AE', '1FBE', '1A6E',
'5AEB', '6A0E', '212F'])
>> b = tf.convert_to_te... | python|tensorflow|hex | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.