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 |
|---|---|---|---|---|---|---|
349,600 | 60,615,416 | How to add column to existing DataFrame with non matching times? | <p>In an existing DataFrame;</p>
<pre><code>2019-12-02 | 1.000000
2019-12-04 | 1.020100
2019-12-05 | 1.030301
2019-12-06 | 1.040604
2019-12-09 | 1.051010
2019-12-10 | 1.061520
</code></pre>
<p>I want to add an new columns based an existing DF or TS, with a non matching index;</p>
<pre><code>2019-12-04 00:00:00 | A... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a>:</p>
<pre><code>df = pd.merge_asof(df1,
df2,
left_index=True,
right_index=True,
toleran... | python|pandas|dataframe|time-series | 3 |
349,601 | 60,749,645 | How come this python pandas dataframe for loop only fills the first row? | <p>I'm working with Spotify's Spotipy library, and trying to build a pandas dataframe of audio features from Spotify's API.</p>
<p>I'm going about this in what I feel is probably a very inefficient (slow) way, but as of now I've got a dataframe <code>pddf</code>, and I want to access the API to pull audio features for... | <p>Change your last row </p>
<pre><code>pddf = pd.concat([audio_features, pddf], axis=0)
</code></pre> | python|pandas|dataframe|spotipy | 1 |
349,602 | 60,521,877 | Getting Tensorflow To Run Faster | <p>I have developed a machine learning python script (let's call it classify_obj written with python 3.6) that imports TensorFlow. It was developed initially for bulk analysis but now I find the need to run this script repeatedly on smaller datasets to cater for more real time usage. I am doing this on Linux RH7.</p>
... | <p>This is the solution I designed to achieve the above.</p>
<p>Reference: <a href="https://realpython.com/python-sockets/" rel="nofollow noreferrer">https://realpython.com/python-sockets/</a></p>
<p>I have to create 2 scripts.
1. client python script: Used to pass the raw data to be classified to the server python s... | tensorflow|python-3.6|redhat | 0 |
349,603 | 60,387,876 | Wrong output from MobileNet SSD V2 converted tflite model | <p>I am working on object detection application on android using the TensorflowLite C++API. When I convert <a href="http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v2_coco_2018_03_29.tar.gz" rel="nofollow noreferrer">ssd_mobilenet_v2_coco_2018_03_29</a> model to tflite, output of converted tflite m... | <p>try using Keras with tensorflow as the backend</p> | c++|android-ndk|tensorflow-lite | 0 |
349,604 | 60,593,373 | tf.keras.layers.Dense - number of parameters? | <p>I've been using keras functional API to build me a nice net. However, i don't understand how spatial connectivity in tf.keras.layers.Dense works. </p>
<p>If I flatten a 7x7x1024 volume i get 50,176 parameters. I expect total number of parameters between two layers to be </p>
<blockquote>
<p>50,176 * 4096 + 4096... | <p>When you pass a tensor with dim>2 Dense create connection with the last dimension as a default behaviour [1] (line 889, input_dim = input_shape[-1]), that's why you don't get any error. And as a result you also get the number of parameters you've already calculated.
So if you're using 3D inputs, you need to flatten... | tensorflow|keras-layer|tf.keras | 0 |
349,605 | 60,552,393 | Merge rows in one dataframe which share the same index | <p>I would like to have a unique <code>DateTimeIndex</code> in a dataframe. Therefore, I would like to <em>merge two rows with the same index</em> into one row. During this merge, I would like to apply a custom formular (such as <code>avg/mean</code>, <code>max</code>, <code>min</code>) to each column. </p>
<p>Idea fo... | <p>Isn't it just <code>groupby</code>:</p>
<pre><code>df.groupby('ts').agg({'value':'mean', 'value2':'max'})
</code></pre> | pandas|dataframe|filter | 1 |
349,606 | 60,532,642 | Tabula-py returns '...' on one specific column in df. everything else seems to work, | <p><strong>Expected behavior:</strong></p>
<p>Read PDF, extract all table data into pandas df.</p>
<p><strong>Actual behavior:</strong></p>
<p>Reads PDF fine, extracts most table data and saves it to a debugging.txt with <code>fp.write(df)</code>. One column (names) usually only returns '...' when I view the debuggi... | <p>This doesn't come from tabula but ipython or Jupyter's display setting.</p>
<p>See also <a href="https://github.com/chezou/tabula-py/issues/216#issuecomment-581837621" rel="nofollow noreferrer">https://github.com/chezou/tabula-py/issues/216#issuecomment-581837621</a></p> | python|pandas|dataframe|tabula|tabula-py | 2 |
349,607 | 60,745,785 | ggplot/plotnine - adding a legend from geom_text() with specific color | <p>I have this dataframe:</p>
<pre><code>df = pd.DataFrame({'Segment': {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'A', 5: 'B', 6: 'C', 7: 'D'},
'Average': {0: 55341, 1: 55159, 2: 55394, 3: 56960, 4: 55341, 5: 55159, 6: 55394, 7: 56960},
'Order': {0: 0, 1: 1, 2: 2, 3: 3, 4: 0, 5: 1, 6: 2, 7... | <p>You can just add color as a variable to <code>geom_text</code> :</p>
<pre><code>import plotnine
from plotnine import ggplot, geom_col, aes, position_stack, geom_text, scale_color_brewer, guides, guide_legend
(ggplot(df, aes(x="Segment", y="$", ymin=0, ymax=300, fill="Variable"))
+ geom_col(position = position_sta... | pandas|ggplot2|plotnine | 0 |
349,608 | 60,637,152 | How to merge two dataframes of unequal size | <p>I have one dataframe with 26 columns, 'A' through 'Z' and 100 rows, and a second dataframe with 3 columns,'C' through 'E' and 30 rows. The first dataframe is missing 50 entries each in columns 'D' and 'E', so what I need to do is overwrite columns 'D' and 'E' in the first dataframe wherever 'C' in the first datafram... | <p>For readalibility of examples I limited the number of columns
in the first DataFrame (<em>df</em>) to 5.</p>
<p>Assume that it contains:</p>
<pre><code> A B C D E
0 a1 b1 c1 d1 e1
1 a2 b2 c2 d2 e2
2 a3 b3 c3 d3 e3
3 a4 b4 c4 d4 e4
4 a5 b5 c5 d5 e5
</code></pre>
<p>The other Dat... | python|pandas|dataframe | 1 |
349,609 | 60,356,404 | how to find the model precision Faster_rcnn_inception_v2? | <p>please help .</p>
<p>run eval.py of the tensorflow detection model</p>
<p>I want to find the precision and I got this data.
Can someone explain to me if it's ok or not and what can I do please.</p>
<p>I am new in these subjects</p>
<p><a href="https://i.stack.imgur.com/OuKOO.png" rel="nofollow noreferrer">enter ... | <p>To explain the concepts in detail.</p>
<ol>
<li>For object detection instead of precision <strong>Average precision</strong> is considered.</li>
<li><strong>AP (Average Precision)</strong> is a popular metric in measuring the accuracy of object detectors.</li>
<li>Average precision computes the average precision val... | python|windows|tensorflow|eval|object-detection-api | 1 |
349,610 | 60,356,297 | Load symmetric matrix into pandas DataFrame where file has 3-column format (row, column, data) | <p>I have a symmetric matrix stored in a tab-separated file that has 3 columns, where the first two columns are the row and column position and the third column is the data. And because it's a symmetric matrix only one triangle is represented, so it looks something like this:</p>
<pre><code>A A 0.2
A B 0.1
B B 1.2
A C... | <pre><code>df = pd.read_csv('file.csv', names=['row', 'col', 'val'], sep=' ')
# A A 0.2
# A B 0.1
# B B 1.2
# A C 0.9
# B C 2.3
# C C 3.4
# A D 2.1
# B D 4.3
# C D 0.8
# D D 1.0
</code></pre>
<p>You can use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofol... | python|pandas | 3 |
349,611 | 60,352,322 | Is there a pandas function for repeated values? | <p>consider series x_1,x_2,x_3,x_4... I want to set x_i as NaN if x_i = x_{i+1}.... I don't care if x_2 equals, say, x_9. For a second or two, I had thought this was the meaning of duplicate values but I now see that it would care about x_9. I'm pretty sure this routine must already exist in pandas, but I can't find it... | <p>Your version should work just fine, but it involves a for loop and therefore is inherently slow. You can make use of vectorization by simply shifting the <code>pd.Series</code> and comparing afterwards:</p>
<pre class="lang-py prettyprint-override"><code>xnp = pd.Series([1,2,3,3,4,2,5,5,6])
ffnp = xnp.shift(1) == x... | python|pandas|duplicates | 1 |
349,612 | 60,374,899 | Why are the values different when iterating them in a for loop, than when printing the whole array? | <p>In Python, using numpy, the values change for printing them in an iterating process, or printing the whole array, why, and how can I fix this? I would like them to be e.g. 0.8 instead of 0.799999999...</p>
<pre><code>>>> import numpy as np
>>> b = np.arange(0.5,2,0.1)
>>> for value in b:
... | <p>This happens because Python and NumPy use <a href="https://en.m.wikipedia.org/wiki/Floating-point_arithmetic" rel="nofollow noreferrer">floating point arithmetic</a> where some numbers, i.e. 0.1, cannot be represented exactly.
Also check <a href="https://docs.python.org/3/tutorial/floatingpoint.html#floating-point-a... | python|numpy | 3 |
349,613 | 60,717,730 | Read some csv files and combine them into one dataframe | <p>I tried to write a code snippet as shown below. Main goal is to read from 03-10-2020.csv to from 03-16-2020.csv and merge them into one dataframe but only last dataframe is included in the dataframe.
How can I fix it? </p>
<pre><code>week_array = []
path = 'URL_ADDRESS'
for i in range(10,17):
dataset_date ... | <p>You need to perform deep copy for data_df.
data_df get replaced with data from new file each time.
hope this solves the issue. </p>
<pre><code>week_array = []
path = 'URL_ADDRESS'
for i in range(10,17):
dataset_date = "03-" + str(i) + "-2020.csv"
url = path + dataset_date
data_df = pd.read_csv(url, er... | python|pandas|dataframe | 0 |
349,614 | 60,659,971 | Sharing parameters in different nn.Moules in pytorch | <p>I've got the model that you can see below, but I need to create two instances of them that shares x2h and h2h.
Does anyone know how to do it?</p>
<pre class="lang-py prettyprint-override"><code>class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
... | <p>It is a Python question i assume.</p>
<p>Variables declared inside the class, not inside a method are class or static variables.</p>
<p>Ref:
<a href="https://radek.io/2011/07/21/static-variables-and-methods-in-python/" rel="nofollow noreferrer">https://radek.io/2011/07/21/static-variables-and-methods-in-python/</a... | python|pytorch|static-variables | 1 |
349,615 | 60,408,844 | Tensorflow 2.0.1 training freezes the system | <p>I am training a GAN using tensorflow 2.0.1's <code>gradienttape()</code>. The training goes around till 2000/2562 batches in the 0th epoch and freezes the system. I've even limited the gpu memory to 8GB:</p>
<pre><code>if gpus:
# Restrict TensorFlow to only allocate 1GB of memory on the first GPU
try:
tf.co... | <p>The cause of a system freeze is really difficult to pinpoint. In your case, I would start by installing a pre-compiled version of tensorflow using pip. </p>
<p>If you observe the same symptoms, I would suspect either a too weak power supply or a problem with the ventilation of your PC.</p>
<p>In order to check if ... | tensorflow|gpu|tensorflow2.0 | 0 |
349,616 | 60,713,523 | Pick elements in one array based on the elements of another array? | <p>I have 2 numpy arrays: array 1 has elements 1 .. 100 denoting ranges to check (the least-significant digit is omitted), array 2 has values 1 .. 1000 to check against each of those ranges.</p>
<pre><code>import numpy
o = numpy.array([3, 7, 20, 47, 60, 72, 76, 83, 94, 94])
p = numpy.array([22, 54, 77, 83, 246, 285, 8... | <h1>tl;dr</h1>
<p>Use <code>any</code> and <code>map</code> to do the real work, not <code>where</code>, which does some magic to determine what to iterate over, and fails when there is more than one iterable in your expression.</p>
<pre><code>>>> numpy.where( map( lambda pval : numpy.any( (o*10 < pval) &... | python|numpy|range | 0 |
349,617 | 60,578,311 | Update 1st column based on string present in 2nd column | <h2>I want to update price 2 times if there is "buy 1 get 1 50%" and 3 times if "buy 1 get 1 40%"</h2>
<ol>
<li>Price| Special_Offer</li>
<li>330 | BUY 1 GET 1 50%</li>
<li>810 | BUY 1 GET 1, 40%</li>
<li>210 |BUY 1,GET 1 at 50%</li>
</ol>
<h2>Below is my code, but it is not working</h2>
<pre><code>DF["Price"]=n... | <p>You forgot the spaces in between, and also dont group with brackets. As I undestand you want to capture the price. So we capture it with \d+ and check if there are needed context with a lookahead like (?= \| BUY 1 GET 1 50%)</p>
<pre><code>\d+(?= ?\| ?BUY 1[, ] ?GET 1(?:,? ?| at )50%)
\d+(?= ?\| ?BUY 1[, ] ?GET 1(?... | python|regex|pandas | 0 |
349,618 | 60,406,140 | AttributeError: module 'tensorflow' has no attribute 'layers' | <p>I am trying to implement the VGG but am getting the above odd error. I am running TFv2 on Ubuntu. Could this be because I am not running CUDA?</p>
<p>The code is from <a href="https://medium.com/@amir_hf8/implementing-vgg13-for-mnist-dataset-in-tensorflow-abc1460e2b93" rel="nofollow noreferrer">here</a>.</p>
<pre><c... | <p>The code you're using was written in Tensorflow v1.x, and is not compatible as it is with Tensorflow v2. The easiest solution is probably to downgrade to a version of tensorflow v1 to run the code as it is.</p>
<p>An other option would be to could follow <a href="https://www.tensorflow.org/guide/migrate" rel="noref... | python|tensorflow | 6 |
349,619 | 60,554,196 | Extract recommendations for user from pivot table | <p>I have a following pivot table with user/items number of purchases that looks like this:</p>
<pre><code>originalName Red t-shirt Black t-shirt ... Orange sweater Pink sweater
customer ...
165 NaN NaN ...... | <pre><code>import pandas as pd
import numpy as np
df=pd.DataFrame({'customer':[165,265,288,268,296],
'R_shirt':[np.nan,1.0,np.nan,1.0,np.nan],
'B_shirt':[np.nan,np.nan,2.0,np.nan,np.nan],
'X_shirt':[5.0,np.nan,2.0,np.nan,np.nan],
'Y_shirt':[3.0,np.nan,2.0,... | pandas|dataframe|recommendation-engine | 1 |
349,620 | 60,523,781 | Pandas column value compare and filter other column The truth value of a Series is ambiguous Error: a.any() or a.all() | <p>I have this pandas dataframe and i want to do this operation
if A ='ad' and C not in ['b','d'] then list [A, B]</p>
<pre><code>A B C D
ad 1 b a
ad 1 b d
cd 2 c k
dc 3 k a
ad 1 c a
</code></pre>
<p>here is the code i tried</p>
<p... | <p>Try this</p>
<pre><code>df[~df['C'].isin(['b', 'd']) & df['A'].isin(['ad'])][["A", "B"]]
</code></pre>
<p><em>one-liner</em> will get you the columns <em>'A'</em> and <em>'B'</em></p> | python|pandas | 2 |
349,621 | 60,632,601 | Python solve subset of linear equations | <p>So I know about sympy and numpy’s linear algebra solver, but what I am trying to do is different. I don’t have the equations to form a solvable matrix so I can solve with those libraries, so I’m trying to solve for a single variable by combining 2 or more equations. For example: </p>
<p>A+B+C = 2<br>
B+C = 1 </p... | <pre><code>from sympy import *
a, b, c = symbols('a, b, c')
f1 = a+b+c
f2 = b+c
result = solve([f1-2, f2-1], (a, b, c))
</code></pre>
<p><b>Output:</b></p>
<pre><code>{b: 1 - c, a: 1}
</code></pre> | python|python-3.x|numpy|differential-equations | 2 |
349,622 | 60,366,033 | Torch.sort and argsort sorting randomly in case of same element | <p>When same elements are encountered, torch.sort and argsort sort the tensor in random manner.
This is not the case in numpy.
I have a list of elements already sorted according to the second column and now i want to sort it using the first column but preserve the earlier sort in case of tie in the new sorting.</p>
<p... | <p>As per torch 1.9.0 you can run the sort with option <code>stable=True</code>. See <a href="https://pytorch.org/docs/1.9.0/generated/torch.sort.html?highlight=sort#torch.sort" rel="nofollow noreferrer">https://pytorch.org/docs/1.9.0/generated/torch.sort.html?highlight=sort#torch.sort</a></p>
<pre><code>>>> x... | python|numpy|sorting|pytorch | 1 |
349,623 | 60,458,024 | TensorBoard in TensorFlow 1 using Google Colab | <p>I would like to use TensorBoard in TensorFlow 1 in Google Colab. The tutorials I have found seem to be on TensorFlow 2 and the suggestions do not seem to work in TensorFlow 1.</p>
<p>It seems I need some equivalent to tf.summary.create_file_writer and tf.summary.scalar. I have tried tf.contrib.summary.create_file_w... | <pre><code>!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
!unzip ngrok-stable-linux-amd64.zip
get_ipython().system_raw('tensorboard --logdir /content/trainingdata/objectdetection/ckpt_output/trainingImatges/ --host 0.0.0.0 --port 6006 &')
get_ipython().system_raw('./ngrok http 6006 &'... | python|tensorflow|jupyter-notebook|google-colaboratory|tensorboard | 1 |
349,624 | 60,722,563 | How can I extend a data frame with date range in two columns using python? | <p>How do I expand the time range of information in a dataframe as a new data frame.</p>
<ul>
<li>I have a data frame df with dates, strings and factors similar to
this:</li>
</ul>
<pre><code> "start" "end" "note" "item"
2016-12-30 2017-01-03 Z 1
2017-09-10 2017-09-14 W 2
</code></pre... | <p>Use:</p>
<pre><code>#convert columns to datetimes if necessary
df[['start','end']] = df[['start','end']].apply(pd.to_datetime)
#repeat datetimes to Series
s = pd.concat([pd.Series(r.Index,pd.date_range(r.start, r.end))
for r in df.itertuples()])
#repoeat values, remove end column and reaa... | python|pandas|dataset|data-science | 2 |
349,625 | 60,547,183 | Pandas - groupby multiple columns and keep multiple columns- | <p>I have a dataframe</p>
<pre><code> action person_id frame_no path
0 boxing person12_boxing_d2_uncomp.avi image_0128.jpg ../../../datasets/kth/train/boxing/person12_bo...
1 boxing person12_boxing_d2_uncomp.avi image_0129.jpg ../../../datasets/kth/train/boxing/person12_bo.... | <pre><code># pd.__version__ == 0.25.1
d=[['hello',1,'GOOD','long.kw'],
['chipotle',2,'GOOD','bingo'],
['hello',3,"BAD", "lm"]]
t=pd.DataFrame(data=d, columns=['A','B','C','D'])
</code></pre>
<p>Output is</p>
<pre><code>t.groupby('A')[['B','C']].agg(lambda x: tuple(x)).applymap(list)
B ... | python|pandas | 2 |
349,626 | 60,582,195 | TypeError: unsupported operand type(s) for +: 'Tensor' and 'dict' | <p>I am new to the world of neural networks and I am trying to implement a CNN generator from <a href="https://i.stack.imgur.com/apDNX.png" rel="nofollow noreferrer">this model</a> <a href="https://i.stack.imgur.com/FDXXd.png" rel="nofollow noreferrer">and these equations</a> (N=32) in order to make motion generation.... | <p>Your question is missing details about your variables but based on the error i am giving you my answer.You are adding a dictionary and a tensor which is giving you the error.If you want to add the values of dictionary to the tensor then you must convert the dictionary into a tensor.And also why are you adding the di... | python|dictionary|pytorch|motion|conv-neural-network | 0 |
349,627 | 60,742,981 | converting json in dataframe to separate columns | <p>I have implemented an emotion analysing using lstm. I am doing the prediction part. I have created a dataframe with my results. In the dataframe, I am having a column having a json file. I want to break this json file and create columns for each labels in the dataframe. I am posting my codes and my results as well a... | <p>I stripped down your code to just fix the last few lines. This addresses your specific question.</p>
<p>Since your code won't run I created dummy data based on your images.</p>
<p>I included lots of comments. Ideally, you shouldn't make a mess of things earlier on in your code. If you follow my example in all of y... | python|json|pandas | 0 |
349,628 | 60,447,056 | Cannot read images from Tensorflow.js Tensorcamera on React Native | <p>I am trying to use Tensorflow.js posenet on React Native but I can not get 'images'. <br>
Currently Expo-camera works ok, but images is undefined, and it also shows<br></p>
<blockquote>
<p>Can't find variable: React</p>
</blockquote>
<p>Please advise how to iterate getting images from TensorCamera.<br>
Thanks</p... | <pre><code><TensorCamera
ref={(ref) => { this.camera = ref }}
type={Camera.Constants.Type.front}
resizeHeight={64}
resizeWidth={64}
resizeDepth={3}
onReady={this.handleCameraStream}
style={{width: width, height: height}}
/>
</code></pre>
<p>You have to pass resizeHeight, resizeWidth... | reactjs|react-native|tensorflow|expo|tensorflow.js | 0 |
349,629 | 60,663,933 | Strange problem when saving to excel pandas | <p>I have some problem wirting to excel. I have 15 columns in my dataframe. I wish only to write 7 of them to excel and in the process use another name for the header.</p>
<p>Here is my code</p>
<pre><code>cols = ['SN', 'Date_x','Material_x', 'Batch_x', 'Qty_x', 'Booked_x', 'State_x']
headers = ['SN', 'Date', 'Mate... | <p>Let me elaborate my idea in the comment by an example:</p>
<pre><code>df = pd.DataFrame(np.arange(16).reshape(4,-1))
# this is the reference dataframe
np.random.seed(1)
ref_df = pd.DataFrame(np.random.randint(1,10,(4,4)))
# this is the function
def highlight(col, ref_df=None):
return ['background-color: yello... | excel|pandas | 2 |
349,630 | 60,398,554 | Should we apply repeat, batch shuffle to tf.data.Dataset when passing it to fit function? | <p>I still don't after having read documentation about <code>tf.keras.Model.fit</code> and <code>tf.data.Dataset</code>, when passing <code>tf.data.Dataset</code> to fit function, should I call <code>repeat</code> and <code>batch</code> on the dataset object or should I provide the <code>batch_size</code> and <code>epo... | <p>There's different ways to do what you want here, but the one I always use is: </p>
<pre><code>batch_size = 32
ds = tf.Dataset()
ds = ds.shuffle(len_ds)
train_ds = ds.take(0.8*len_ds)
train_ds = train_ds.repeat().batch(batch_size)
validation_ds = ds.skip(0.8*len_ds)
validation_ds = train_ds.repeat().batch(batch_size... | python|tensorflow|tensorflow-datasets|tf.keras|tensorflow2.x | 2 |
349,631 | 60,381,159 | How can I improve the speed of hundreds of pandas .loc calls on 1M rows of data? | <p>I have a pandas dataframe of about 1M rows and growing. I need to do multiple case-insensitive look-ups in a column, and assign a different value to another column if it is found. The current way I'm accomplishing this is:</p>
<pre><code>df.loc[df.columnA.str.contains('(?i)^match_string', na=False, regex=True), 'co... | <p>There are a few hints that could help you to improve processing</p>
<p>1) Create a new column columnC that clones columnA but lowercased.
And then, of course, make sure you use a lowercased match_string
This will avoid the case insensitive search.</p>
<p>2) You can even create your columnC with a substring of colu... | python|regex|pandas | 2 |
349,632 | 60,414,189 | How to replace all same values of a group in a column (dataframe) according to another column without loop? | <p>I'm trying to replace all the same values in a group of values by 0 if there is a 1 in another column corresponding to this group.</p>
<p>Here is an example of the output I want, if there is a 1 in the Y column, I want all the group made of ones in the input column to be 0.
For speed problematic, I don't want to us... | <p>Use:</p>
<pre><code>df['output']=(df['Y'].ne(1)
.groupby(df['input'].ne(df['input'].shift()).cumsum())
.transform('all')
.mul(df['input']))
</code></pre>
<p>or </p>
<pre><code>((~df['Y'].eq(1)
.groupby(df['input'].ne(df['input'].shif... | python|pandas|numpy|dataframe | 1 |
349,633 | 72,493,501 | Replace value based on a corresponding value but keep value if criteria not met | <p>Given the following dataframe,</p>
<p><strong>INPUT df:</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Cost_centre</th>
<th>Pool_costs</th>
</tr>
</thead>
<tbody>
<tr>
<td>90272</td>
<td>A</td>
</tr>
<tr>
<td>92705</td>
<td>A</td>
</tr>
<tr>
<td>98754</td>
<td>A</td>
</tr>
<tr>... | <p>IIUC, you can use <code>isin</code></p>
<pre class="lang-py prettyprint-override"><code>filt = df['Cost_centre'].isin([90272, 91350])
df.loc[filt, 'Pool_costs'] = 'B'
</code></pre>
<pre><code>print(df)
Cost_centre Pool_costs
0 90272 B
1 92705 A
2 98754 A
3 9... | python|arrays|pandas|dataframe|apply | 0 |
349,634 | 72,624,809 | Pandas include single row in df after filtering with .loc | <p>So, in this function:</p>
<pre class="lang-py prettyprint-override"><code>def filter_by_freq(df, frequency):
filtered_df = df.copy()
if frequency.upper() == 'DAY':
pass
else:
date_obj = filtered_df['Date'].values[0]
target_day = pd.to_datetime(date_obj).day
t... | <p>Here's one way you could do it. In this example I have a df and I want to filter out all rows that have <code>c1 > 0.5</code>, but I want to keep the last row no matter what. I create a boolean series called <code>lte_half</code> to keep track of the first condition, and then I create another boolean series/list/... | python|pandas|filter | 0 |
349,635 | 72,744,665 | How to add noise to row/column selection in python | <p>I want to select a specific row/column of a matrix i have, the twist however is that i want an added noise in the selection of the chosen row.</p>
<p><strong>Example</strong></p>
<p>I have a matrix <code>m</code> of size <code>100x100</code>. I now want to select row 40 i.e. m[40,:].</p>
<p>What is <em>actually want... | <p>Assuming this 10x10 input and getting column 3 ± 1:</p>
<pre><code># setting up example
np.random.seed(0)
a = np.arange(100).reshape(10, 10, order='F')
# target column
col = 3
# noise (+ -1/0/1)
rand = np.random.randint(-1, 2, a.shape[0])
# example:
# array([2, 3, 2, 3, 3, 4, 2, 4, 2, 2])
out = a[np.arange(a.shap... | python|numpy|matrix | 1 |
349,636 | 72,561,932 | Multiply pandas dataframe with a differently shaped dataframe based on condition | <p>I have a pandas DataFrame (df_A) with this basic form:</p>
<pre><code>|id| alt| a | b | c | d | e |
|--|----|-----|-----|-----|---|---|
| 0| ICV| 0.2 | 1.0 | 0.2 | 0 | 1 |
| 1| ICV| 1.0 | 1.0 | 0.2 | 0 | 0 |
| 2| BEV| 3.2 | 1.0 | 0.2 | 1 | 0 |
| 3| ICV| 2.0 | 1.0 | 0.2 | 0 | 0 |
| 4| BEV| 2.0 | 1.0 | 0.2 | 1 |... | <p>You can use a <code>merge</code> and in place multiplication:</p>
<pre><code>cols = ['a', 'b', 'c']
df_A[cols] *= df_A[['alt']].merge(df_B, how='left')[cols]
</code></pre>
<p>output:</p>
<pre><code> id alt a b c d e
0 0 ICV 0.02 0.3 0.10 0 1
1 1 ICV 0.10 0.3 0.10 0 0
2 2 BEV 0.64 ... | python|pandas|dataframe | 2 |
349,637 | 72,717,398 | how could I write some code containing flask and pandas? | <p>I need to display the results of my script in Python using pandas which contain <code>group by</code>, but I couldn't. What I want actually is to see my result (from my script) on my website.</p>
<p>This the code I tried, it did not give a result</p>
<pre><code>from flask import Flask
import pandas as pd
app = Flask... | <p>You need to return a string for route or use <code>render_template</code>. Create a template folder in your root and add index.html. You need to use <a href="https://www.fullstackpython.com/jinja2.html" rel="nofollow noreferrer">Jinja2</a> to render the python data as html.</p> | python|pandas|database|csv|flask | 0 |
349,638 | 72,725,680 | Python- Pandas Subtract columns value in ascending order value of a columns | <p>Have a dataframe mortgage_data with columns name mortgage_amount and month (in asceding order)</p>
<p>input=
<code>mortgage_amount_paid = 1000</code>
<code>mortgage_amount_paid_date = 30-12-2019</code></p>
<p>mortgage_data:</p>
<pre><code>name mortgage_amount month to_be_paid_date
mark 500 1 ... | <p>First I would convert your date column and <code>to_be_paid_date</code> to datetime like so</p>
<pre><code>df["to_be_paid_date"] = pd.to_datetime(df["to_be_paid_date"], format="%d-%m-%Y")
mortgage_amount_paid_date = datetime.strptime(mortgage_amount_paid_date,"%d-%m-%Y")
</cod... | python|python-3.x|pandas|dataframe | 0 |
349,639 | 72,816,507 | how to use two columns as condition to create a new column in the data frame which will return a Boolean value | <p>I have an idea but i cant seem to write the right code for the problem
io want to add a column in the data frame that will return a Boolean value when two conditions are met.
the first condition is a multi-condition type
i have to find out all adults with higher education (Bachelors or Masters or Doctorate)
the seco... | <p>It would have been better if you provided a peak of the data but anyways I can understand the scenario in some way. Here is the solution as per my understanding:</p>
<pre><code>df = pd.DataFrame({'Education' : ['bachelor', 'master', 'doc', 'school', 'highschool'],
'Salary' : [100000, 51000, 40000, 3000... | pandas|dataframe|boolean-expression | 1 |
349,640 | 72,663,365 | How to make a sum by using group by? | <p>I have the following dataset and I want to sum the values of the column UnitPrice grouping by CustomerID.</p>
<p><a href="https://i.stack.imgur.com/hpiXE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hpiXE.png" alt="enter image description here" /></a></p>
<p>I'm trying the following way but des... | <p>In this case, the shape of the output from the groupby operation will be different than the shape of your dataframe. You will need to use the <code>transform</code> method on the groupby object to restore the correct shape you need:</p>
<pre class="lang-py prettyprint-override"><code>data['TotalEN'] = data.groupby([... | python|pandas|dataframe|group-by|sum | 2 |
349,641 | 72,743,363 | Pandas: How to append a row in multiindex dataframe? | <p>I have an empty data-frame (with NaN), there are two index levels (<em><strong>‘Index’ and ‘Data_set’</strong></em>) and three columns, as shown below.</p>
<pre><code> multi_index = pd.MultiIndex.from_tuples([('ind1', 'set1'),
('ind1','set2'),
... | <p>You need recreate MultiIndex by new in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a>:</p>
<pre><code>mux = pd.MultiIndex.from_tuples([('ind1', 'set1'),
('ind1','set2'),
... | python|pandas|multi-index | 0 |
349,642 | 72,638,793 | Pandas replace values in columns based on condtion | <p>I have a dataframe like below:</p>
<pre><code>dummy_df_dict = {'Email':['joblogs@gmail.com', 'joblogs@gmail.com', 'johnsmith@gmail.com', 'johnsmith@gmail.com'],
'Transaction_Country': ['CA', 'No Country Listed', 'No Country Listed', 'DE'],
'Country_name': ['Canada', 'No Country Listed', '... | <pre><code>df = df.replace('No Country Listed', np.nan).replace('No Contient listed', np.nan)
df = df.sort_values(['Email', 'Transaction_Country']).groupby('Email')[df.columns].ffill()
print(df)
</code></pre>
<p>Output:</p>
<pre><code> Email Transaction_Country Country_name Continent
0 joblogs@g... | python|pandas | 2 |
349,643 | 72,827,945 | How can I print out the max nos in each column of a numpy array in an object using python? | <p>I have the below numpy array</p>
<pre><code>[[7, 0, 0, 6],
[5, 6, 6, 1],
[4, 1, 6, 7],
[5, 3, 4, 7]]
</code></pre>
<p>I want to find the max no in each column using np.max and then print out the result in an object such that output will be as shown below</p>
<p><code>[7, 6, 6, 7]</code></p> | <p>If <code>arr</code> is your array, then you just need to use the <code>max</code> function, indicating the chosen axis:</p>
<pre><code>arr.max(axis=0)
</code></pre>
<p>Output:</p>
<pre><code>array([7, 6, 6, 7])
</code></pre>
<p>If you want a list instead of a numpy array:</p>
<pre><code>arr.max(axis=0).tolist()
</co... | python|numpy|indexing | 3 |
349,644 | 72,504,901 | Calculating cross-correlation between 2 signals using FFT without considering lags | <p>I'm trying to calculate the cross correlation between 2 signals without considering a lag. Essentially I want to recreate the cross correlation of 2 signals with zero lags, to see if my understanding of how cross correlation is calculated is correct.</p>
<p>The following is my code:</p>
<pre><code>x1 = np.linspace(0... | <p>The unnormalized circular correlation is calculated as follows</p>
<pre><code># your code
import numpy as np
x1 = np.linspace(0,2*np.pi,1000)
y1 = np.sin(x1)
y2 = np.sin(x1 - np.pi/4)
y1_fft = np.fft.fft(y1)
y2_fft = np.fft.fft(y2)
y2_conj = np.conjugate(y2_fft)
# calculate the correlation (without padding)
corr = ... | numpy|scipy|fft|cross-correlation | 0 |
349,645 | 72,790,028 | Pandas pivot and include columns with variable values | <p>I have this dataframe <code>jpm_2021</code>:</p>
<pre><code> SRC SRCDate Ticker Coupon Vintage Bal WAC WAM WALA LNSZ LTV FICO Refi% Month_Assessed CPR Month_key
894 JPM 02/05/2021 FNCI 1.5 2020 28.7 2.25 175 4 293 / 286 60 777 91 Apr 7.536801 ... | <p>What you're asking for doesn't make much sense. If you pivot a dataframe, and make its index columns that won't have an accompanying value for every pivoted value... then having NaN values is to be expected.</p>
<p>You could make it very wide like:</p>
<pre><code>df.pivot(index=['SRC', 'Ticker', 'Coupon', 'Vintage',... | python|pandas|dataframe|pivot | 1 |
349,646 | 72,643,835 | use custom column list in pandas crosstab | <p>I have a dataframe like as below</p>
<pre><code>ID,Region,year,output
1,ANZ,1978,1
1,ANZ,2019,1
1,ANZ,2021,1
1,ASEAN,2021,1
1,ASEAN,2021,2
1,ASEAN,2020,3
2,UK,2021,8
2,UK,2021,1
2,UK,2021,0
</code></pre>
<p>I would like to do the below</p>
<p>a) create 4 year columns <code>year_2019,year_2020,year_2021 and year_2022... | <p>You can use:</p>
<pre><code>out = (pd
.crosstab(df['ID'], df['year'])
.reindex(range(2019, 2022+1), axis=1, fill_value=0)
.add_prefix('year_')
.reset_index()
.rename_axis(columns=None)
)
</code></pre>
<p>output:</p>
<pre><code> ID year_2019 year_2020 year_2021 year_2022
0 1 1 1 ... | python|pandas|list|dataframe|pandas-groupby | 2 |
349,647 | 72,568,276 | Interpolate each 25 rows of a dataframe | <p>I have a 250 by 86 dataframe. I wish to linearly interpolate each 25 rows of each column of this dataframe using the ".interpolate function". This is the code I tried:</p>
<pre><code>for i in range(0,25,25):
for x in range(2,len(df.columns)):
df.iloc[i,x].interpolate(method='linear', inplace=True)
</co... | <p>In a matrix-like dataframe, <code>df.iloc[i,j]</code> returns the value located in i-th row and j-th column. That is why you get this error, you are trying to interpolate a number. See this example:</p>
<pre class="lang-py prettyprint-override"><code>>>> x = pd.DataFrame(data=[{1:2, 3:4, 5:6},{1:8,3:10,5:12... | python|numpy|interpolation | 0 |
349,648 | 72,815,591 | How can I have a series of numpy ndarrays as the input data to train a tensorflow machine learning model? | <p>I am trying to build a machine learning model which predicts a single number from a series of numbers. I am using a Sequential model from the keras API of Tensorflow.</p>
<p>Basically my x data is a Pandas series which contains numpy ndarrays, which contain floats.
My y data is a series of numpy ndarrays of shape (1... | <p>Pandas Data Series does not support a direct conversion to tensors.
So I would try first to convert those to <strong>list</strong>:</p>
<pre><code>X = X.to_list()
Y = Y.to_list()
</code></pre> | python|pandas|numpy|tensorflow|keras | 0 |
349,649 | 72,737,862 | Extract only numbers from string with python | <p>I am trying to extract numbers only from a pandas column</p>
<p>I used <code>.str.extract('([?:\s\d+]+)')</code></p>
<p>and it seems it worked well, but when I checked the data, there is a row that it is not matching the condition.</p>
<p>Row contains: <code>86531 86530 86529PIP 91897PIP</code></p>
<p>Result: <code>... | <p>Your regex doesn't do what you think it does. What you have is a <a href="https://stackoverflow.com/questions/9801630/what-is-the-difference-between-square-brackets-and-parentheses-in-a-regex">character class</a>, which matches any of the characters in the set <code>?: \t\r\n\f\v0-9+</code>. So when the regex encoun... | python|pandas | 3 |
349,650 | 72,673,887 | read_csv with dypes, thousands and keep_default_na defined | <p>I have an exported Excel CSV file with <code>str(date), str, float, float, float, float, int</code> as column values. Some of the Excel cells are empty, thus using <code>keep_default_na</code> is needed.
Some are in double quotes, thousand separators present.
The number of parameters seems to confuse the pandas pars... | <p>I think the problem may be that the routine which reports which values are the problem isn't as sophisticated as the full parsing engine - I think you have multiple dtype issues in each column and pandas is telling you the wrong value is the actual issue. float columns can't have the value "" (so it needs ... | python|pandas|csv | 2 |
349,651 | 72,652,038 | Why can't I see the local epochs output when training tensorflow federated learning model? | <p>I am training a tensorflow federated learning model. I cannot see the output of epochs. Details are as follows:</p>
<pre><code>split = 4
NUM_ROUNDS = 5
NUM_EPOCHS = 10
BATCH_SIZE = 2
PREFETCH_BUFFER = 5
</code></pre>
<pre class="lang-py prettyprint-override"><code>
for round_num in range(1, NUM_ROUNDS+1):
state,... | <blockquote>
<p>Why can't I see the local epochs output when training tensorflow federated learning model?</p>
</blockquote>
<p>Generally in federated learning the client is performing local computation not visible to the server. In this case, the server (or us modelers) only see the the result of that local training (... | python-3.x|tensorflow2.0|tensorflow-federated|federated-learning | 2 |
349,652 | 72,744,942 | Geopandas: use loop to difference each polygon from the one before in geodataframe? | <p>I have a geodataframe with many polygons. I'd like to automate differencing with a loop, to do this with each preceding and following polygon and add them to a new gdf:</p>
<p><code>new_gdf = polygon[0:1].overlay(polygon[1:2], how='difference')</code></p>
<p>I am able to do this one at a time, but I'd like to find a... | <p>Instead of <code>overlay()</code> you might be looking for <a href="https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoSeries.difference.html#geopandas.GeoSeries.difference" rel="nofollow noreferrer"><code>GeoSeries.difference()</code></a></p>
<blockquote>
<p>Returns a GeoSeries of the points in each al... | loops|gis|geopandas | 1 |
349,653 | 72,495,273 | StellarGraph PaddedGraphGenerator - how to provide specific training, validation and test sets | <p>I'm trying to train a basic Graph Neural Network using the StellarGraph library, in particular starting from the example provided in [0].</p>
<p>The example works fine, but now I would like to repeat the same exercize removing the N-Fold Crossvalidation and providing specific training, validation and test sets. I'm ... | <p>I found a solution digging in the <code>StellarGraph</code> <a href="https://github.com/stellargraph/stellargraph/blob/master/stellargraph/mapper/padded_graph_generator.py" rel="nofollow noreferrer">documentation for <code>PaddedGraphGenerator</code></a> and <a href="https://github.com/stellargraph/stellargraph/blob... | python|tensorflow|keras|graph|stellargraph | 0 |
349,654 | 72,616,626 | Dask .repartition(partition_size="100MB") is not respecting given size | <p>I'm turning pandas dataframes into parquet files. For this I'm using dask, to help to partition the generated files.</p>
<pre><code>my_dask_df = dask.dataframe.from_pandas(my_pandas_df, npartitions=1)
my_dask_df = my_dask_df.repartition(partition_size="100MB")
dask.dataframe.to_parquet(my_dask_df, destinat... | <p>The parquet file format compresses your data by default. The repartition argument is talking about the size of the data in memory, whereas you are looking at the size on disk.</p>
<p>The default compression algorithm right now is <a href="https://github.com/andrix/python-snappy" rel="nofollow noreferrer"><code>pytho... | python|pandas|dask|parquet | 1 |
349,655 | 72,557,369 | Accessing the elements of an Input Layer in a keras model | <p>I am trying to compile and train an RNN model for regression using Keras Tensorflow. I am using the "Functional API" way for the definition of my model.</p>
<p>I need to have <strong>2 different inputs</strong>. The first one (<code>input</code>) is my training data which is an array with the shape: (TOTAL... | <p>Try using <code>tf</code> operations only:</p>
<pre><code>import tensorflow as tf
@tf.function
def mask_creator(lengths, number_of_GRU_features=256, max_pad_len=1564):
ones = tf.ragged.range(lengths * number_of_GRU_features)* 0 + 1
zeros = tf.ragged.range((max_pad_len - lengths) * number_of_GRU_features) * 0
... | python|tensorflow|machine-learning|keras|recurrent-neural-network | 1 |
349,656 | 72,664,156 | Data from OSM (overpy) to geodataframe with polygons | <p>I try to put OSM data (some polygons) to geodataframe.
Export from OSM contains LineString. But in the end i need to converte all data into geodataframe in this format:</p>
<p>0 -> name_from_tag_first_area -> polygon (or multipolygon) type with coordinates</p>
<p>1 -> name_from_tag_second_area -> polygon... | <p>Apart from an additional import I will keep the beginning of your script as the same.</p>
<pre><code>import overpy
import requests
import json
import geopandas as gpd
from shapely.geometry import shape, MultiPolygon
from shapely.ops import polygonize
url = "https://maps.mail.ru/osm/tools/overpass/api/interpret... | python|openstreetmap|geopandas|overpass-api | 1 |
349,657 | 72,773,747 | How to match dict keys with dataframe column entries to insert the values | <p>I used text mining to capture word counts from various documents.
In doing so, I search a given list of words in the texts. Example: data, digital & wifi</p>
<p>My code outputs a dictionary with the matched word (key) and count (value) as a result. Example:</p>
<pre><code>txt_file_1: {'data': 2, 'digital': 1}
tx... | <p>A <code>pd.Series</code> is quite similar to a dictionary. It has an index (dictionary keys) and a value for each key.</p>
<p>In this solution, we use these basic facts about Series and pandas automatic index alignment when handling Series and DataFrames. We just produce Series with the right indexes and they combin... | python|pandas|dataframe | 0 |
349,658 | 72,635,609 | What does two values separated only by parentheses on right side of = mean? | <p>What is the meaning of two values separated only by parenthesis on the RHS of = in Keras?</p>
<pre><code>LSTM_layer = LSTM(units=256)(embedding)
</code></pre>
<p>Full code:</p>
<pre><code>from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, LSTM, Dense, Embedding
from tensorflow.keras... | <p>It's just ordinary call syntax without a temporary variable. <code>LSTM_Layer = LSTM(units=256)(embedding)</code> is equivalent to</p>
<pre><code># assuming t isn't already defined
t = LSTM(units=256)
LSTM_Layer = t(embedding)
del t
</code></pre> | python|tensorflow|keras | 1 |
349,659 | 72,567,364 | Find groups of Y values for unique X values, numpy structured array? | <p>I have a <code>numpy</code> structured array:</p>
<pre><code>import numpy as np
arr1 = (np.array([32, 32, 32, 32, 32, 39, 21], dtype=np.int64),np.array([449, 451, 452, 453, 454, 463, 340], dtype=np.int64))
arr1_x = arr1[0]
arr1_y = arr1[1]
arr1_struct = np.empty(arr1_x.shape[0], dtype=[('x', int), ('y', int)])
ar... | <p>Sounds like you need to be using <code>pandas</code> and work with a dataframe-like structure.</p>
<pre><code>df = pd.DataFrame([*arr1], index=['x', 'y']).T
</code></pre>
<p>which gives</p>
<pre><code> x y
0 32 449
1 32 451
2 32 452
3 32 453
4 32 454
5 39 463
6 21 340
</code></pre>
<p>Then,</p>
<... | python|numpy | 2 |
349,660 | 72,527,948 | How to convert a nested JSON object to a dataframe? | <p>I am getting a JSON object returned from an API call which looks like this:</p>
<pre><code>{"meta":{"symbol":"AAPL","interval":"1min","currency":"USD","exchange_timezone":"America/New_York","exchange":"NASDAQ&quo... | <h5>Edit to fit actual solution:</h5>
<p>You should be able to load your API response with:</p>
<pre><code>data = resp.json()
pd.DataFrame(data['values'])
</code></pre> | python|pandas | 1 |
349,661 | 72,664,225 | Please help to fix it: TypeError: predict_proba() missing 1 required positional argument: 'X' | <p>I was building a binary classifier using the random forest classifier. Before it, I did a feature selection based on the high AUC score. However, when I wanted to get AUC for this model I couldn't. Here is the code below. Sorry for the lack of the dataset.</p>
<pre><code>
import numpy as np
import pandas as pd
impor... | <p>You should use <code>clf.predict_proba(X_test)</code> instead, and also I think you need to fix this part too:</p>
<pre><code>y_pred1 = clf.predict(X_test)
print('Accuracy on test set: ', accuracy_score(y_test, y_pred))
</code></pre>
<p>you are declaring <code>y_pred1</code>, but using <code>y_pred</code></p> | python|pandas|scikit-learn|random-forest|auc | 2 |
349,662 | 72,772,196 | Run 2 slurm jobs only when both get the allocated resources | <p>One job is submitted to get hold of 4 GPUs. The second is submitted to get hold of the next 4 GPUs (on a different node). How can I ensure that both of the jobs run at the same time such that they eventually synchronise (Pytorch DPP).</p>
<p>Having an extra script to check the available resources does the trick, how... | <p>The simple answer is to be more explicit with slurm.</p>
<pre><code>idx=0; export CUDA_VISIBLE_DEVICES=$idx; python -u run_pos.py --fold=1 &
idx=1; export CUDA_VISIBLE_DEVICES=$idx; python -u run_pos.py --fold=2 &
idx=1; export CUDA_VISIBLE_DEVICES=$idx; python -u run_pos.py --fold=3 &
wait
</code></pre... | pytorch|scheduled-tasks|distributed-computing|slurm | 0 |
349,663 | 72,806,654 | dataframe to list of dictionary | <p>I have the following df:</p>
<pre><code>df = pd.DataFrame({"year":[2020,2020,2020,2021,2021,2021,2022,2022, 2022],"region":['europe','USA','africa','europe','USA','africa','europe','USA','africa'],'volume':[1,6,5,3,8,7,6,3,5]})
</code></pre>
<p><a href="https://i.stack.imgur.com/Fh7Dz.png" rel="n... | <p>Another approach that uses pivot before <code>to_dict(orient='records')</code></p>
<pre><code>df.pivot(
index='year',
columns='region',
values='volume'
).reset_index().to_dict(orient='records')
#Output:
#[{'year': 2020, 'USA': 6, 'africa': 5, 'europe': 1},
# {'year': 2021, 'USA': 8, 'africa': 7, 'europe... | python|pandas|dictionary | 4 |
349,664 | 72,501,003 | TypeError: __init__() missing 1 required positional argument: 'data' | <p>In Python, I have read in a lightGBM pmml file named <code>flaml_lgbm.pmml</code>, like so:</p>
<pre><code>from pypmml import Model
model = Model.fromFile('flaml_lgbm.pmml')
</code></pre>
<p>Then I have tried to generate the SHAP graph with these lines of code:</p>
<pre><code>shap_values = shap.KernelExplainer(mode... | <p>You simply need to include data also in <strong>shap.KernelExplainer()</strong>, try this:</p>
<pre><code>shap_values = shap.KernelExplainer(model, X).shap_values(X)
</code></pre> | python|pandas|shap | 2 |
349,665 | 72,667,576 | Filtering text from dataframe based on keywords in a list | <p>I have a list of lists, each sublist of the list contains keywords to filter text from a dataframe.</p>
<pre><code>keywords = [[('tarifa',), ('mantenimiento',), ('mensual',)],
[('tasa',), ('anual',)],
[('seguro',), ('bancaria',)],
[('seguro',), ('generales',)],
[('mi salud',), ('unific',)]]
</code></pre>
... | <h1>How to filter a DataFrame by a volatile subset of words?</h1>
<h2>Dummy data</h2>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
columns = ['transaction_description', 'value']
data = [
['pac c.misalud conv. unificado', 12320.0],
['cargo seguro proteccion bancaria', 3... | python|pandas|list|dataframe|variables | 2 |
349,666 | 72,686,842 | Pandas Replace changes values not only in the dataframe it is applied to | <p>I have the following dataframe:</p>
<pre><code>df1 = pd.DataFrame([[1,2],['a',1]])
df1 = df1.replace(1, np.nan)
</code></pre>
<p>So, df1 takes <a href="https://i.stack.imgur.com/usGKP.png" rel="nofollow noreferrer">this form</a>.</p>
<p>After this, I want to replace some values in df2:</p>
<pre><code>df2 = df1
df2[1... | <p>By default, python goes for shallow copy of variables i.e. any changes made to any variable will be reflected to the object that was assigned as well hence both df1 & df2 changes in your case. You can use deepcopy() to avoid this</p>
<pre><code>import copy
df1 = pd.DataFrame([[1,2],['a',1]])
df1 = df1.replace(1,... | python|pandas|dataframe|replace | 0 |
349,667 | 72,739,163 | Conditional filtering of dataframe – TypeError: unsupported operand type(s) | <p>I want to get some data from "Year" columns</p>
<p>that is <code>"22 < x < 100"</code></p>
<p>and I made this code</p>
<pre><code>df4 = df_y[[df_y["Year"]<100] & [df_y['Year']>22]]
</code></pre>
<p>but that doesn't work with this error</p>
<blockquote>
<p>"TypeError... | <pre><code>df4 = df_y[(df_y["Year"]<100) & (df_y['Year']>22)]
</code></pre>
<p>Use <code>()</code> instead of <code>[]</code> for <code>&</code> operation</p> | python|pandas | 2 |
349,668 | 72,593,471 | array copy and view in numpy python | <p>I am new to numpy.Recently only I started learning.I am doing one practice problem and getting error.
Question is to replace all even elements in the array by -1.</p>
<pre><code>import numpy as np
np.random.seed(123)
array6 = np.random.randint(1,50,20)
slicing_array6 = array6[array6 %2==0]
print(slicing_array6)
slic... | <pre><code>In [12]: np.random.seed(123)
...: array6 = np.random.randint(1,50,20)
...: slicing_array6 = array6[array6 %2==0]
In [13]: array6.shape
Out[13]: (20,)
In [14]: slicing_array6.shape
Out[14]: (9,)
</code></pre>
<p><code>slicing_array6</code> is not a <code>view</code>; it's a copy. It does not use or... | python|numpy|numpy-slicing | 2 |
349,669 | 72,508,079 | pandas: How do I create a dictionary with two columns and add them to an existing dictionary column? | <p>You need to create a dictionary with two columns as shown below and add values to the dictionary in the existing columns.
The two columns may be separated by <code>,</code> and multiple values may be added.</p>
<p>How can this be handled to make this possible?</p>
<pre><code> site url urls
0 a, b link... | <p>Let us try <code>apply</code> along columns axis:</p>
<pre><code>df.apply(lambda r: {**r['urls'], **dict(zip(r['site'].split(', '), r['url'].split(', ')))}, axis=1).to_frame('urls')
</code></pre>
<hr />
<pre><code> urls
0 {'e': 'link3', 'a': 'link1', 'b': 'link2'}
1 {'f': 'l... | python|pandas|dataframe | 1 |
349,670 | 72,615,877 | Finding NumPy column index distance of non-minus-one elements in an n-d array | <p>Suppose I have the following NumPy array:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
arr = np.array([['a', -1, -1, -1],
[ -1,'b','c', -1],
['e', -1,'d','f']], dtype=object)
</code></pre>
<p>Now I would like to find the column index distance of neighboring ... | <p>I think this does what you want:</p>
<pre><code>[np.diff(np.where(row!=-1)).flatten() for row in arr]
</code></pre>
<p>The result:</p>
<pre><code>[array([], dtype=int64), array([1]), array([2, 1])]
</code></pre>
<p>I can't think of a way to vectorize it (i.e. to avoid the loop); it's kind of a weird data structure (... | python|arrays|numpy | 2 |
349,671 | 72,762,742 | AttributeError: 'Tensor' object has no attribute 'close' | <p><a href="https://i.stack.imgur.com/BZEPh.png" rel="nofollow noreferrer">this is the code I am working with:</a></p>
<p>I searched for a similiar error do i need to change the .close() ?</p>
<p>Can anyone help please?</p> | <p>You should remove the close() function call on the parameter tensor image in line -
<code>image = tensor.cpu().close().detach().numpy()</code>. This should be replaced with - <code>image = tensor.cpu().detach().numpy()</code></p> | numpy|tensorflow|pytorch|tensor | 0 |
349,672 | 72,716,588 | Finding all unique combinations of columns of pandas data frame | <p>I have a data balancing problem at hand wherein I have images which have multiple classes i.e. each image can have multiple class or one class. I have the label file which has all the classes named from A to G and fn(image name) as the columns. Each column has a value 0 or 1,wherein 0 means that class is absent in i... | <p>Hi you should use the <code>groupyby</code> and <code>get_group</code> methods to extract the desired elements.</p>
<p>Here is an example if you are trying to get datas where A = 0 & B= 0 :</p>
<pre class="lang-py prettyprint-override"><code>#Simulation of your datas
nb_rows = 10000
nb_colums = 5
df_array = np.r... | python|pandas|dataframe|machine-learning|deep-learning | 1 |
349,673 | 72,593,721 | In rolling().apply() of pandas, are args cached when enigne="numba" | <p>In <code>rolling().apply()</code> of pandas, Args are cached when <code>enigne="numba"</code>.<br />
Is this correct behavior?<br />
Is there any way to prevent args from being cached?</p>
<p>The sample code is as follows</p>
<pre><code>import pandas as pd
import numba as nb
@nb.jit
def test_func(x, c):
... | <p>It turns out <strong>this is a bug</strong> and it as been <strong>solved in version 1.4.0</strong>. See <a href="https://github.com/pandas-dev/pandas/issues/42287" rel="nofollow noreferrer">this closed bug</a>.</p> | python|pandas|numba | 2 |
349,674 | 72,699,261 | How do I accurately represent SHAP values of columns made with a hashingVectorizer? | <p>I used a <code>HashingVectorizer()</code> from sklearn to represent the unique IDs of a dataset which hashes the data into n columns, and I want to calculate the total SHAP value of this data. Is the correct way to simply add all their mean SHAP values together, or do I take the average of the values</p> | <p>I think the closest you will get without significant additional work is <a href="https://shap.readthedocs.io/en/latest/generated/shap.explainers.Partition.html" rel="nofollow noreferrer"><code>shap.explainers.Partition</code></a>, which will either accept or compute a hierarchical clustering of features.</p>
<p>Alte... | python|tensorflow|scikit-learn|sklearn-pandas|shap | 0 |
349,675 | 72,612,970 | Merge two Dataframes on two columns with different length by closest match | <p>I want to merge these example dataframes:</p>
<ol>
<li>How to get the closest matches in a new df?</li>
</ol>
<pre class="lang-py prettyprint-override"><code>df1:
name age department
DJ Griffin 27 FD
Harris Smith 33 RD
df2:
name age department
D.J. Griffin III ... | <p>The issue arises when you have zero match, slicing <code>[0]</code> is not possible.</p>
<p>You could use instead:</p>
<pre><code>df2['name'].apply(lambda x: next(iter(difflib.get_close_matches(x, df1['name'])), pd.NA))
</code></pre>
<p>or</p>
<pre><code>df2['name'].apply(lambda x: difflib.get_close_matches(x, df1['... | python-3.x|pandas|difflib | 2 |
349,676 | 72,761,473 | What is the most efficient way to adjust hue of an image in Python? | <p>I am trying to turn images into infinite looping GIFs, basically you have an image and a number, you then create an array of that number elements, each element is the original image with hue rotated by index divided by number times 360°, and you save the array as a GIF.</p>
<p>Working solution:</p>
<pre class="lang-... | <p>I switched to <code>cv2</code> and now it's much faster. I also replaced GIF with MP4, because GIFs are of low quality.</p>
<p>But I didn't use <code>cv2.VideoWriter</code>, because: 1, I can't control the bitrate, and 2, it doesn't use an FFMPEG version that supports CUDA, instead I found pre-compiled FFMPEG binari... | python|numpy|image-processing|vectorization | 0 |
349,677 | 72,661,988 | Creating dataframes for every numpy.ndarray in a list | <p>I am fairly new to Python and trying to figure out how to generate dataframes for multiple arrays. I have a list where the arrays are currently stored:</p>
<pre><code>list = [ [1 2 3 4], [12 19 30 60 95 102] ]
</code></pre>
<p>What I want to do is take each array from this list and put them into separate dataframes,... | <p>As mentioned in the comments, dynamically created variables is a bad idea. Why not use a single dataframe, like so:</p>
<pre class="lang-py prettyprint-override"><code>In [1]: zlist = [[1, 2, 3, 4], [12, 19, 30, 60, 95, 102], [1, 2, 4, 5, 1, 6, 1, 7, 8, 21]]
In [2]: pd.DataFrame({f"array_{i}": pd.Series(z... | python|arrays|pandas|dataframe | 1 |
349,678 | 72,744,666 | How do I fit an input with shape (128,224,224,3) into ResnetV2 | <p>Hello I am new to tensorflow and I am currently having an issue with using Keras's Resnet50_V2 model. The acceptable input to the Resnet layer is only (224,224,3) while my images are in batches of 128. I can only provide a snippet of this part of the code but the error I'm getting is this</p>
<pre><code>ValueError: ... | <ul>
<li>According to the keras official documentation, Input_shape only to be
specified if include_top is False otherwise the input shape has to be
(224, 224, 3) with channels_last data format or (3, 224, 224) with
channels_first data format.</li>
<li>It should have exactly 3 input channels, and width and height shoul... | python|tensorflow|keras | 0 |
349,679 | 72,538,964 | How to make Groupby dataframe using list? | <p>I have xyz dataframe like below.</p>
<pre><code>x y z
1 2 1
1 2 2
3 3 1
3 1 2
4 1 2
'''''
9 3 4
</code></pre>
<p>and I have to make dataframes by x.</p>
<pre><code>df1(x=1)
x y z
1 2 3
1 3 3
df2(x=2)
x y z
2 3 3
2 4 5
dfx(x=n)
x y z
n y z
- - -
</code></pre>
<p>I know pandas df.groupby("x") makes data... | <p>In your case save the df into <code>dict</code></p>
<pre><code>d = {x : y for x , y in df.groupby('x')}
d[1]
</code></pre> | arrays|pandas|numpy|group-by | 0 |
349,680 | 72,616,485 | NumPy advanced indexing using np.ix_() does not always result in the desired shape | <p>I have a snippet of code that looks like this:</p>
<pre><code>def slice_table(table, index_vector)
to_index_product = []
array_indices = []
for i, index in enumerate(index_vector):
if isinstance(index, list):
to_index_product.append(index)
array_indices.append(i)
inde... | <p>As <a href="https://stackoverflow.com/users/901925/hpaulj">@hpaulj</a> mentioned, advanced indexing forms the first subset of dimensions, followed by basic indices. Since slice objects trigger basic indexing, their dimensions are appended to the subslice made by advanced indices. An exerpt <a href="https://numpy.org... | python|numpy|array-broadcasting|numpy-indexing | 0 |
349,681 | 72,678,293 | RAM Overflow Colab, when running model.fit() in Image Classifier of AutoKeras for many images | <p>I'm trying to create an Image Classifier on a dataset with 40'000 images, in order to let Autokeras train the most appropriate model for me afterwards. Now the problem is, that every time I load all the images and get their labels but when I run the normalization Google Colab, there is a RAM overflow (although havin... | <p>I highly recommend you <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="nofollow noreferrer"><code>tf.data.Dataset</code></a> for creating the dataset:</p>
<ol>
<li>Do all processes (like resize and normalize) that you want on all images with <a href="https://www.tensorflow.org/api_docs/pyth... | python|tensorflow|keras|image-classification|auto-keras | 1 |
349,682 | 72,577,980 | AttributeError: 'list' object has no attribute 'assign' | <p>I have this dataframe:</p>
<pre><code> SRC Coup Vint Bal Mar Apr May Jun Jul BondSec
0 JPM 1.5 2021 43.9 5.6 4.9 4.9 5.2 4.4 FNCL
1 JPM 1.5 2020 41.6 6.2 6.0 5.6 5.8 4.8 FNCL
2 JPM 2.0 2021 503.9 7.1 6.3 5.8 6.0 4.9 FNCL
3 JPM 2.0 2020 308... | <p>I'd suggest a helper function to handle all your duplications:</p>
<pre class="lang-py prettyprint-override"><code>def duplicate_and_rename(df, target, value):
return pd.concat([df, df[df["BondSec"] == target].assign(BondSec=value)])
</code></pre>
<p>Then</p>
<pre class="lang-py prettyprint-override"><... | python|pandas|dataframe|indexing|append | 1 |
349,683 | 72,756,089 | Rename a column in dataframe based on a list of str variables | <p>First I have created a for loop to iterate through a NC file based on the list of "variables".
I have created the code below to convert that list to a dataframe and only consider the rows from 4 to 18.</p>
<pre><code>var = data.variables
var = list(var)
var_df = pd.DataFrame(var, columns =['vari'])
var_df... | <p>Rename column example:</p>
<pre><code>df.rename(columns={0: "rainfall"}, inplace=True)
</code></pre>
<p>This renames column 0 to string rainfall</p>
<p>if you want to change it back</p>
<pre><code>df.rename(columns={"rainfall":0}, inplace=True)
</code></pre> | python|pandas|dataframe | 0 |
349,684 | 59,878,744 | { "error": "inputs is a plain value/list, but expecting an object as multiple input tensors required as per tensorinfo_map" } | <p>I am using tensorflow serving to deploy my model . </p>
<p>my tensorinfo map is </p>
<blockquote>
<p>saved_model_cli show --dir /export/1/ --tag_set serve
--signature_def serving_default</p>
</blockquote>
<pre><code>The given SavedModel SignatureDef contains the following input(s):
inputs['length_0'] tensor... | <p>You are passing your input in row format, so if you replace "inputs" to "instances" everything should work fine, <a href="https://www.tensorflow.org/tfx/serving/api_rest#specifying_input_tensors_in_row_format" rel="noreferrer">See here for the difference between row and columnar format</a></p> | python|json|tensorflow|tensorflow-serving | 6 |
349,685 | 59,562,694 | How to split the list of list in to seperate column | <p>My df is below</p>
<pre><code>gender list
MALE [['Office/Work'], ['31-40'], ['Salaried'], ['Master’s/PhD degree']]
</code></pre>
<p>Expected Out df['out']</p>
<pre><code>Type Age EmpType Education
Office/Work 31-40 Salaried Master’s/PhD degree
</code></pre> | <p>If there are only one element values in lists use:</p>
<pre><code>c = ['Type','Age','EmpType','Education']
df = pd.DataFrame([[y[0] for y in x] for x in df['list']], columns=c)
print (df)
Type Age EmpType Education
0 Office/Work 31-40 Salaried Masters/PhD degree
</code></pre> | pandas | 0 |
349,686 | 59,728,014 | How do you to save and load a tensorflow model that has a feature_layer? | <p>I was following this tutorial with my own dataset: <a href="https://www.tensorflow.org/tutorials/load_data/csv" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/load_data/csv</a>.
This was my squential of the model:</p>
<pre><code>model = keras.Sequential([
keras.layers.Dense(128, activation='rel... | <p>Try <a href="https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/Saver" rel="nofollow noreferrer">Saver</a> class member functions: <code>saver.save</code> and <code>saver.restore</code>.
See this <a href="https://cv-tricks.com/tensorflow-tutorial/save-restore-tensorflow-models-quick-complete-tutorial/" re... | python|tensorflow | 0 |
349,687 | 59,603,417 | How to distribute list of even/noteven elements to index pandas | <p>Is there any way to produce below output as I desire</p>
<p>I have pd.dataframe as below:</p>
<pre><code>df1
data
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
</code></pre>
<p>and i want to add column of list </p>
<pre><code>lst1 = ['TEXT1','TEXT2']
lst2 = ['text1','text2','text3']
</code>... | <p>You can group by <code>index</code> and then use <code>.ngroup()</code> as index to your list:</p>
<pre><code>import pandas as pd
d = {'data': [1,2,3,4,5,6,7,8]}
lst2 = ['text1','text2','text3']
df = pd.DataFrame(d)
df['txt'] = df.groupby(df.index // len(lst2)).ngroup().map(lst2.__getitem__) # or .apply(lambda... | python|pandas|numpy | 1 |
349,688 | 59,521,203 | using pgeocode lib of python to find the latitude and longitude | <p>why am I getting NaN in the answer when i run the following code. it works fine for some pin codes and doesnt for others.</p>
<pre><code>import pgeocode
nomi = pgeocode.Nominatim('in')
print(nomi.query_postal_code("302023"))
</code></pre>
<p>the answer i am getting is :</p>
<pre><code>postal_code 302023 co... | <p>For pgeocode to work, it is essential to download a text file containing the postal codes from the specific country of interest.</p>
<p>Head over to <a href="http://download.geonames.org/export/zip/" rel="nofollow noreferrer">http://download.geonames.org/export/zip/</a> and download the zip postal code lookup file ... | python|python-3.x|pandas|numpy|latitude-longitude | 2 |
349,689 | 59,891,563 | Printing specific columns as a percentage | <p>I have multi index dataframe and I want to convert two columns' value into percentage values.</p>
<pre><code> Capacity\nMWh Day-Ahead\nMWh Intraday\nMWh UEVM\nMWh ... Cost Per. MW\n(with Imp.)\n$/MWh Cost Per. MW\n(w/o Imp.)\n$/MWh Intraday\nMape Day-Ahead\nMape
Power Plants Date... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html" rel="nofollow noreferrer"><code>DataFrame.applymap</code></a>:</p>
<pre><code>nested_df[['Intraday\nMape', 'Day-Ahead\nMape']] = \
nested_df[['Intraday\nMape', 'Day-Ahead\nMape']].applymap('{:.0%}'.format)... | pandas|dataframe|format|percentage | 0 |
349,690 | 59,815,440 | Create a new column based on groupby a column value and count of another column in pandas? | <p>I have a pandas dataframe</p>
<pre><code>df = pd.DataFrame({'Birds': ['Falcon','Falcon','Parrot','Peacock','Peacock'],
'Name': ['A', 'D', 'B', 'C', 'C']})
</code></pre>
<p>I need to create a new column, </p>
<pre><code>df = pd.DataFrame({'Birds': ['Falcon','Falcon','Parrot','Peacock','Peacock']... | <p>You can use <code>transform</code> combined with <code>nunique</code>:</p>
<pre class="lang-py prettyprint-override"><code>df["count"] = df.groupby("Birds")["Name"].transform(lambda x: x.nunique() - 1)
</code></pre>
<p><strong>Without <code>lambda</code> - Option 1</strong></p>
<pre class="lang-py prettyprint-ov... | python|pandas | 2 |
349,691 | 59,485,845 | Python, Pandas: The Merged Sum of Some Rows according to Column value | <p>I have the following pandas DataFrame example. I try to to have sum of some spesific rows. I have researched how to carry out, however I could not find the solution. Could you give a direction, please? The example is as below. I thought that I can apply group by and sum but there is column (Value_3) that I would no... | <p>First idea is pass dictionary for aggregate functions, for last column is possible use <code>first</code> or <code>last</code> function:</p>
<pre><code>d = {'Value_1':'sum','Value_2':'sum','Value_3':'first'}
df1 = df.groupby(['Machine','Shift'], as_index=False).agg(d)
</code></pre>
<p>If want more dynamic solution... | python|pandas | 3 |
349,692 | 59,536,633 | How can i save a lot of images with plt.savefigure() in python? | <p>i wrote the next code:</p>
<pre><code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import pylab as pl
files = ["xyz_01.txt", "xyz_02.txt", "xyz_03.txt", "xyz_04.txt", "xyz_05.txt", "xyz_06.txt", "xyz_07.txt", "xyz_08.txt", "xyz_09.txt", "xyz_10.txt","xyz_11.txt","x... | <p>You can make a list consists of your file name. Or simply put something like <code>'img'+i+'.jpg'</code> and do a recursion. </p>
<pre><code>plt.savefig(i[:-4]+'.png')
</code></pre>
<p>if you want to name your image according to the file. <code>i[:-4]</code> is to remove the last 4 characters of <code>i</code> so ... | python|pandas|matplotlib|mplot3d | 1 |
349,693 | 59,871,761 | How to interpret this fft graph | <p>I want to apply Fourier transformation using <code>fft</code> function to my time series data to find "patterns" by extracting the dominant frequency components in the observed data, ie. the lowest 5 dominant frequencies to predict the y value (bacteria count) at the end of each time series.
I would like to preserve... | <p>I'm gonna answer in reverse order of your questions</p>
<blockquote>
<p>3) Why are transformed values all complex numbers? </p>
</blockquote>
<p>The output of a Fourier Transform is always complex numbers. To get around this fact, you can either apply the absolute value on the output of the transform, or only pl... | python|numpy|scipy|signal-processing|fft | 2 |
349,694 | 59,643,614 | ValueError: Failed to find data adapter that can handle input: <class 'numpy.ndarray'>, <class 'pandas.core.series.Series'> | <pre><code>DROPOUT = 0.5
ACTIVATION = "tanh"
model = Sequential([
Dense(int(trainX.shape[1]/2), activation=ACTIVATION, input_dim=trainX.shape[1]),
Dropout(DROPOUT),
Dense(int(trainX.shape[1]/2), activation=ACTIVATION, input_dim=trainX.shape[1]),
Dropout(DROPOUT),
Dense(int(trainX.shape[1]/4), a... | <p>Most likely, your are not converting your X or y to <code>numpy</code>.</p>
<p>The error springs from your data/the way you input the data. You should recheck the manner in which you feed data to your neural network as well as the type of the data (ensure that it's <code>numpy</code> array).</p>
<p><strong>Convert... | python-3.x|tensorflow|keras|tensorflow2.0 | 0 |
349,695 | 59,809,495 | How to install TensorFlow with Python 3.8 | <p>Whenever I try to install TensorFlow with pip on Python 3.8, I get the error that TensorFlow is not found. I have realized later on that it is not supported by Python 3.8.</p>
<p>How can I install TensorFlow on Python 3.8?</p> | <p>As of May 7, 2020, according to <a href="https://www.tensorflow.org/install/pip" rel="noreferrer">Tensorflow's Installation page with pip</a>, Python 3.8 is now supported. Python 3.8 support requires TensorFlow 2.2 or later.</p>
<p>You should be able to install it normally via pip.</p>
<hr />
<p>Prior to May 2020:</... | python|python-3.x|tensorflow|python-3.8 | 14 |
349,696 | 59,564,384 | estimator.train throws ValueError: model_fn should return an EstimatorSpec | <p>Here's the code I'm using...</p>
<p>I've got a breakpoint installed at what is for me line 304...</p>
<p>estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)</p>
<p>Has anyone seen this? I'm certain I have the correct versions of TensorFlow and BERT installed.</p>
<p>The complete stack trace is a... | <p>Horrifyingly, the answer to this problem was all about indentation. There is a function in the Google Colab example posted above called def model_fn. This appears to be wrapper function for another function that actually creates a model to pass to the TensorFlow Estimator. While I was debugging this in VS code I... | tensorflow|tensorflow-estimator|bert-language-model | 0 |
349,697 | 59,501,215 | pandas groupby, filter and aggregate function | <p>I have following dataframe in pandas</p>
<pre><code> key time outlier
1_2 4 False
1_2 2 True
1_2 2 True
1_2 5 True
1_2 6 False
1_3 10 False
1_3 12 False
1_3 10 True
1_3 20 True
<... | <p>First filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>, then aggregate, rename columns names by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.add_prefix.html" rel... | python|pandas | 1 |
349,698 | 59,844,475 | tflite object detection inference not working properly | <ul>
<li><strong>What is the top-level directory of the model you are using</strong>: /home/USER/PROJECT/tf-models</li>
<li><strong>Have I written custom code (as opposed to using a stock example script provided in TensorFlow)</strong>: No</li>
<li><strong>OS Platform and Distribution (e.g., Linux Ubuntu 16.04)</strong... | <p>The output of tflite model requires post-processing. The model returns a fixed number (here, 10 detections) by default. Use the output tensor at index 3 to get the number of valid boxes, <code>num_det</code>. (i.e. top <code>num_det</code> detections are valid, ignore the rest).</p>
<pre><code>num_det = int(interpre... | arrays|tensorflow|object-detection|tensorflow-lite|toco | 2 |
349,699 | 59,550,543 | How to avoid automatic changing of data type in panda dataframe and convert into CSV in python? | <p>I'm trying to convert Json file to csv using pandas in python</p>
<p>json file data:</p>
<pre><code>[{
"source": "https://www.na-kd.com/en/sweaters/cardigans/button-up-ribbed-cropped-cardigan-pink",
"class_ids": "3_33",
"id_matrix": "0_0_0_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_1_0... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html" rel="nofollow noreferrer"><code>astype</code></a> attribute of <code>pandas.DataFrame</code> :</p>
<pre><code>import pandas as pd
raw_data = pd.read_json('/home/mobin/PycharmProjects/na-kd/Jsons/mapped_imp... | python|json|pandas|csv|dataframe | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.