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
7,500
55,908,567
How can I replace any value with an NAN that is not within a certain range of the previous value in a pandas series?
<p>I have a pandas series and I want to find out if a value is within a certain range of the previous value (say 10% above or below) and replace it with NAN if not. I am not sure how to proceed. The standard outlier removal techniques mostly deal with overall standard deviation etc.</p> <p>How can I access the previou...
<p>You can use <code>pct_change</code> as @ALollz mentioned in the comment. Use <code>Series.loc</code> to set the values where the condition is not met to False.</p> <pre><code>ts.loc[ts.pct_change().abs() &gt; 0.1] = np.nan 2018-09-06 NaN 2018-09-07 NaN 2018-09-08 NaN 2018-09-09 662.105 2018...
python|pandas
4
7,501
64,806,982
Pivot Pandas Column of Lists
<p>I have a pandas dataframe that has a column whose values are lists and where another column is a date. I would like to create a dataframe that counts the elements of the lists by date.</p> <p>The dataframe looks like:</p> <p><img src="https://i.stack.imgur.com/zBZtq.png" alt="image of dataframe. I'm not yet awesome ...
<p>You can use <code>extractall</code> to extract the values inside <code>''</code>, then counts the values with <code>groupby</code>:</p> <pre><code>out= (df.col1.str.extractall(&quot;'([^']*)'&quot;) .groupby(level=0)[0].value_counts() .unstack(level=1,fill_value=0) .reindex(df.index, fill_value=0) ) out.in...
python|pandas|list|dataframe|pivot-table
2
7,502
64,762,595
Apply a function from package to one column in Python
<p>Given a small dataset as follows:</p> <pre><code> id floor room company 0 1 1 101.0 NaN 1 2 1 102.0 繁簡轉換器 ---&gt; need to convert 2 3 2 201.0 缔美诗药妆皮肤管理中心 3 4 2 201.0 TT潮牌造型设计(上海) 4 5 2 202.0 TT潮牌造型设计(北京) 5 6 3 Na...
<p>I don't know about <code>HanziConv</code>, but this may be work.</p> <p><code>df['company'] = df['company'].astype(str).apply(HanziConv.toSimplified)</code></p>
python-3.x|pandas|dataframe|apply
1
7,503
40,297,848
SGD with momentum in TensorFlow
<p>In Caffe, the SGD solver has a momentum parameter (<a href="http://caffe.berkeleyvision.org/tutorial/solver.html" rel="nofollow noreferrer">link</a>). In TensorFlow, I see that <code>tf.train.GradientDescentOptimizer</code> does not have an explicit momentum parameter. However, I can see that there is <code>tf.train...
<p>Yes it is. <code>tf.train.MomentumOptimizer</code> = SGD + momentum</p>
tensorflow|optimization|sgd
20
7,504
39,970,099
ValueError for comparison of np.arrays
<p>I have a list of lists of np.arrays, representing islands > island > geodesic point on the island.</p> <p>I'm trying to use:</p> <pre><code>if not groups: createNewGroup(point) else: for group in groups: if point in group: continue else: createNewGroup(point) </code></pre> ...
<p>This error arises when a boolean array is used in a scalar context, such as an <code>if</code> statement. Or maybe in the <code>in</code> part of the expression.</p> <p>Is <code>point</code> an array, and <code>group</code> a list of arrays?</p> <p>In general <code>in</code> is not a good test when working with ...
python|numpy
0
7,505
44,202,825
Tensorflow-GPU Error - Pycharm
<p>I am installing Tensor flow.</p> <p>I was having trouble installing through Anaconda, so I uninstalled everything including Python, and downloaded Python 3.5 from here:</p> <p><a href="https://www.python.org/downloads/release/python-352/" rel="nofollow noreferrer">https://www.python.org/downloads/release/python-35...
<p>You are missing some dependencies. I would recommend to rebuild it from scratch. Use <a href="https://www.tensorflow.org/install/install_windows" rel="nofollow noreferrer">this guide</a> for Windows.</p> <p>You need to fulfill the requirements for running TF GPU.</p>
python|python-3.x|tensorflow
0
7,506
69,516,366
RuntimeError: expected scalar type Float but found Double
<p>My code is as follows:</p> <pre><code>net = nn.Linear(54, 7) optimizer = optim.SGD(net.parameters(), lr=lr, momentum=0) logloss = torch.nn.CrossEntropyLoss() for i in range(niter): optimizer.zero_grad() y_2 = torch.from_numpy(np.array(y, dtype='float64')) X_2 = torch.from_numpy(np.array(X, dtype='float64...
<p>You need to cast your tensors to <em>float32</em>, either with <code>dtype='float32'</code> or calling <code>float()</code> on your input tensors.</p>
pytorch|logistic-regression
1
7,507
69,371,559
Pandas - group sales by month
<p>I need help with group sales for employee_ID by month.</p> <p>with this:</p> <pre><code>date |employee_ID |price 2000-01-01| 12 | 300 2000-01-02| 12 | 250 </code></pre> <p>i want make this</p> <pre><code>date | employee_ID |total_sales 2000-01 | 12 2 </code></pre> <p>I dont kno...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Grouper.html" rel="nofollow noreferrer"><code>Grouper</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</code></a>:</p> <p...
python|pandas
1
7,508
69,434,657
How to iterate over pandas dataframe column which is a list and then map to new values
<p>I have a dataframe like below. I want to iterate through the &quot;label&quot; column values and replace to new values which is label_dict = {1:'production', 2:'to_be_discussed'}</p> <pre><code> Name label score 0 prdn [2, 1] [0.886071, 0.78242475] 1 tbd [1] [0.9897076] </code></pre> <p>I tri...
<p>Solution working with lists in column <code>label</code>:</p> <pre><code>#if not lists but strings create them #import ast #df['label'] = df['label'].apply(ast.literal_eval) </code></pre> <p>Solution with removing values from original column if not exist in keys of dict:</p> <pre><code>label_dict = {1:'production', ...
python|pandas
3
7,509
41,157,005
python pandas - joining specific columns
<p>I have a main dataframe (MbrKPI4), and I want to left join it with another dataframe (mbrsdf). They have the same index. I am successful with the below.</p> <pre><code>MbrKPI4.join(mbrsdf['Gender']) </code></pre> <p>However, I want to join more columns from mbrsdf, and the below does not work (MemoryError). Is the...
<p>Based on documentation for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow noreferrer">join()</a> I think you want to pass in an array of dataframes to left join by, or chain join calls.</p> <pre><code>d1.join([d2['Gender'], d2['Marital Status']]) d1.join(d2[...
python|pandas
0
7,510
41,092,836
Pandas get sorted index order for multiple columns
<p>I have something like the following multi-index Pandas series where the values are indexed by Team, Year, and Gender. </p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; multi_index=pd.MultiIndex.from_product([['Team A','Team B', 'Team C', 'Team D'],[2015,2016],['Male','Fem...
<p>Starting from your unstacked version, you can use <code>.argsort()</code> with <code>.apply()</code> to rank order each column and then just use that as a lookup against the index:</p> <pre><code>df.unstack([1,2]).apply(lambda x: x.index[x.argsort()]).reset_index(drop=True) Year 2015 2016 G...
python|pandas
2
7,511
41,131,728
Problems with KNN implemantion in TensorFlow
<p>I am struggling to implement K-Nearest Neighbor in TensorFlow. I think that either I am overlooking a mistake or doing something terrible wrong.</p> <p>The following code always predicts Mnist labels as 0.</p> <pre><code>from __future__ import print_function import numpy as np import tensorflow as tf # Import MN...
<p>So in general it's not a good idea to go to <code>numpy</code> functions while defining your TensorFlow model. That's precisely why your code wasn't working. I have made just two changes to your code. I have replaced <code>np.argmax</code> with <code>tf.argmax</code>. I've also removed the comments from <code>#This ...
python|machine-learning|tensorflow|knn
13
7,512
53,875,372
How do I modify this PyTorch convolutional neural network to accept a 64 x 64 image and properly output predictions?
<p>I took this convolutional neural network (CNN) from <a href="https://gist.github.com/johnolafenwa/96b3322aabb61d4d36fd870a77f02aa3" rel="nofollow noreferrer">here</a>. It accepts 32 x 32 images and defaults to 10 classes. However, I have 64 x 64 images with 500 classes. When I pass in 64 x 64 images (batch size held...
<p>The problem is an incompatible reshape (view) at the end.</p> <p>You're using a sort of &quot;flattening&quot; at the end, which is different from a &quot;global pooling&quot;. Both are valid for CNNs, but only the global poolings are compatible with any image size.</p> <h2>The flattened net (your case)</h2> <p>In y...
python|conv-neural-network|pytorch
1
7,513
53,873,845
Filter a pandas dataframe by a list of column values
<p>This is a subsample of my dataframe:</p> <pre><code>idcontrn ctosaldo fecanota diamovto fecopera codsprod 491748 000 2017-08-25 3 2017-08-25 0 1014320 000 2018-05-28 99999 2018-05-28 33 1907630 000 2017-06-12 99999 2017-06-0...
<p>Use <code>groupby</code> + <code>size</code> + <code>head</code> to get the largest <code>'codsprod'</code> groups. Use <code>.isin</code> to filter the original <code>DataFrame</code>. To get the largest 2 groups:</p> <pre><code>df[df.codsprod.isin(df.groupby('codsprod').size().head(2).index)] </code></pre> <h3>O...
python|python-3.x|pandas|dataframe|conditional-statements
2
7,514
53,979,515
Representing ratios in a pandas Dataframe Columns
<p>I am trying to represent ratios in dataframe column. However, the formatting I am getting is totally horrendous when I am just able to use a print function and print what I want. The true problem is representing it in a correct format.</p> <p>what I have done is create the Greatest common divisor, apply it to my d...
<p>It's not clear how you derive <code>3:2</code> and <code>4:5</code>. But note you can use NumPy (via <code>np.gcd</code>) for calculating the greatest common divisor, since these operations will be vectorised. Alternatively, you can use the <a href="https://docs.python.org/3.7/library/fractions.html" rel="nofollow n...
python|pandas
0
7,515
52,458,563
Tensorflow Parameter server: Is it necessary?
<p>I'm currently experimenting with tensorflow distribution and I was wondering if it is necessary to include the parameter server.</p> <p>The method that I am using is tf.estimator.train_and_evaluate. My setup is one master, one worker, and one parameter server running on three servers.</p> <p>It seems that the par...
<p>After doing multiple tests...yes you do need a parameter server</p>
python|tensorflow|distributed-computing
1
7,516
52,479,349
How to use named binds with bulk inserts (executemany) in cx_Oracle from pandas dataframe
<p>I am uncertain on how to bulk insert to Oracle from Python 3 using named bind-variables, when source-data is in a Pandas Dataframe. The code below shows my attempt. With unnamed binds, it is pretty easy, but errorprone, as the order of binds need to be the same as columns in the Dataframe. </p> <pre><code> "Name...
<p>If you intend to use named bind variables you will need to do the following instead:</p> <pre><code>[{"a" : 1, "b" : "Dog"}, {"a" : 2, "b" : "Cat"}] </code></pre> <p>In other words you need to create a list of dictionaries instead of a list of lists.</p>
python-3.x|pandas|dataframe|cx-oracle
1
7,517
52,798,399
EXCLUDED from export because they cannot be be served via TensorFlow Serving APIs
<p>Tensorflow version 1.10</p> <p>Using: <code>DNNClassifier</code> and <code>tf.estimator.FinalExporter</code></p> <p>I'm using the Iris example from TF <a href="https://developers.googleblog.com/2017/09/introducing-tensorflow-datasets.html" rel="nofollow noreferrer">blog</a>. I defined the following code:</p> <pre...
<p>I found a solution <a href="https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/iris/tensorflow/estimator/trainer/model.py" rel="nofollow noreferrer">here</a>.</p> <pre><code>def _make_input_parser(with_target=True): """Returns a parser func according to file_type, task_type and target. Need to s...
tensorflow|google-cloud-ml|tensorflow-estimator
0
7,518
52,600,059
Pandas qcut based on expanding window of all columns
<p>Let's say I have a dataframe:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.normal(0,1,[100,50])) </code></pre> <p>that looks like:</p> <pre><code> 0 1 2 3 4 5 6 \ 0 -0.141305 2.158252 1.006520 -1.004185 -0.213160 0....
<p>For anyone who stumbles upon this Q, below is what I went with. There may be faster solutions, so please post if you have any better ideas.</p> <p>Thanks</p> <pre><code>def standardize_block(df_standardize_arg): df_standardize_arg = df_standardize_arg.copy() ix_ = df_standardize_arg.index prior_data = ...
python|python-3.x|pandas|dataframe
0
7,519
46,449,716
Most efficient way to test whether each element from one 1-d array exists in corresponding row of another 2-d array, using python
<p>I would like to know the most efficient way to test whether each element from one 1-d array exists in corresponding row of another 2-d array, using python</p> <p>Specifically, I have two arrays. The first is an 1-d array of integers. The second is a 2-d array of integers.</p> <p>Sample input:</p> <pre><code>[1, 4...
<p>You can reshape <code>a</code> to 2d array, compare with <code>b</code> and then check if there's any <code>True</code> in each row:</p> <pre><code>np.equal(np.reshape(a, (-1,1)), b).any(axis=1) </code></pre> <hr> <pre><code>a = [1, 4, 12, 9] # array 1 ​ b = [[1, 12, 299], [2, 5, 11], [1, 3, 11], [...
python|numpy
1
7,520
58,346,764
Histogramm Binning Two Data Sets With Reference To Each Other
<p>I have two lists of equal length. Each item in one list corresponds to the same index in the other list. I have histogrammed one of the two lists:</p> <pre><code>xnums, xbins = np.histogram(x) </code></pre> <p>What I need is a quick way to bin the corresponding data accordingly, i.e. bin the data in y in correspon...
<p>If I understand correctly, then you want to use <code>xbins</code> as <code>ybins</code>, and find the corresponding <code>ynums</code> (i.e. the counts).</p> <p>You want <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html" rel="nofollow noreferrer"><code>np.digitize()</code></a>. Give...
python|numpy|histogram|binning
0
7,521
58,498,669
video segmentation on mobile devices
<p>I have used tensorflow.js to do person segmentation of live video in a web browser. Is there a similar tensorflowlite/mobile version of the same? Is there any android SDK available to do person/video segmentation on mobile clients? Any pointers would be very helpful.</p> <p>thanks Sowmya</p>
<p>Yes, TensorFlow Lite is available for Android. <a href="https://www.tensorflow.org/lite/guide/android" rel="nofollow noreferrer">Click here for more.</a></p>
tensorflow|tensorflow-lite
0
7,522
69,026,756
How to select a row in a pandas DataFrame datetime index using a datetime variable?
<p>I am not a Professional programmer at all and slowly accumulating some experience in python. This is the issue I encounter.</p> <p>On my dev machine I had a python3.7 installed with pandas version 0.24.4</p> <p>the following sequence was working perfectly fine.</p> <pre><code> &gt;&gt;&gt; import pandas as pd &gt;&...
<p>It depends of version. If need more robust solution use <code>datetime</code>s for match <code>DatetimeIndex</code>:</p> <pre><code>import datetime D = datetime.datetime(2000,1,1) print (df[D]) 0 </code></pre>
python-3.x|pandas|dataframe|datetime
1
7,523
68,946,196
Reading in a Database file (DBF) using Python and then plotting the shapefile
<p>My goal is to read in a DBF from CropScape using Python and plot the DBF to create a figure as in the example. I need help reading in and plotting the DBF.</p> <p>DATA: I download the CropScape Cropland DBF from <a href="https://nassgeodata.gmu.edu/CropScape/" rel="nofollow noreferrer">https://nassgeodata.gmu.edu/Cr...
<ul> <li>As per <strong>ArcGIS_coloro_table_readme.docx</strong>, which downloads in the zip file, all of the downloaded files are specifically for <code>GeoTIFF</code> in <code>ArgGIS</code>. There is no shape, or geolocation data in the <code>.dbf</code> files.</li> <li><strong><code>'CDL_2020_clip_20210826173123_160...
python|shapefile|geopandas|geotiff
1
7,524
69,167,900
Numpy slice not updating as expected
<p>I've written an algorithm for LU decomposition of a square matrix. Problem I'm facing is that the values in a NumPy 2-d array <strong>slice</strong> are <strong>not updating as expected</strong>. See the image at the bottom.</p> <p>The matrix A is defined as follows:</p> <pre><code>A = np.array([[1, -3, 5, 2], [1, 0...
<p><code>B</code> is an integer array, so the incoming values are being cast to integers. If you need floats. you should use <code>astype</code> to convert <code>B</code> to float64.</p>
python|numpy|array-broadcasting
0
7,525
68,982,750
Python - Pandas - KeyError: "None of [Index(['questions'], dtype='object')] are in the [columns]"
<p>I am new to Python, and currently trying to write a code which will suggest answers to specific questions automatically. I have this issue, when running the following code:</p> <pre><code>import pandas as pd df=pd.read_csv(&quot;Book11.csv&quot;, encoding= 'cp1252'); df.columns=[&quot;question&quot;,&quot;answers&qu...
<p>On the windows computer, try reading and changing the encoding to utf8:</p> <pre><code>import pandas as pd df=pd.read_csv(&quot;Book11.csv&quot;, encoding= 'cp1252') df.to_csv(&quot;Book11-utf8.csv&quot;, encoding='utf-8', index_col=None) </code></pre> <p>Copy the utf8 csv file to the VM.</p> <p>Then on the VM mach...
python|pandas|dataframe
0
7,526
68,916,814
After scaling the train and test data, the model score goes to 1, something doesn't seem right?
<p>prescaled features <a href="https://i.stack.imgur.com/kDmb6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kDmb6.png" alt="enter image description here" /></a></p> <pre><code>scaler.fit(x_train) scaler.fit(x_test) xts= scaler.transform(x_train) xts=pd.DataFrame(xts, columns=x_train.columns) xtest...
<p>It's hard to say without more data to work on, but it is possible, especially given the dramatic impact of scaling on your dataset. Take a look at the impact of scaling in this below example. In a 2-d case it is easier to picture, and it's important to understand that a score of 1 indicates there is most likely no o...
python|pandas|machine-learning|svm
0
7,527
68,947,061
how low in dataframe to find all elements of list
<p>I have a list:</p> <pre><code>elements = ['a', 'b', 'c', 'd'] </code></pre> <p>And a dataframe that has some or all of the elements of my list:</p> <pre><code> mycol 0 a 1 x 2 y 3 e 4 b 5 c 6 o 7 l 8 s 9 d 10 g </code></pre> <p>I want to know how low I have...
<p>It's worth considering <a href="https://stackoverflow.com/questions/68947061/how-low-in-dataframe-to-find-all-elements-of-list/68947793#comment121849905_68947061">Barmar's comment</a>. I couldn't get the fancier indexing answers to work with some bigger testing data, but Barmar's loop should be reliable:</p> <blockq...
python|pandas|list|dataframe
2
7,528
44,396,618
Vectorize or optimize an loop where each iteration depends on the state of the previous iteration
<p>I have an algorithm which I am implementing in python. The algorithm might be executed 1.000.000 times so I want to optimize it as much as possible. The base in the algorithm is three lists (<code>energy</code>, <code>point</code> and <code>valList</code>) and two counters <code>p</code> and <code>e</code>.</p> <p>...
<p>Within the current problem setting that's not possible since vectorization essentially requires that your <code>n</code>-th computation step shouldn't depend on previous <code>n-1</code> steps. Sometimes, however, it's possible to find so-called "closed form" of a recurrence <code>f(n) = F(f(n-1), f(n-2), ... f(n-k)...
python|performance|numpy|optimization
1
7,529
61,095,091
How to strip and split in pandas
<p>Is there a way to perform a split by new line and also do a strip of whitespaces in a single line ? this is how my df looks like originally</p> <pre><code> df["Source"] 0 test1 \n test2 1 test1 \n test2 2 test1 \ntest2 Name: Source, dtype: object </code></pre> <p>I used to do a sp...
<pre><code>df['Source'].str.split('\n').apply(lambda x: [e.strip() for e in x]).tolist() </code></pre>
python|pandas
5
7,530
71,552,215
Merge two DataFrame on the index, but if one DFs is missing an index I want it to create Null (Nan) values if one of the DFs is missing that index
<p>I want to merge two DataFrames on the index. But if one of those DataFrames is missing an index value I want it to put null ('Nan') values in the place of the new DataFrame for whatever Dataframe is missing that index.</p> <pre><code>import pandas as pd dict1 = { 'Short Name': ['SOO','BS', 'SOC'], 'File': [...
<p>Try <code>join</code></p> <pre><code>out = df1.join(df2,lsuffix='_x',rsuffix='_y',how='left') Out[934]: File_x acc1 File_y acc2 Short Name SOO r1 321 NaN NaN BS r2 321 NaN NaN SOC r3 321 r2 123 </code></pre>
python|pandas|database|dataframe|jupyter-notebook
1
7,531
71,567,214
efficient way to calculate between columns with conditions
<p>I have a dataframe looks like</p> <pre><code> Cnt_A Cnt_B Cnt_C Cnt_D ID_1 0 1 3 0 ID_2 1 0 0 0 ID_3 5 2 0 8 ... </code></pre> <p>I'd like to count columns that are not zero and put the result into new column like this,</p> <pr...
<p>Check if each value not equals to 0 then sum on columns axis:</p> <pre class="lang-py prettyprint-override"><code>df['Total_Not_Zero_Cols'] = df.ne(0).sum(axis=1) print(df) # Output Cnt_A Cnt_B Cnt_C Cnt_D Total_Not_Zero_Cols ID_1 0 1 3 0 2 ID_2 1 0 0 ...
python|pandas
5
7,532
71,658,063
In google-colab pandas.read_pickle() is not working on pickle5
<p>I made a pickle file of a dataframe from my computer using <code>pd.to_pickle()</code> which I could not read in colab. It gives error <code>ValueError: unsupported pickle protocol: 5</code>. Please give a solution.</p>
<p>You need to install <code>pickle5</code> first, using:</p> <pre><code>!pip install pickle5 </code></pre> <p>Then,</p> <pre><code>#Import the library import pickle5 as pickle path = 'path_to_pickle5' with open(path, &quot;rb&quot;) as dt: df = pickle.load(dt) </code></pre>
pandas|dataframe|google-colaboratory|pickle
1
7,533
71,636,236
Add a new column for color code from red to green based on the increasing value of Opportunity in data frame
<p>I have a data frame and I wanted to generate a new column for colour codes which stars from red for the least value of <strong>Opportunity</strong> and moves toward green for highest value of <strong>Opportunity</strong></p> <p>My Data Frame -</p> <pre><code>State Brand DYA Opportunity Jharkhand ...
<p>To obtain the color range from red to green you can use matplotlib <a href="https://matplotlib.org/stable/tutorials/colors/colormaps.html#diverging" rel="nofollow noreferrer"><code>color maps</code></a>, more specifically, the <code>RdYlGn</code>. But before applying the color mapping, first, you need to normalize t...
python|pandas|dataframe|data-science
2
7,534
71,735,256
How to read csv file as dataframe with missing headers and data shift problem in certain rows due to extra commas?
<p>I want to read this CSV file in data frame</p> <pre><code>Username,Identifier,First name,Last name,Department,Location booker12,9012,Rachel,Booker,,,Sales,Manchester grey07,2070,Laura,Grey,,,Depot,London johnson81,4081,Craig,Johnson,Depot,London jenkins46,9346,Mary,Jenkins,Engineering,Manchester smith79,5079,Jamie,S...
<p>you have to use pd.merge with NaN with the right column</p>
python|pandas|dataframe|csv|header
0
7,535
71,668,357
Calling a specific Pandas Dataframe from user input to use in a function?
<p>This might have been answered, but I can't quite find the right group of words to search for to find the answer to the problem I'm having.</p> <p><strong>Situation</strong>: I have a several data frames that could be plugged into a function. The function requires that I name the data frame so that it can take the sh...
<p>I'd recommend assigning each of your dataframes to a dictionary, then retrieving the dataframe by name from the dictionary to pass it to the <code>heatmap</code> function.</p> <p>For example:</p> <pre><code>df_by_name = {&quot;df_a&quot;: pd.DataFrame(), &quot;df_b&quot;: pd.DataFrame()} table_name= input('specify T...
python|pandas|dataframe|user-input|shapes
2
7,536
69,839,409
Reorder axis in TensorFlow Keras layer
<p>I am building a model that applies a random shuffle to data along the first non batch axis, applies a series of Conv1Ds, then applies the inverse of the shuffle. Unfortunately the <code>tf.gather</code> layer messes up the batch dimension <code>None</code>, and i'm not sure why.</p> <p>Below is an example of what ha...
<p>Try to wrap <code>input_img</code> and <code>order</code> into a list when you pass them to <code>tensor</code> layer.</p> <p>In this way <code>tensor</code> layer becomes:</p> <pre><code>tensor = layers.Lambda(lambda x: tf.gather(x[0], tf.cast(x[1], tf.int32), axis=1,))([input_img, order]) </code></pre> <p>and your...
python|tensorflow|keras|tensorflow2.0|tf.keras
1
7,537
43,381,986
Creating list of 2D matrices in Python
<p>I am trying to create a list of 2d matrices, as per the illustration below:</p> <p><a href="https://i.stack.imgur.com/8kQJe.jpg" rel="nofollow noreferrer">list of 2d matrices</a></p> <p>Basically, I want to start with a NxN matrix with all zeros and sequentially replace the 0's with 1's (as shown in the image). Wi...
<p>This will do the job:</p> <pre><code>import numpy as np dim = 4 x=[] for i in range(dim): lst=[] matrix=np.zeros((dim,dim)) vec=np.ones(i+1) for j in range(dim): matrix[0:i+1,j]=vec lst.append(np.copy(matrix)) x.append(lst) print(x) </code></pre>
python|python-3.x|numpy|for-loop|matrix
0
7,538
72,226,280
Perform a merge by date field without creating an auxiliary column in the DataFrame
<p>Be the following DataFrames in python pandas:</p> <pre><code>| date | counter | |-----------------------------|------------------| | 2022-01-01 10:00:02+00:00 | 34 | | 2022-01-03 11:03:02+00:00 | 23 | | 2022-02-01 12:00:05+00:00 | 12 | |...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> with datetimes without times by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.normalize.html" rel="nofollow noreferrer"><code>Seri...
python|pandas|dataframe|datetime
1
7,539
72,316,941
Create a pandas.PeriodIndex from a list of quarter strings in format YYYYQ
<p>I know a bit about <code>pandas.Period</code> and <code>pandas.PeriodIndex</code>. But I am not able to make them fit to my use case.</p> <p>I have a list of <em>quarter strings</em> in format <code>YYYYQ</code>:</p> <pre><code>df = pandas.DataFrame({'quarter': ['20214', '20222']}) </code></pre> <p>How can I create ...
<p>Add <code>q</code> before last digit by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>Series.str.replace</code></a> and then is possible converting to quarters by your solution:</p> <pre><code>df['quarter'] = pd.PeriodIndex(df['quar...
python|pandas
1
7,540
72,288,839
`logits` and `labels` must have the same shape, received ((None, 512, 768) vs (None, 1)) when using transformers
<p>I get the next error when im trying to fine tuning a bert model to predict sentiment analysis.</p> <p>Im using as input: X-A list of strings that contains tweets y-a numeric list (0 - negative, 1 - positive)</p> <p>I am trying to fine tuning a bert model to predict sentiment analysis but i always get the same error ...
<p>As described in this <a href="https://www.kaggle.com/code/dhruv1234/huggingface-tfbertmodel/notebook" rel="nofollow noreferrer">kaggle notebook</a>, you must build a custom Keras Model around the pre-trained BERT model to perform classification,</p> <blockquote> <p>The bare Bert Model transformer outputing raw hidd...
tensorflow|machine-learning|keras|sentiment-analysis|bert-language-model
0
7,541
50,584,887
Python: how to get sum of values based on different columns
<p>I have a datframe <code>df</code> like the following:</p> <pre><code>df name city 0 John New York 1 Carl New York 2 Carl Paris 3 Eva Paris 4 Eva Paris 5 Carl Paris </code></pre> <p>I want to know the total number of people in the different cities</p> <pre><code>df2 city ...
<p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</code></a>:</p> <pre><code>df1 = df.groupby(['city']).size().reset_index(name='number') print (df1) city number 0 New York 2 1 Paris ...
python|pandas|group-by
1
7,542
50,507,468
Fastest way to parse a column to datetime in pandas
<p>I have the following dataframe with more than 400 000 lines.</p> <pre><code>df = pd.DataFrame({'date' : ['03/02/2015 23:00', '03/02/2015 23:30', '04/02/2015 00:00', '04/02/2015 00:30', '04/02/2015 01:00', '04/02/2015 01:30', '04/02/2015 02:00', '04/02/2015 02:30', '04/02/2015 03:00', '04/02/2015 03:30', '04/02/2015...
<p>You can define format of <code>datetime</code>s by <a href="http://strftime.org/" rel="noreferrer">http://strftime.org/</a>:</p> <pre><code>df = pd.concat([df] * 1000, ignore_index=True) %timeit df['dateTimeFormat1'] = pd.to_datetime(df['date'],dayfirst=True) 2.94 s ± 285 ms per loop (mean ± std. dev. of 7 runs, ...
pandas|parsing|datetime
10
7,543
62,815,494
Python/Pandas: Find min value in dataframe or dictionary
<p>I created a dictionary in a for loop which gave me the following 192 results:</p> <pre><code>dic_aic = {0: 16.83024400288158, 1: 10.580792750644934, 2: 10.460203246761916, 3: 10.44309674334913, 4: 10.425859422774248, ... 191: 10.273789550619007, 192: 10.272853618268071} </code></pre> <p>When I plot this out ...
<p>You can first set min value as you just did.</p> <p>Then you need to set a tolerance value like 0.1.</p> <p>Then you can return smallest key value with with satisfies min +- tolerance</p> <pre><code>minimum = min(aic_dic, key=aic_dic.get) #your code here tolerance = 0.1 #could be higher lower up to you possible_ans...
python|pandas|optimization
1
7,544
62,880,355
Creating new variable based on data in dataframe, ignore NaN
<p>I have a dataframe like that below and want to create a new variable that is a <code>1/0</code> or <code>True/False</code> if all of the available scores in certain columns are equal to or above 4.</p> <p>The data is quite messy. Some cells are <code>NaN</code> (respondent didn't provide a response), some are white ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="nofollow noreferrer"><code>pd.to_numeric</code></a> with optional parameter <code>errors=coerce</code> to convert each of the column in <code>Var1</code>, <code>Var2</code> and <code>Var3</code> to numeric type, then...
python|pandas|dataframe
0
7,545
62,752,191
Seaborn columnwise violinplot
<p>I have a dict <code>d</code> which lists numbers' occurences:</p> <pre><code>{'item1': [42, 1, 2, 3, 42, 2, 1, 1, 1, 1, 1], 'item2': [2, 5], 'item3': [5, 1, 7, 2, 7, 1, 42, 2, 9]} </code></pre> <p>Which I then convert to a DataFrame counting these occurences:</p> <pre><code>df = pd.DataFrame.from_dict({k: dict(Cou...
<p>Pass <code>DataFrame</code> to <a href="https://seaborn.pydata.org/generated/seaborn.violinplot.html" rel="nofollow noreferrer"><code>seaborn.violinplot</code></a>, so each Series (column) is plotted separately:</p> <pre><code>sns.violinplot(data=df) </code></pre> <p><a href="https://i.stack.imgur.com/heD0Q.png" rel...
python|pandas|dataframe|plot|seaborn
2
7,546
54,250,651
How Weight update in Dynamic Computation Graph of pytorch works?
<p>How does the Weight Update works in Pytorch code of Dynamic Computation Graph when Weights are shard (=reused multiple times)</p> <p><a href="https://pytorch.org/tutorials/beginner/examples_nn/dynamic_net.html#sphx-glr-beginner-examples-nn-dynamic-net-py" rel="nofollow noreferrer">https://pytorch.org/tutorials/begi...
<p>When you call <a href="https://pytorch.org/docs/master/autograd.html#torch.autograd.backward" rel="nofollow noreferrer"><code>backward</code></a> (either as the function or a method on a tensor) the gradients of operands with <code>requires_grad == True</code> are calculated with respect to the tensor you called <co...
deep-learning|pytorch|computation-graph
4
7,547
54,640,571
Iterating through Pandas rows after an initial condition in the same row is met
<p>“I am trying to write a program that uses a pandas data.rsi and iterate through this column. if rsi > 70 i would like to check whether the n next data points have an rsi of 60, if the do and the rsi moves above 70 again a would like to create a 1 in a column called data.RSIFI ”</p> <p>To sum it up the problem is to...
<p>The problem is that <code>.loc</code> is used for accessing a group of rows, while the <code>.at</code> method accesses the value of a single index of the data frame. </p> <pre><code>for i in data.index: val = data.at[i,'rsi'] if val &gt; 70 and data.at[i, 'cross_ov_un'] == 1: data.at[i,'RSIFI']= ...
python|python-3.x|pandas
0
7,548
54,647,372
Check if values of multiple columns are the same (python)
<p>I have a binairy dataframe and I would like to check whether all values in a specific row have the value 1. So for example I have below dataframe. Since row 0 and row 2 all contain value 1 in col1 till col3 the outcome shoud be 1, if they are not it should be 0.</p> <pre><code>import pandas as pd d = {'col1': [1, 0...
<p>A classic case of <code>all</code>. </p> <p>(The <code>iloc</code> is just there to disregard your current outcome col, if you didn't have it you could just use <code>df == 1</code>.)</p> <pre><code>df['outcome'] = (df.iloc[:,:-1] == 1).all(1).astype(int) col1 col2 col3 outcome 0 1 1 ...
python|pandas|similarity
11
7,549
71,342,922
TensorFlow.js prediction time is difference between the first trial and followings
<p>I am testing to load the TensorFlow.js model and trying to measure how many milliseconds it takes to predict. For example, the first time, it takes about 300 milliseconds to predict value but the time is decreased to 13~20 milliseconds from the second trial. I am not calculating time from the model loading. I am cal...
<p>Usually the first prediction would take longer due to needing to load the model into memory from the API request, once thats done it would be cached and you would not need make the same API request again.</p> <p>If you wanted to see the actual prediction time, repeat the process of timing the predictions many times(...
javascript|memory|time|tensorflow.js|performance-measuring
0
7,550
52,282,896
ML Engine: Prediction Error while executing local predict command
<p>I have uploaded a version of the model in the Google ML Engine with <code>saved_model.pb</code> and a variables folder. When I try to execute the command:</p> <pre><code>gcloud ml-engine local predict --model-dir=saved_model --json-instances=request.json </code></pre> <p>It shows the following error:</p> <pre><co...
<p>It appears your model was exported with only one input named "inputs". In that case, you shouldn't be sending "key" in the JSON, i.e., (scroll to the end to see I've removed "keys"):</p> <pre><code>{"inputs": {"b64": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLD...
python|tensorflow|machine-learning|google-cloud-platform|google-cloud-ml
1
7,551
52,097,943
count and calculate percentage of each column by threshold in Python
<p>If I have a following dataframe:</p> <pre><code>studentId sex history english math biology 01 male 75 90 85 60 02 female 85 80 95 70 03 male 55 60 78 86 04 male 90 89 ...
<p>Use:</p> <pre><code>s = df.iloc[:, 2:].ge(80).mean().mul(100) print (s) history 50.0 english 75.0 math 50.0 biology 50.0 dtype: float64 </code></pre> <p><strong>Explanation</strong>:</p> <p>First select only necessary columns by positions by <a href="http://pandas.pydata.org/pandas-docs/stable/gene...
python|pandas
8
7,552
60,577,436
Append multiindex dataframe in HDF
<p><strong>Following end-of-day stock data as example:</strong></p> <pre><code>In [36]: df Out[36]: Code Name High Low Close Volume Change Change.2 0 AAAU Perth Mint Physical Gold ETF 16.8500 16.3900 16.6900 311400 0.0000 0.02 1 AADR Advisorsh...
<p>The answer to my main problem was quite simple:</p> <p>Fond it here: <a href="https://github.com/pandas-dev/pandas/issues/4584" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues/4584</a></p> <p>Just add 'append = True'</p> <pre><code>df.to_hdf(wkd + 'Database.h5', key='stocks', mode='a', forma...
python|pandas|hdf5
0
7,553
72,748,479
numpy - conditional change with closest elements
<p>In a numpy array, I want to replace every occurrences of 4 where top and left of them is a 5.</p> <p>so for instance :</p> <pre><code>0000300 0005000 0054000 0000045 0002050 </code></pre> <p>Should become :</p> <pre><code>0000300 0005000 0058000 0000045 0002000 </code></pre> <p>I'm sorry I can't share what I tried,...
<p>this might seem tricky, but an <code>and</code> between three shifted versions of the matrix will work, you simply need to shift the x==5 array to the bottom, and another version of it shifted to the right, the third matrix is the x==4.</p> <pre class="lang-py prettyprint-override"><code>first_array = np.zeros(x.sha...
python|numpy
2
7,554
72,793,767
Matching two columns with the same row values in a csv file
<p>I have a csv file with 4 columns:</p> <pre><code>Name Dept Email Name Hair Color John Smith candy Lincoln Tun brown Diana Princ candy John Smith gold Perry Plat wood Oliver Twist bald Jerry Springer clothes Diana Princ gold Calvin Klein clo...
<p>You could use merge for that:</p> <pre><code>pd.merge(df[['Name','Dept']],df[['Email Name','Hair Color']], left_on='Name', right_on='Email Name', how='left') </code></pre> <p><strong>Result</strong></p> <pre><code> Name Dept Email Name Hair Color 0 John Smith candy John Smith ...
python-3.x|pandas|csv|sorting
1
7,555
72,532,019
Finding points in radius of each point in same GeoDataFrame
<p>I have geoDataFrame:</p> <pre class="lang-py prettyprint-override"><code>df = gpd.GeoDataFrame([[0, 'A', Point(10,12)], [1, 'B', Point(14,8)], [2, 'C', Point(100,2)], [3, 'D' ,Point(20,10)]], columns=['ID','Value','geometry'...
<p>Although in your example the output will have a predictable amount of columns in the resulting dataframe, this not true in general. Therefore I would instead create a column in the dataframe that consists of a lists denoting the index/value/geometry of the nearby points.</p> <p>In a small dataset like you provided, ...
python-3.x|pandas|geopandas|shapely
0
7,556
59,819,683
concatenate more than two model of cnn in keras
<p>I make model by keras in <strong>CNN like MNIST.h5,cifar10.h5,dogs_and_cats_classification.h5</strong> .but these model is bounded in their own class like mnist only predict handwritten digit or dogs_and_cats_classification.h5 only predict dogs or cats output separately. but I want to make a <strong>single model</st...
<p>You can remove the last dense layer, add a new dense layer and then retrain your model, or you can create a multi output ensemble, which you can learn more about from keras FAQ.</p>
tensorflow|keras|conv-neural-network
0
7,557
59,515,290
Since it is not "checkpoint", what is the standard method for crash-recovery to resume TensorFlow 2.0 Training?
<p>To resume training after a crash, one must restore not only the model but all objects and parameters that go into the state of a <code>model.fit(...)</code> process. </p> <p>Before I go bother to fork the <code>keras</code> code to implement a <code>fitting</code> object includes for example, the training data, I'...
<p>The canonical way of checkpointing a <code>tf.keras.Model.fit()</code> process is the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint" rel="nofollow noreferrer">ModelCheckpoint</a> callback. </p> <p>The usage looks something like:</p> <pre class="lang-py prettyprint-override"...
tensorflow2.0|checkpointing
0
7,558
59,788,539
How can I convert this tensor to a numpy array?
<p>I'd like to apply the pagerank algorithm to the x_attn tensor. But the nx.pagerank module only accepts numpy arrays. When I try to convert it to using <strong>x_att.eval()</strong>, it says:</p> <p>"tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'main_inpu...
<p>On your tensor (v2.0):</p> <p><code>npa = tf.numpy()</code></p> <p>where npa will be your numpy array name.</p> <p>Alternatively, tensor (&lt; v2.0):</p> <pre class="lang-py prettyprint-override"><code>npa=tf.eval() print(type(npa)) </code></pre> <p>Update 1:</p> <p>Use below code how to check what type of arr...
python|tensorflow|keras
0
7,559
59,551,458
Numpy / PyTorch - how to assign value with indices in different dimensions?
<p>Suppose I have a matrix and some indices</p> <pre><code>a = np.array([[1, 2, 3], [4, 5, 6]]) a_indices = np.array([[0,2], [1,2]]) </code></pre> <p>Is there any efficient way to achieve following operation?</p> <pre><code>for i in range(2): a[i, a_indices[i]] = 100 # a: np.array([[100, 2, 100], [4, 100, 100]]...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.put_along_axis.html" rel="noreferrer"><code>np.put_along_axis</code></a> -</p> <pre><code>In [111]: np.put_along_axis(a,a_indices,100,axis=1) In [112]: a Out[112]: array([[100, 2, 100], [ 4, 100, 100]]) </code></pre> <p>Alternaytiv...
python|numpy|tensorflow|pytorch|tensor
7
7,560
59,714,814
Filter list based on another query result with JMESPath
<p>Having an object such as the one below:</p> <pre><code>{ "pick": "a", "elements": [ {"id": "a", "label": "First"}, {"id": "b", "label": "Second"} ] } </code></pre> <p>how can I retrieve the item in the <code>elements</code> list where <code>id</code> is equal to the value of <code>pick</code>?</p> <...
<p>Unfortunately, <em>JMESPath</em> does not allow to reference the parent element.</p> <p>To circumvent this limitation, in this simple case, you can:</p> <ul> <li>read the <em>pick</em> attribute in the first query,</li> <li>create the second query using the value just read,</li> <li>read the wanted content in the ...
python|pandas|jmespath
5
7,561
59,864,408
tensorflow:Your input ran out of data
<p>I am working on a seq2seq keras/tensorflow 2.0 model. Every time the user inputs something, my model prints the response perfectly fine. However on the last line of each response I get this:</p> <blockquote> <p>You: WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or ...
<p>To make sure that you have &quot;<em>at least <code>steps_per_epoch * epochs</code> batches</em>&quot;, set the <code>steps_per_epoch</code> to</p> <pre><code>steps_per_epoch = len(X_train)//batch_size validation_steps = len(X_test)//batch_size # if you have validation data </code></pre> <p>You can see the maximum...
python|tensorflow|machine-learning|keras|deep-learning
24
7,562
61,693,503
How do groupby elements in pandas based on consecutive row values
<p>I have a dataframe as below :</p> <pre><code> distance_along_path 0 0 1 2.2 2 4.5 3 7.0 4 0 5 3.0 6 5.0 7 0 8 2.0 9 5.0 10 7.0 </code></pre> <p>I want be able to group these by the distance_along_path values, every time a 0 is seen a new group is c...
<p>You can try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>eq</code></a> followed by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>cumcun</code></a>: </p> <pre...
python|pandas|pandas-groupby
1
7,563
62,003,143
Delete specific numbers characters from Excel cell counting backwards
<p>I have an Excel sheet where my column B has following combination of words and letters</p> <p>(Name Lastname 3to4Numbers PM/AM Month date Year)</p> <p>Example:</p> <ul> <li>Kevin Hart 206PM May 16 2020</li> <li>Michael B Jordan 0339AM May 06 2020</li> </ul> <p>I want to go in each cell in my B column and remove the ...
<p><strong>Edit</strong>: I realize you might now have it in pandas yet. If you don't, you do somethe like this:</p> <pre><code>import pandas as pd df = pd.read_csv('YOURFILE.CSV') </code></pre> <p>And then you run the line under the <code>#Solution</code> in the code below, change <code>col</code> to the name of you...
python|excel|pandas|numpy|dataframe
2
7,564
61,943,386
How to assign smaller array to larger in overlapping area
<p>I'm trying to put a small 8x7 2D array, inside an 8x8 2D array.</p> <p>Here's what I'm working with:</p> <pre><code>--&gt; Array called 'a' with shape 8x7 a = [[ 16., 11., 10., 16., 24., 40., 51.], [ 12., 12., 14., 19., 26., 58., 60.], [ 14., 13., 16., 24., 40., 57., 69.], [ 14., ...
<p>You can just slice assign to <code>b</code> up to the dimensions of <code>a</code>:</p> <pre><code>x, y = a.shape b[:x, :y] = a </code></pre> <hr> <pre><code>print(b) array([[ 16., 11., 10., 16., 24., 40., 51., 0.], [ 12., 12., 14., 19., 26., 58., 60., 0.], [ 14., 13., 16., 24., ...
python|arrays|numpy|indexing|numpy-ndarray
2
7,565
61,637,020
Problem when importing json to dataframe with pandas
<p>I'm trying to import a .json file with pandas.read_json(), but it imports the file as one single line and column.</p> <p>The structure of the json file is like this:</p> <pre><code>{ "DataList": [ [ { "parameter": 12345, "parmeter 2": 56789, "DataSet": [ {"Data": "data", "Time": "date"} , {...}, {...} ], [ { "para...
<p>No problem still it can work fine</p>
python|json|pandas
0
7,566
58,030,812
Pandas - add a column with value computed based on another column value in current and previous row
<p>Given the dataframe below, </p> <pre><code>colNames = ["Time","Col2","Col3","Col4","Col5","Col6","Col7","Col8","Col9","Col10","Col11","Col12","Col13"] colVals = [['05:17:55.703', '', '', '', '', '', '21', '', '3', '89', '891', '11', ''], ['05:17:55.703', '', '', '', '', '', '21', '', '3', '217', '891', '12', ''], [...
<p>Can you try this?</p> <pre><code>df['col14']=df.Col11.gt(df.Col11.shift(-1)).cumsum() </code></pre> <p>or </p> <pre><code>df['col14a']=df.Col11.gt(df.Col11.shift(-1)).shift().fillna(0).cumsum().astype(int) </code></pre> <p>The difference between the two is that the count switches at the end of lower value (in th...
python|pandas|dataframe
2
7,567
58,007,325
How to merge list of lists with a tsv file in pandas
<p>I have a list of lists namely <code>mylist</code> as follows.</p> <pre><code>mylist = [[9, ["nuts", "fruits"]], [12, ["france", "italy", "rome", "paris"]], [18, ["cat", "dog", "parrot", "rabbit", "cow"]], [19, ["ebay", "wish"]]] </code></pre> <p>I also have a tsv file namely <code>myinput</code> as follows.</p> <...
<p>Use <code>map</code></p> <p><strong>Ex:</strong></p> <pre><code>mylist = [[9, ["nuts", "fruits"]], [12, ["france", "italy", "rome", "paris"]], [18, ["cat", "dog", "parrot", "rabbit", "cow"]], [19, ["ebay", "wish"]]] d = dict(mylist) df = pd.DataFrame({"ID": [12, 19, 18, 9], "Category": [["places...
pandas
2
7,568
54,703,473
TensorFlow why we still use tf.name_scope when we already have the function tf.variable_scope
<p>I do not understand why we also need the function <code>tf.name_scope</code> when we already have <code>tf.variable_scope</code>. From the Tensorflow official API, I see that the <code>tf.variable_scope</code> is more powerful because it can have an effect on <code>tf.get_variable</code>. When we create layers and w...
<p>You can use <code>tf.variable_scope</code> to add a prefix on <strong>both</strong> variables created with <code>tf.get_variable</code> and operations: as you said, this allows also variable sharing but it also makes the first call to <code>tf.get_variable</code> the definition of new variable under this scope.</p> ...
python|tensorflow
0
7,569
67,334,932
ValueError trying to remove elements from a pandas dataframe that are in a list
<p>I am trying to remove items from a pandas dataframe that have a value for column a that is part of a list.</p> <pre><code>import pandas as pd a = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'yz'] b = [1,2,3,2,1,1,3,2,1] df = pd.DataFrame(zip(a, b), columns = ['a', 'b']) print(df) verwijder = ['jkl', 'm...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>.isin()</code></a>. <code>not in</code> doesn't support operation on Series.</p> <pre class="lang-py prettyprint-override"><code>df = df[~df['a'].isin(verwijder)] </code></pre>
python|python-3.x|pandas|dataframe
3
7,570
67,495,172
Unable to remove rows from dataframe based on condition
<p>So i have a dataframe, df:</p> <pre><code> Rank Name Platform ... JP_Sales Other_Sales Global_Sales 0 1 Wii Sports Wii ... 3.77 8.46 82.74 1 2 ...
<p>First off, it's important to know why you're missing data, and to see if you can possibly impute rather than just drop.</p> <p>If you still want to drop, you can use <code>df = df.dropna(how='any')</code>.</p> <p>The reason why Excel shows &quot;N/A&quot; as the value for missing data is because that's Excel's way o...
python|pandas|dataframe
2
7,571
67,344,123
Get indexs and columns from a Dataframe that satisfy two conditions
<p>I'm new in Python and Pandas.</p> <p>I'm trying to filter a string dataframe by two conditions, to get a list or dataframe with indexs and columns that satisfy both conditions. I get this dataframe from a spreadsheet where each cell is YES or NOT.</p> <pre><code>df = pd.DataFrame([['YES', 'YES', 'NO', 'NO'], ['NO', ...
<p>You can use pandas' <code>melt</code> to convert the data frame to the long format, and then apply the condition</p> <pre><code>df_long = df.melt(value_vars=['David', 'Carol', 'Tony', 'Anna'], ignore_index=False).reset_index() df_long.columns = ['Task', 'Name', 'Value'] print(df_long) Task Name Value 0 task...
python|pandas|numpy
1
7,572
59,925,338
Is there a model.config file for tensorflow-serving to return all the models at the host
<p>I have followed the instruction of tensorflow serving and using docker could run 3 models by specifying their versions. But as the output at the host i get only the latest version of the model. Is there any model.config file that cna help display all three models at the host?</p>
<p>Figured it out!! This is how you can do it</p> <ol> <li><p>Include model_config file in the folder where the models are present</p> <pre><code> model_config_list: { config: { name: &quot;half_plus_three&quot;, base_path: &quot;/models/half_plus_three&quot; model_platform: &quot;tensorflow&quot;, ...
docker|tensorflow-serving
2
7,573
65,202,027
Convert large string with data frame like content into a data frame
<p>So I have a file which I can ope through Python read function, which returns one large string that essentially looks like a data frame, but is still a large string. So for example it could look something like this:</p> <pre><code>1609441 test.test1.test3 1/15.34 -1 100 622 669 160441 test.test1.test3 2/11.10...
<p>I tried with <code>read_csv</code> and this looked like it worked:</p> <pre><code>t = '''1609441 test.test1.test3 1/15.34 -1 100 622 669 160441 test.test1.test3 2/11.101 -1 100 140216 177363 16041 test2.test8.test6 2/15.34 -1 100 2791 2346 160441 test.test7.test5 2/15.34 1 100 Bin Any 5 ...
python|pandas|dataframe
1
7,574
65,211,176
How to rewrite the node ids that stored in .mtx file
<p>I have a <code>.mtx</code> file that looks like below:</p> <pre><code>0 435 1 0 544 1 1 344 1 2 410 1 2 471 1 </code></pre> <p>This matrix has shape of <code>(1000, 1000)</code>. As you can see, node ids starts at <code>0</code>. I want to change this to start at <code>1</code> instead of <code>0</code>. I...
<p>Why wouldn't you increment only the first column?</p> <pre><code>data[:, 0] += 1 </code></pre> <p>You may want to have a look at <a href="https://numpy.org/doc/stable/reference/arrays.indexing.html" rel="nofollow noreferrer">indexing in NumPy</a>.</p> <p>Additionally, I don't think the loop in your code ever worked:...
python|python-3.x|numpy
0
7,575
65,390,947
How to count rows based on multiple column conditions using pandas?
<p>How can I count csv file rows with pandas using <code>&amp;</code> and <code>or</code> condition?</p> <p>In the below code I want to count all rows that have True/False=FALSE and status = OK, and have '+' value in any of those columns openingSoon, underConstruction, comingSoon.</p> <p>I've tried:</p> <pre><code>chec...
<p>Use <code>|</code> for bitwise <code>or</code> and for count <code>True</code>s values filtering not necessary, use <code>sum</code>:</p> <p>Also for testing boolean <code>df['True/False'] == False</code> is possible simplify by <code>~df['True/False']</code></p> <pre><code>checkOne = (~df['True/False'] &amp; ...
python|pandas
3
7,576
65,387,643
Obtaining an empty plot when plotting cost vs epoch for a multivariate linear regression model
<p>I am leaning machine leaning and trying to implement Multivariate Linear Regression on a car price dataset to predict the price of cars in the future.</p> <p><a href="https://github.com/ua9612/JUPYTER/blob/main/car_price.csv" rel="nofollow noreferrer">Here is my dataset</a></p> <p><a href="https://github.com/ua9612/...
<p>Your data had 663 null values in total and hence the error,</p> <pre><code>data.isnull().values.sum() 663 </code></pre> <p>Did a mean imputation and replaced all NaNs.</p> <pre><code>data = data.fillna(data.mean()) data.isnull().values.sum() 0 </code></pre> <p>Then executed the remaining code,</p> <pre><code>alpha =...
python|pandas|numpy|machine-learning|linear-regression
0
7,577
64,132,973
multiple regex condition after certain character
<p>I would like to do regex that return boolean value if it matches. I want to extract characters <em>after</em> <code>@</code>. It could be a lot of character. For example I want to check if email using <code>banana</code> or <code>apple</code> domain. sample:</p> <p><code>df.head()</code></p> <pre><code>EMAIL data1@g...
<p>You can use <code>.str.contains</code> because <code>.str.match</code> only searches for a match at the start of a string (it is based on <code>re.match</code>). Also, <code>[^@]*</code> matches zero or more chars other than <code>@</code>, so it does not restrict matching <code>banana</code> or <code>apple</code> m...
python|regex|pandas|dataframe
2
7,578
63,897,642
How can words with misspellings be corrected in a data frame?
<p>I have a data frame and I want the wrong words to be edited in it. First i delete the characters that have been repeated more than twice in a word and then i apply Spell Correction on it. For the first part, I can only apply changes on strings. I want to be able to apply it to the data frame as well. How can I do th...
<p>If you have do it with <code>apply</code> function like below</p> <pre><code>df[&quot;Text&quot;] = df[&quot;Text&quot;].apply(reduce_lengthening) </code></pre> <p>or before adding this column ( <code>using </code>df['Text']=text<code>),you can pass each text element to </code>reduce_lengthening` in list comprehensi...
python|pandas
1
7,579
63,885,517
How to replace whole cell in pandas, with values from other dataframe and rest to be set as 1?
<p>I have a two DataFrames. df1:</p> <pre><code>A | B | C -----|---------|---------| 25zx | b(50gh) | | 50tr | a(70lc) | c(50gh) | </code></pre> <p>df2:</p> <pre><code> A | B -----|----- b | 1.2 a | 3.5 c | 6 </code></pre> <p>I want to replace values in df1. The row that I'm comparing i...
<p>Use the <code>regex</code> with <code>replace</code> then <code>apply</code> <code>to_numeric</code> follow by <code>fillna</code></p> <pre><code>df3 = df1.replace(df2.set_index('A').B,regex=True) df3 = df3.apply(pd.to_numeric,errors='coerce').fillna(1) df3 Out[123]: A B C 0 1.0 1.2 1.0 1 1.0 3.5 6...
python|pandas|dataframe
3
7,580
64,135,228
numpy 2d: How to get the index of the max element in the first column for only the allowed value in the second column
<p>Help find a high-performance way to solve the problem: I have a result after neural-network(answers_weight), a category for answers(same len) and allowed categories for current request:</p> <pre><code>answers_weight = np.asarray([0.9, 3.8, 3, 0.6, 0.7, 0.99]) # ~3kk items answers_category = [1, 2, 1, 5, 3, 1] # same...
<p>The easiest way would be to use numpy's masked_arrays to mask your weights according to allowed_categories and then find <code>argmax</code>:</p> <pre><code>np.ma.masked_where(~np.isin(answers_category,categories_allowed1),answers_weight).argmax() #2 </code></pre> <p>Another way of doing it using masks (this one ass...
python|arrays|numpy|max|masked-array
3
7,581
64,062,297
I just need tensorflow function equivalent to cv2.threshold nad np.std to use in tensorflow 1.8
<pre><code> I need to convert the following line into its tensorflow equivalent in tf version 1.8 but I am not getting the appropriate functions equivalent to cv2.threshold and np.std in TF 1.8 ret,mask = cv2.threshold(mask,tf.reduce_mean(mask)+1.2*np.std(mask),255,cv2.THRESH_BINARY) </code></pre> <p>The output of ...
<p>You can do that like this:</p> <pre class="lang-py prettyprint-override"><code>thr = tf.math.reduce_mean(mask) + 1.2 * tf.math.reduce_std(mask) mask = tf.cast(mask &gt; thr, tf.uint8) * 255 </code></pre>
tensorflow
0
7,582
46,673,882
Tensorflow tf.squared_difference outputs unexpected shape
<p>Newbie here, I am sorry if this question is silly but I couldn't find anything about it online. I am getting an unexpected shape for the output of <code>tf.squared_difference</code>. I would expect the obtain of a Tensor with <code>shape=(100, ?)</code> shape as the loss from the following snippet</p> <pre><code>[p...
<p>There's a slight difference between your first example (with <code>logits</code> and <code>labels</code>) and second example (with <code>myTESTX</code> and <code>myTESTY</code>). <code>logits</code> has the same shape as <code>myTESTY</code>: <code>(100, 1)</code>. However, <code>labels</code> has shape <code>(100,)...
python|machine-learning|tensorflow|deep-learning
2
7,583
46,835,607
Pandas apply works on individual columns as expected, but not entire dataframe
<p>I have a dataframe that looks something like this:</p> <pre><code>pd.DataFrame({'state':['AL','AL'],'statefp':[1.0,1.0]}) state statefp 0 AL 1.0 1 AL 1.0 </code></pre> <p>I want to turn the entire dataframe into type str and am using the <code>.apply</code> method. What I want to do is if the it...
<p>Try using dtype instead:</p> <pre><code>df.apply(lambda x: x.astype(int).astype(str) if x.dtype==np.float else x.astype(str).str.lower()) </code></pre> <p>Output:</p> <pre><code> state statefp 0 al 1 1 al 1 df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 2 entries, 0 to 1...
python|pandas|apply
0
7,584
46,784,822
Low-pass Chebyshev type-I filter with Scipy
<p>I am reading a paper, trying to reproduce the results of the paper. In this paper, they use a low-pass Chebyshev type-I filter on the raw data. And they give those parameters. </p> <p>Sampling frequency = 32Hz, Fcut=0.25Hz, Apass = 0.001dB, Astop = -100dB, Fstop = 2Hz, Order of the filter = 5. I found some material...
<p>Take a look at <a href="https://en.wikipedia.org/wiki/Chebyshev_filter#Type_I_Chebyshev_filters" rel="nofollow noreferrer">the wikipedia page on the Type I Chebyshev filter</a>. Note that your plot illustrates the characteristics of a general filter. A lowpass Type I Chebyshev filter, however, has no ripple in the...
numpy|filter|scipy|signal-processing|data-processing
4
7,585
63,028,927
Creating Orange table from numpy array
<p>I am trying to create an Orange table manually and am having some issues.</p> <p>My code:</p> <pre><code>new_domain = Domain([ ContinuousVariable(&quot;NAME&quot;), ContinuousVariable(&quot;AGE&quot;), DiscreteVariable(&quot;BLOOD TYPE&quot;, list([&quot;A+&quot;, &quot;A-&quot;, &quot;B+&quot;, &quot;B-...
<p>The error message is telling you everything you need to know:</p> <blockquote> <p>ValueError: could not convert string to float: 'Joe'</p> </blockquote> <p>The problem is that numpy arrays can <em>only</em> contain floating point (numeric) values inside of them. Here, you are tying to include non-numeric (string) va...
numpy-ndarray|orange
1
7,586
62,938,291
How can I access the data generated by autocorrelation_plot?
<p>I plotted the autocorrelation line using the function <code>autocorrelation_plot</code> in Pandas and would like to access the data it generates.</p> <p>I am basically trying to find out (locate) the lag points in my dataset.</p> <p>How can this be achieved?</p> <p><a href="https://i.stack.imgur.com/vgU9u.png" rel="...
<p>The following should work:</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd import numpy as np data = np.array(range(5)) * 10 ax = pd.plotting.autocorrelation_plot(data) </code></pre> <p><a href="https://i.stack.imgur.com/XnDs3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xn...
python|pandas|plot
0
7,587
63,238,061
Reading excel file with pandas and printing it for inserting it in http GET statement for Rest-API
<p>I want to read each line of an excel file (.xlsx-file) in the column called 'ABC'. There are 4667 lines and each line there is a string. I want to print each string. But it does not work.</p> <pre><code>import requests import pandas as pd get_all_ABC = pd.read_excel('C:\Users\XXX\XXX2\XXX3\table.xlsx', header = 0)...
<p>Why are you using the requests library? That is for making HTTP requests. Also, it's almost always bad practice to iterate over rows in pandas, and 99% of the time unnecessary.</p> <p>Also, <code>r.text</code> will be undefined as it's outside of the for loop scope.</p> <p>Could you explain exactly what you're tryin...
python|excel|pandas|python-requests|rest
1
7,588
63,078,749
How to fill a time series that's missing data but only when the gap is smaller than a certain number?
<p>Good afternoon,</p> <p>I'm working on pre-processing data that's streaming from sensors and which normally comes in every second (1hz). However this is not always the case, there are instances when there is gaps of data of 2s, 3s and even more.</p> <p>I'm trying to set up some code that fills these gaps but only whe...
<p>without the 10s missing window, it is something with <code>resample</code> and <code>interpolate</code>.</p> <pre><code>df.set_index('Timestamp').resample('s').interpolate().reset_index() </code></pre> <p>To add the filling only when less than 10s missing, then you can use <code>groupby</code> and get a new group wh...
python|pandas|time-series
1
7,589
67,698,119
How to create multiple triangles based on given number of simulations?
<p>Below is my code:</p> <pre><code>triangle = cl.load_sample('genins') # Use bootstrap sampler to get resampled triangles bootstrapdataframe = cl.BootstrapODPSample(n_sims=4, random_state=42).fit(triangle).resampled_triangles_ #converting to dataframe resampledtriangledf = bootstrapdataframe.to_frame() print(resampl...
<p>Try:</p> <pre><code>df['sample_size'] = pd.to_numeric(df['sample_size'].str.replace(',','')) df.pivot_table('sample_size','year', 'no', aggfunc='first')\ .pipe(lambda x: pd.concat([x,x.sum().to_frame('Grand Total').T])) </code></pre> <p>Output:</p> <pre><code>no 12 24 36 ...
python|pandas|dataframe|numpy
2
7,590
67,678,256
Match between two dataframes and add result to the column of one of them (Pandas)
<p>I have the following dataframes:</p> <pre><code>df = pd.DataFrame({'user': ['A', 'B', 'C'], 'results': ['hi how why', 'which how raw', 'final what is']}) df_v2 = pd.DataFrame({'user': ['A', 'B', 'C'], 'results': ['John', 'Peter', 'Anne']}) </code></pre> <p>What I have to do ...
<p>You can use the <code>set_index</code> method to tell <code>pandas</code> how to align dataframes when performing operations like addition, subtraction, etc.</p> <pre><code>new_series = df.set_index(&quot;user&quot;)[&quot;results&quot;] + &quot; &quot; + df_v2.set_index(&quot;user&quot;)[&quot;results&quot;] print...
python|pandas|dataframe|nlp|match
0
7,591
67,952,600
Python categorize data in excel based on key words from another excel sheet
<p>I have two excel sheets, one has four different types of categories with keywords listed. I am using Python to find the keywords in the review data and match them to a category. I have tried using pandas and data frames to compare but I get errors like &quot;DataFrame objects are mutable, thus they cannot be hashed&...
<p>One approach would be to build a regular expression from the <code>cat</code> frame:</p> <pre><code>exp = '|'.join([rf'(?P&lt;{col}&gt;{&quot;|&quot;.join(cat[col].dropna())})' for col in cat]) </code></pre> <pre><code>(?P&lt;Service&gt;fast|slow)|(?P&lt;Experience&gt;bad|easy) </code></pre> <p>Alternatively replace...
python|excel|pandas|dataframe
0
7,592
67,971,213
Read several csv from another folder in python
<p>my python file in which I work is contained in the following path '/Users/pycar/Documents/Srett/Python/', In this same space I have a folder that contains 8 other folders that all contain a csv that I want to import via panda because it's a database, the problem is that most of the codes found do not work (It says t...
<p>If catalog <code>month</code> and subcatalogs hold solely csv files of interest, you might use <a href="https://docs.python.org/3/library/glob.html#glob.glob" rel="nofollow noreferrer">glob.glob</a>. Please prepare following script in same catalog in which <code>month</code> catalog is present, run it and write if i...
python|pandas|csv
2
7,593
67,972,661
Hugging Face: NameError: name 'sentences' is not defined
<p>I am following this tutorial here: <a href="https://huggingface.co/transformers/training.html" rel="nofollow noreferrer">https://huggingface.co/transformers/training.html</a> - though, I am coming across an error, and I think the tutorial is missing an import, but i do not know which.</p> <p>These are my current imp...
<p>This error is because you have not declared sentences. Now you need to access raw data using:</p> <pre><code>k = raw_datasets['train'] sentences = k['text'] </code></pre>
python|bert-language-model|huggingface-transformers|huggingface-tokenizers|huggingface-datasets
1
7,594
61,442,931
Matplotlib Animation plotting the same thing for every frame
<p>I am trying to recreate the animation in <a href="https://youtu.be/kbKtFN71Lfs" rel="nofollow noreferrer">this</a> video.</p> <p>Currently, my code plots, but each frame is the same frame as the last. I am trying to first plot the vertices, then plot each dot one at a time. The points are precalculated, so all I wa...
<p>It seems like you misunderstood how <a href="https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.animation.FuncAnimation.html" rel="nofollow noreferrer">matplotlib.animation.funcanimation</a> works, I'll strongly advise you to look at some of the many examples to be found online. Let's try with this version as follo...
python|numpy|matplotlib
1
7,595
68,851,524
Filter out the last available day of a quarter in the dataframe in which Quarter column is already present
<p>I want to get the row for the last available date in a Quarter in a pandas df. There's already a column denoting the Quarter of that particular year.</p> <pre><code> player amount date Quarter dan 10 2021-06-29 2Q21 dmitri 45 2021-06-30 2Q21 darren 15 2021-12-31 4Q21 xae12 40...
<p>You can use <code>pd.offsets.QuarterEnd</code>:</p> <pre><code># df[&quot;date&quot;] = pd.to_datetime(df[&quot;date&quot;]) print (df.loc[df[&quot;date&quot;] == (df[&quot;date&quot;]+pd.offsets.QuarterEnd(0))]) player amount date Quarter 1 dmitri 45 2021-06-30 2Q21 2 darren 15 2021-12-31...
python|pandas|dataframe|date|datetime
3
7,596
68,697,977
While working on building an image segmentation model I am facing a problem of getting dimensions not equal
<p>I am working on an image segmentation problem where training images=50 and testing images=51. I am facing an error where dimensions are not equal. Input_shape=(256,256,3) Model Code:</p> <pre><code>import tensorflow as tf from tensorflow.keras.layers import Conv2D, BatchNormalization, Activation, MaxPool2D, Conv2DTr...
<p>The error occurs at this line</p> <pre><code>x = Multiply()([init, se]) </code></pre> <p>The reason for the error is that <code>Multiply()</code> does an element-wise multiplication and hence the dimension of <code>init</code> and <code>se</code> should be same. In you case the <code>init</code> is a output of a <co...
python|tensorflow|deep-learning|conv-neural-network|image-segmentation
0
7,597
68,830,578
How to properly get all the data in excel from dataframe in google colab
<p>I have a dataframe in google colab when I print the dataframe this is the output I get:</p> <pre><code> 0 0 Aaron Burciaga 1 \nECS 2 \nVP Artificial Intelligence\n 3 Chanchal Chatterjee 4 \nGoogle, Inc...
<p>The problem comes from the <a href="https://stackoverflow.com/questions/31489377/working-of-n-in-python"><code>\n</code></a> at the beginning (of some) of your values. Just <a href="https://www.w3resource.com/pandas/series/series-str-strip.php" rel="nofollow noreferrer">strip</a> them.<sup>In case you haven't figure...
python|pandas|google-colaboratory
0
7,598
65,494,915
TypeError: f() takes 1 positional argument but 2 were given
<p>I can't figure out why i get the error message</p> <pre><code>TypeError TypeError: f() takes 1 positional argument but 2 were given </code></pre> <p>I have this code `</p> <pre><code>df_dur=user.groupby(['Date'], as_index=False).sum(['Duration']) df_dur=df_dur.duration print('DF Dura...
<p>I had the same error message, however I'm not sure this at all is relevant to your question. But maybe someone else will find it useful, I updated my pandas from 0.22 to 1.1 and it solved my problem (TypeError: f() takes 1 positional argument but 2 were given).</p> <blockquote> <p>pip install --upgrade pandas</p> </...
python|pandas
3
7,599
65,762,304
Getting very poor accuracy on stanford_dogs dataset
<p>I'm trying to train a model on the stanford_dogs dataset to classify 120 dog breeds but my code is acting strange.</p> <p>I downloaded the image data from <a href="http://vision.stanford.edu/aditya86/ImageNetDogs/images.tar" rel="nofollow noreferrer">http://vision.stanford.edu/aditya86/ImageNetDogs/images.tar</a></p...
<p>For validation data you should not do any image augmentation, just do rescale. In validation flow_from_directory set shuffle=False. Be advised that the Stanford Dog Data set is very difficult. To achieve a reasonable degree of accuracy you will need a much more complex model. I recommend you consider transfer learni...
python|python-3.x|tensorflow|neural-network|tensorflow2.0
1