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
357,100
71,131,163
check if column of strings contain a word in a list of string and extract the words in python
<p>I have a DataFrame, and a list of key words, how can I extract matched words from the Text in the DataFrame. Can anyone help? Thank you!</p> <p>** DataFrame**</p> <pre><code>df = pd.DataFrame({'ID':range(1,6), 'text':['red blue', 'bbb', 'rrrr blue', 'yyy b', 'ed yye']}) </code></pre> <p><a href="https://i.stack.imgu...
<p>Your code works fine. I think your issue is that you are getting wrong keyword pattern. Try adding <code>header=None</code> to the kword csv.</p> <pre><code>import pandas as pd keyword = &quot;np-match/keyword.csv&quot; kword = pd.read_csv(keyword, encoding_errors=&quot;ignore&quot;, header=None) Wrd_list = kword.va...
python|pandas|dataframe
0
357,101
71,256,083
How to get an image to array, Tensorflow 1.9
<p>So I have to use <em>Tensorflow 1.9</em> for system specific reasons. I want to train a cnn with a custom dataset consisting of images. The folder structure looks very much like this:</p> <pre><code>./ + circles - circle-0.jpg - circle-1.jpg - ... + hexagons - hexagon-0.jpg - hexagon-1.jpg ...
<p>You have to build a custom data generator for that. If you have two arrays, <code>train_paths</code> containing the paths to images and <code>train_labels</code> containing the labels for the images, then this function (<code>datagen</code>) would yield the images as array and with their respective label as a tuple ...
python|tensorflow|keras|deep-learning
2
357,102
71,234,348
Export DF to seperate .csv files based on column name
<p>I want to split a dataframe based on the column name and export it in seperate .csv files. How can i do this?</p> <pre><code>import pandas as pd from google.colab import files uploaded = files.upload() import io df1 = pd.read_csv(io.BytesIO(uploaded['Your Keywords Clustered.csv'])) df_list = [d for _, d in df1.group...
<p>If new filenames are henerated from names of groups use <code>for loop</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer"><code>DataFrame.to_csv</code></a>:</p> <pre><code>for name, d in df1.groupby(['Cluster_Name']): d.to_csv(f'...
python|pandas|google-colaboratory
0
357,103
71,342,915
Remap values in a Pandas column based on dictionary key/value pairs using RegEx in replace() function
<p>I have the following Pandas dataframe:</p> <pre><code>foo = { &quot;first_name&quot; : [&quot;John&quot;, &quot;Sally&quot;, &quot;Mark&quot;, &quot;Jane&quot;, &quot;Phil&quot;], &quot;last_name&quot; : [&quot;O'Connor&quot;, &quot;Jones P.&quot;, &quot;Williams&quot;, &quot;Connors&quot;, &quot;Lee&quot;],...
<p>One approach would be using <code>columns</code> attribute:</p> <pre class="lang-py prettyprint-override"><code>regex_patterns = { 'last_name' : '[^A-Za-z \/\-\.\']', 'first_name' : '[^A-Za-z \/\-\.\']', 'salary' : '[^0-9 ]' } for column in df.columns: df[column] = df[[column]].replace(regex_pattern[co...
python|regex|pandas
1
357,104
71,207,526
How to sort values in pivot table by values names
<p>Could you, please, help me with sorting the names of values?</p> <p>I have the code which forms the Table 1:</p> <pre><code>df1 = pd.pivot(data=df_selected, index='source', columns='ds', values=['y','percent_diff']) df1 = df1.swaplevel(0,1, axis=1).sort_index(axis=1, ascending=False)#.reset_index() df1 = df1.sort_va...
<p>Use <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_product([pd.date_range('2022-01-01', periods=3), ['y','rolling', 'percent_diff'...
python|pandas|sorting|pivot|pivot-table
0
357,105
71,332,132
Columns names of top n values of each row in a pandas DataFrame
<pre><code>Data: d = {'a': [1,5], 'b': [2,4], 'c': [3,3], 'd':[4,2], 'e': [5,1]} df = pd.DataFrame(d) </code></pre> <p>Desired Output:</p> <pre><code>d2 = {'a': [1,5], 'b': [2,4], 'c': [3,3], 'd':[4,2], 'e': [5,1], 'Top (First)': ['e','a'], 'Top (Second)': ['d','b'], 'Top (Third)': ['c','c']} df2 = pd.DataFrame(d2) </c...
<p>You could use <code>nlargest</code> to find the 3 largest values, then get the index of the largest values (which are column names since we apply <code>nlargest</code> row-wise) and build DataFrame and <code>join</code> it back to <code>df</code>:</p> <pre><code>df2 = df.join(pd.DataFrame(df.apply(lambda x: x.nlarge...
python|pandas|dataframe
2
357,106
71,321,705
Efficient way to manipulate values of a pandas dataframe
<p>I am dealing with 2 huge dataframes and I need to perform a specific operation to retrieve the most frequent value of one of the two dataframe for each unique id in the first one. I will explain it better with an example.</p> <p>Suppose I have to dataframes, the first one will be called <code>df_id</code>, the secon...
<p>My suggestion:</p> <ol> <li><p>Find most frequent value in df_values, grouped by ids. If there is more than one most frequent value, take the first one:</p> <pre><code>most_freq = df_values.groupby('ids').agg(lambda x: pd.Series.mode(x)[0])['values'].to_dict() </code></pre> </li> <li><p>Create a dictionary from ids ...
python|pandas|dataframe|numpy|multiprocessing
1
357,107
71,215,358
TypeError: <tf.Tensor ... has type <class 'tensorflow.python.framework.ops.EagerTensor'>, but expected one of: numbers.Real
<p>I am writing a function to save images to TFRecord files in order to then read then using the Data API of TensorFlow. However, when trying to create a TFRecord to save it, I receive the following error message:</p> <pre><code>TypeError: &lt;tf.Tensor ...&gt; has type &lt;class 'tensorflow.python.framework.ops.EagerT...
<p>The problem is that <code>image</code> is a tensor but you need a list of float values. Try something like this:</p> <pre><code>import tensorflow as tf def create_tfrecord(filepath, label): image = tf.io.read_file(filepath) image = tf.image.decode_jpeg(image, channels=1) image = tf.image.convert_im...
python|image-processing|tensorflow2.0|tensorflow-datasets
1
357,108
71,383,926
export a comma-separated string as a text file without auto-formatting it as a CSV
<p>Im developing an API which should, ideally, export a conmma-separated list as a .txt file which should look like</p> <p><code>alphanumeric1, alphanumeric2, alphanumeric3</code></p> <p>the data to be exported is coming from a column of a pandas dataframe, so I guess I get it, but all my attempts to get it as a single...
<p>I am not sure if what you need is:</p> <pre><code>csvList = ','.join(df.ColumnHeader) </code></pre> <p>where, df is of course your pandas dataframe</p>
python|pandas|io
1
357,109
71,093,075
"Thousands" and " skip_blank_lines" arguments of pandas.read_csv would not work properly. Why?
<p>This my code:</p> <pre><code>in[0] import pandas as pd df = pd.read_csv('datefile6.csv',thousands=',', skip_blank_lines=True) df out[1] month day year salary age 0 8.0 15.0 2012.0 1400.0 25.0 1 NaN NaN NaN NaN NaN 2 9.0 4...
<p><code>thousands</code> parameter is a property of the input file. It tells pandas that numbers in your csv file contain thousands character (typically comma or dot). Parameter thousands does not impact the output.</p> <p>Consider this code:</p> <pre><code>import pandas as pd df = pd.read_csv('datafile6.csv', sep=';'...
python|pandas|read.csv
1
357,110
71,338,674
Evenly distribute samples within a dataframe
<p>I have a dataframe with 2 columns:</p> <ol> <li>employee_num (from 0 to 4999)</li> <li>risk, which only has 3 values - high, med and low. They are randomly distributed between the dataframe.</li> </ol> <p>I need to add a third column, called checker, which has 5 values - 1,2,4,6,8. Those checkers need to be evenly d...
<p>We can <code>groupby</code> by risk and then cycle through 0..4 in each group mapping to the 'checker' values:</p> <pre><code>cm = {0:1,1:2,2:4,3:6,4:8} workers['checker'] = (workers.groupby('risk').cumcount()%5).map(cm) </code></pre> <p><code>workers</code> looks like this:</p> <pre><code> employee_num risk ...
python|pandas|dataframe
0
357,111
71,222,184
AttributeError: 'DataFrame' object has no attribute 'convert_to_tensor'
<p>I am trying to train a model with <code>keras</code> and the data I am feeding it is of the following type. I hae a dataframe with input an input vector called <code>Fingerprint</code> and an ouput vector called <code>position</code>. For reference<code>Fingerprint</code> are recieved signal intensities from individ...
<p>For some reason your X_train is composed of lists, it's not an array.</p> <p>You must make it a single array. If all lists have the same size, you should be able to make something like</p> <pre><code>X_train = numpy.array([obj[0] for obj in X_train]) </code></pre> <p>Make sure the shape is 2D with <code>X_train....
pandas|numpy|keras
1
357,112
71,397,934
Multithread and AttributeError: 'NoneType' object has no attribute 'groups'
<p>We wrote this code in order to plot the data conteined in a txt file:</p> <pre><code>import pandas as pd import plotly.express as px import matplotlib.pyplot as plt import re import numpy as np import os names = ['CH','LG','HG','Ts(ns)','ToT(ns)'] righe_primo_header = 5 righe_header = 5 canali = 64 # input file in...
<p>I resolve the firt issue:</p> <pre><code>import pandas as pd import plotly.express as px import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as go import re import numpy as np import os names = ['CH','LG','HG','Ts(ns)','ToT(ns)'] righe_primo_header = 5 righe_header = 5 canali = 6...
pandas|multithreading|python-re
-1
357,113
71,244,042
Loop through excels and extract values in excel using pandas
<p>I am learning python while doing small automation and I need help here. I have excel files in folder and I need to read all excel files and look for specific text in excel and get value from a specific column if required text is found. I was able to read excel and get values but I think I am getting those values in ...
<p>I can't really follow your code (you should try using more expressive variable names, not only for others sake but also for you if you later want to understand or change parts of the code), but I assume that the problem is mainly because of the indexes.</p> <p>The way you construct this results in INDDEDIN and FAMDE...
python|pandas
1
357,114
71,191,874
Can't load dataframe columns by tf.data.Dataset.from_tensor_slices()
<p>I have a dataframe which consist of columns = id, Text, Media_location (which is relative path to images folder).</p> <p>Now, I'm trying to load the columns Text, Media_location like this:</p> <pre><code>features = df[['Text', 'Media_location']] dataset = tf.data.Dataset.from_tensor_slices((features)) </code></pre> ...
<p>If the columns <code>Text</code> and <code>Media_location</code> have the same data type your code will work:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import pandas as pd df = pd.DataFrame(data={'Text': ['some text', 'some more text'], 'Media_location': ['/...
python|dataframe|tensorflow|tensorflow-datasets
1
357,115
71,215,965
How to save checkpoints for thie transformer gpt2 to continue training?
<p>I am retraining the GPT2 language model, and am following this blog :</p> <p><a href="https://towardsdatascience.com/train-gpt-2-in-your-own-language-fc6ad4d60171" rel="nofollow noreferrer">https://towardsdatascience.com/train-gpt-2-in-your-own-language-fc6ad4d60171</a></p> <p>Here, they have trained a network on GP...
<pre><code>training_args = TrainingArguments( output_dir=model_checkpoint, # other hyper-params ) trainer = Trainer( model=model, args=training_args, train_dataset=train_set, eval_dataset=dev_set, tokenizer=tokenizer ) trainer.train() # Save the model to model_dir trainer.save_model() def...
tensorflow|nlp|gpt-2
1
357,116
71,362,729
Quantized model gives negative accuracy after conversion from pytorch to ONNX
<p>I'm trying to train a quantize model in pytorch and convert it to ONNX. I employ the quantized-aware-training technique with help of pytorch_quantization package. I used the below code to convert my model to ONNX:</p> <pre><code>from pytorch_quantization import nn as quant_nn from pytorch_quantization import calib f...
<p>After some tries, I found that there is a version conflict. I changed the versions accordingly:</p> <pre><code>onnx == 1.9.0 onnxruntime == 1.8.1 pytorch == 1.9.0+cu111 torchvision == 0.10.0+cu111 </code></pre>
pytorch|onnx|quantization-aware-training
0
357,117
71,435,264
How can I convert Tensor to eagerTensor
<p>I got tensor class from <code>Model.pred()</code> that tensor class is <code>&lt;tf.python.framework.ops.Tensor&gt;</code> (not eager).</p> <p>but I can't use them for custom loss function. So I tried convert 'that Tensor' to <code>&lt;tf.python.framework.ops.EagerTensor&gt;</code>.</p> <p>If I convert them I can us...
<p>You can either:</p> <ol> <li><p>Try forcing eager execution with <code>tf.config.run_functions_eagerly(True)</code> or <code>tf.compat.v1.enable_eager_execution()</code> at the start of your code.</p> </li> <li><p>Or using a session (<a href="https://www.tensorflow.org/api_docs/python/tf/compat/v1/Session" rel="nofo...
numpy|tensorflow2.0|tensor
0
357,118
71,356,555
pandas profiling with dask-dataframe. IndexError
<p>I get an IndexError (<code>IndexError: only integers, slices (:), ellipsis, nmpy.newaxis and integer or bolean arays are valid indices</code>) while pandas profiling with dask. data: 290170 x 55</p> <pre><code>import dask.dataframe as dd from pandas_profiling import ProfileReport df = dd.read_csv(&quot;covtype.data&...
<p><em>Quick fix</em>: following <a href="https://github.com/ydataai/pandas-profiling/issues/911" rel="nofollow noreferrer">Issue #991</a>, you can change line <strong>#13</strong> in <code>utils_pandas.py</code>, just like <a href="https://github.com/ieaves" rel="nofollow noreferrer">ieaves</a> suggested.</p> <p>From:...
python|index-error|dask-dataframe|pandas-profiling|eda
0
357,119
71,414,550
create a dictionary value key from dataframe
<p>I have a dataframe :</p> <pre><code>PageId OSBrowser 1005581 (11, 16) 1016529 (11, 16) 1016529 (11, 17) 1016529 (12, 14) 1016529 (12, 16) </code></pre> <p>I am trying to create a dictionary dico : where the key is the OSBrowser value and PageID are the list for each key value :</p> <p>So the...
<p>You should use <code>df.index</code> to traverse through the dataframe</p> <pre><code>d = {} for ind in data.index: page_id = data[&quot;PageId&quot;][ind] os_browser = data[&quot;OSBrowser&quot;][ind] if os_browser not in d: d[os_browser] = [page_id] else: d[os_browser].append(page_i...
python|python-3.x|pandas|dataframe|dictionary
2
357,120
71,388,965
Read Excel file in AWS
<p>I wanted to read an excel file in S3 from Glue.</p> <p>Here's what I've done so far.</p> <pre><code>import pandas as pd import awswrangler as wr import io ad_request_path = 's3://bucketname/key.xlsx' df = wr.s3.read_excel(ad_request_path) </code></pre> <p>OR</p> <pre><code>bucket_name = 'bucketname' object_key = 'k...
<p>Managed to make it work. Just add <code>engine = 'openpyxl'</code></p> <pre><code>import awswrangler as wr import openpyxl ad_request_path = 's3://bucketname/key.xlsx' df = wr.s3.read_excel(ad_request_path, engine='openpyxl') </code></pre>
python|pandas|amazon-web-services|amazon-s3
2
357,121
71,308,111
Accessing element index in a matrix
<p>I want to save the index of an element in a matrix as following</p> <pre class="lang-py prettyprint-override"><code>cx = [] for j in range(len(self.correctors_indexes)): self.lattice[self.correctors_indexes[j]].KickAngle = [self.dkick, 0.00] lindata0, tune, chrom, lindata = self.lattice.linopt(get_chrom=Tru...
<p>You may use the function <a href="https://numpy.org/devdocs/reference/generated/numpy.argwhere.html" rel="nofollow noreferrer"><code>np.argwhere</code></a> to get the indices of a value within an array or a matrix and later use these values for a filename. See the following example:</p> <pre class="lang-py prettypri...
python|numpy|matrix
1
357,122
71,110,210
Pandas data manipulation with date
<p>I have two df, I want to manipulation the one on the basis of other. My df1 looks like this date format is mm-dd-yyyy</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Date</th> <th style="text-align: center;">col_1</th> <th style="text-align: center;">col_2</th> ...
<p>IIUC, use <code>Date</code> column as index of both dataframes then apply your operation:</p> <pre><code>df2['col_3'] = df2.set_index('Date')['col_2'] \ .mul(df1.set_index('Date').reindex(df2['Date'])['col_3']).values print(df2) # Output Date col_1 col_2 col_3 0 01/01/2021 A 110...
python|pandas|dataframe|date|data-manipulation
1
357,123
71,251,749
Python/Pandas: How to find rows that are duplicated in two df columns?
<p>I have a df where I want to check for duplicate rows in only two of the columns, but if those columns are similar to the previous row, then I'd like to isolate/print them. So for example, if rows 12 - 89 have the same value in column 2 and column 3 as the previous row(s), then I want to know this range of rows.</p> ...
<p>Try <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer">the dataframe's duplicated function</a>. This returns an index that you can use to slice/select those rows. Some variation of this will get you close:</p> <pre><code>dup_rows = df.duplicated(subset...
python|pandas|duplicates
0
357,124
71,368,770
how to strip customized missing value pandas dataframe
<br> I have a dataset with a customized missing values which is the character `\?` but a cell with the missing value also contains whitespaces with inconsistent number of space characters. As in my example picture, at row 11, It could have 3 spaces, or 4 spaces. <p>So my idea is to apply the <code>str.strip()</code> fu...
<p><code>dropna</code> drops NaN values. Since your NaNs are actually <code>?</code>, you could <code>replace</code> them with NaN and use <code>dropna</code>:</p> <pre><code>df = df.replace('?', np.nan).dropna() </code></pre> <p><code>mask</code> them and use <code>dropna</code>:</p> <pre><code>df = df.mask(df.eq('?')...
python|pandas|dataframe|missing-data
1
357,125
71,151,461
JSON normalize pandas column without losing index
<p>I've got a dataframe as in the image:</p> <p><a href="https://i.stack.imgur.com/qokIR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qokIR.png" alt="enter image description here" /></a></p> <p>I'd like to transform that into a dataframe similar to the following:</p> <p><a href="https://i.stack.im...
<p>try <code>pd.json_normalize(df['card_fields']).set_index(df.index)</code>? df is the dataframe from image 1.</p>
python|json|pandas
1
357,126
71,175,620
Cleaning Google TPU memory (python)
<p>My python code has two steps. In each step, I train a neural network (primarily using <code>from mesh_transformer.transformer_shard import CausalTransformer</code> and delete the network before the next step that I train another network with the same function. The problem is that in some cases, I receive this error:...
<p>Unfortunately, you can’t clean the TPU memory, but you can reduce memory usage by these options;</p> <p>The most effective ways to reduce memory usage are to:</p> <blockquote> <p>Reduce excessive tensor padding</p> </blockquote> <p>Tensors in TPU memory are padded, that is, the TPU rounds up the sizes of tensors sto...
python|tensorflow|google-cloud-platform|huggingface-transformers|tpu
1
357,127
71,319,104
Is there a way to send the pixel information of a very big sized picture to multiple excel files using python?
<p>I was trying to send the pixel information of a picture to an excel file. But I was constantly getting the size errors. So I tried to make several excel files to copy the information. But now I am getting this error:</p> <pre><code>TypeError Traceback (most recent call last) &lt;ipyth...
<p>I suppose, you've read your image into a numpy array: <code>img</code>.</p> <p>After that, you converted <code>img</code> to a DataFrame, <code>df</code> in the line:</p> <pre><code>df=pd.DataFrame(img.flatten()) </code></pre> <p>The error is raised because you're trying to call <code>df</code> with a slice of the o...
python|excel|pandas|dataframe
0
357,128
71,425,837
Compare df's including detailed insight in data
<p>I'm having a python project:</p> <p>df_testR with columns={'Name', 'City','Licence', 'Amount'}</p> <p>df_testF with columns={'Name', 'City','Licence', 'Amount'}</p> <p>I want to compare both df's. Result should be a df, wehere I see the Name, City and Licence and the Amount. Normally, df_testR and df_testF should be...
<pre><code>import copy import pandas as pd data1 = {'Name': ['A', 'B', 'C'], 'City': ['SF', 'LA', 'NY'], 'Licence': ['YES', 'NO', 'NO'], 'Amount': [100, 200, 300]} data2 = copy.deepcopy(data1) data2.update({'Amount': [500, 200, 300]}) df1 = pd.DataFrame(data1) df2 = pd.DataFrame(data2) df2.drop(1, inplace=True) </code...
python|pandas|dataframe|comparison
0
357,129
71,146,343
Pandas for each new value in a column, remove the following two rows
<p>I have the following dataframe:</p> <pre><code>time alarm 0 0 1 1 2 0 3 1 4 1 5 1 6 1 7 0 8 0 9 1 10 0 </code></pre> <p>The column <code>alarm</code> represents an alarm. If it rings, it takes value 1. <br /> Each time the alarm rings, I want to &quo...
<p>I think you can not avoid the for-loop in this problem but you can certainly optimize the function and then compile it using numba to achieve C like speed on large datasets</p> <pre><code>from numba import njit @njit def silence(alarm): count = 0 for a in alarm: if count &gt; 0: yield Tr...
python|pandas|dataframe|numpy|fillna
1
357,130
71,214,405
Faster RCNN Bounding Box Coordinate
<p>I trained a model using Faster RCNN, this model is used to follow the strips.</p> <p><a href="https://i.stack.imgur.com/2hwDP.jpg" rel="nofollow noreferrer">here is the output of my model</a></p> <p>The python code I use to get this output is as follows:</p> <pre><code>import cv2 import numpy as np import tensorflow...
<p>You need to apply nms and denormalize the boxes.</p> <pre><code>def apply_non_max_suppression(boxes, scores, iou_thresh=.45, top_k=200): &quot;&quot;&quot;Apply non maximum suppression. # Arguments boxes: Numpy array, box coordinates of shape (num_boxes, 4) where each columns corresponds ...
tensorflow|image-processing|computer-vision|object-detection|faster-rcnn
1
357,131
71,378,244
Applying KNN Clustering based on user id
<p>Dataset file : <a href="https://drive.google.com/file/d/1UuWMK1XH52mU4L6hoI1vhR8RVdF_fxgO/view?usp=sharing" rel="nofollow noreferrer">google drive link</a></p> <p>Hello Community , I need help regarding how to apply <strong>KNN</strong> clustering on this use case.</p> <p>I have a dataset consisting <code>(27884 ROW...
<p>Since you don't have class labels in your data, I'm guessing <a href="https://pythonprogramminglanguage.com/how-is-the-k-nearest-neighbor-algorithm-different-from-k-means-clustering/#:%7E:text=KNN%20represents%20a%20supervised%20classification,into%20k%20number%20of%20clusters." rel="nofollow noreferrer">you may wan...
python|pandas|numpy|knn
1
357,132
71,384,685
Iterating through pandas dataframe and appending a dictionary?
<p>I am trying to transition from excel to python, and for practice I would like to analyze sports data from the NFL season. I have created a pandas dataframe with the data I would like to track, but I was wondering how I can go through the data and create a dictionary with each teams wins and loses. I thought that I c...
<p>The more pandas way of doing this is to create a new data frame indexed by team with columns for wins and losses. The <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">groupby</a> method can help with this. You can group the rows of your dataframe by team ...
pandas|dataframe
2
357,133
71,392,971
Torchscript call other function rather than forward
<p>When I compile my torch model to torchscript I can make use of the function <code>forward</code> by just calling the torchscript model object <code>model()</code>.</p> <p>But when I want to use another function created on the model I cant call the function. I try to do <code>model.functionName()</code> expecting to ...
<p>I suppose you should add <a href="https://pytorch.org/docs/stable/jit.html#torch.jit.export" rel="nofollow noreferrer">decorator</a> <code>@torch.jit.export</code> above the method you want to call and convert torchscript model again. After that you can call method by <code>module.run_method(name, args)</code> <a hr...
pytorch|torch|torchscript
0
357,134
71,433,793
Using Numpy.NET NuGet package in C# class library making .exe file too big
<p>I'm using Numpy.NET NuGet package in C# class library and it's making .exe files on release build too big (from ~10 to ~30 MB). What is the exact reason for that and is there any solution to this problem?</p> <p>I used ILDASM to get stats of .exe file and this is what it showed:</p> <pre><code> File size ...
<p>Turns out the issue was in <strong>.csproj</strong> file. It has following lines, that embeds all .dll's on &quot;AfterResolveReferences&quot; event (don't know if it's VS default settings or previous dev's did this on purpouse).</p> <pre><code>&lt;Target Name=&quot;AfterResolveReferences&quot;&gt; &lt;ItemGroup...
c#|.net|wpf|numpy
1
357,135
71,400,056
Convert a string into a number in Pandas
<p>I am having trouble solving one assignment. Well, in a dataframe in one column I have values as text strings (objects). I want to convert this to a numeric value but every time I get an error that I cannot convert the string to a float. I want to try using regex to convert the string '-1 203.45' into the value '1203...
<p>First what I did:</p> <ol> <li><p>Read the file csv in different way:</p> <p>df = pd.read_csv('dane_navision.csv', delimiter=&quot;;&quot;, decimal= &quot;,&quot;, thousands=&quot; &quot; )</p> </li> </ol> <p>and</p> <pre><code>df = pd.read_table('dane_navision.csv', delimiter=&quot;;&quot;, thousands=&quot; &quot;,...
python|regex|pandas
-1
357,136
71,352,354
sklearn KMeans is not working as I only get 'NoneType' object has no attribute 'split' on nonEmpty Array
<p>I don't know what is wrong but suddenly <code>KMeans</code> from <code>sklearn</code> is not working anymore and I don't know what I am doing wrong. Has anyone encountered this problem yet or knows how I can fix it?</p> <pre class="lang-python prettyprint-override"><code>from sklearn.cluster import KMeans kmeanMode...
<p><strong>Upgrade <code>threadpoolctl</code> to version &gt;3.</strong></p> <p>This works for all versions of <code>numpy</code>.</p>
python|numpy|scikit-learn|jupyter-notebook
9
357,137
52,176,478
How to check if value exists in another dataframe in pandas?
<p>I have a dataframe below that contains mapping between french to english</p> <pre><code>df1 french english ksjks an sjk def ssad sdsd </code></pre> <p>And another dataframe columns are in french so need to convert them into english by using df1</p> <pre><code>df2 ksjks sjk ssad 2 4 6 </code></pre>...
<p><strong><em>Option 1</em></strong><br> Use <code>map</code> with <code>set_index</code></p> <pre><code>df2.columns = df2.columns.map(df1.set_index('french').english) print(df2) </code></pre> <p><strong><em>Option 2</em></strong><br> Use <code>rename</code> with <code>set_index</code>:</p> <pre><code>df2.rename(co...
python|pandas
2
357,138
52,396,237
Pandas - Returning a boolean if value is in between
<p>I have a pandas dataframe that I want to create a new column named df3['outlier'], that columnn would contain a boolean, if df3['Rolling_Rate'] is in between df3['LowerControl'] &amp; df3['UpperControl'] return False else True.</p> <p>Any help would be greatly appreciated.</p>
<p>No need to use <code>apply</code>:</p> <pre><code>df3['outlier'] = ~df3['Rolling_Rate'].between(df3['LowerControl'], df3['UpperControl']) </code></pre>
python-2.7|pandas
1
357,139
52,002,807
How do I solve this 'transpose' in Python?
<p>I am trying to do some kind of reverse transpose where the ID(ISIN) becomes duplicates, but where the feature 'Period' defines the time period and the value-features goes from 3 features to the same feature. How do I get from dfs to dfs2 in Python?</p> <pre><code>dfs = pd.DataFrame({ 'ISIN': [ 'A', 'B',...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow noreferrer"><code>pd.melt</code></a> to "unpivot" your dataframe and then use string slicing:</p> <pre><code>res = pd.melt(dfs, id_vars='ISIN', value_vars=dfs.columns[1:].tolist()) res['variable'] = res['vari...
python|pandas|numpy|reverse|transpose
1
357,140
52,178,248
Summing or groupby at different levels with MultiIndex columns?
<p>I have a dataframe where, to avoid tuple column names, I intentionally used blank levels:</p> <pre><code>&gt;&gt;&gt; df user1 user2 count 0 1 2 a a b a 0 2 6 0 1 0 0 1 4 6 0 0 0 3 ...
<p>First use <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers" rel="nofollow noreferrer">slicers</a> for filter only <code>1,2</code>, then <code>sum</code> and add levels for same levels like original <code>DataFrame</code> for possible use <a href="http://pandas.pydata.org/pandas-docs/...
pandas
1
357,141
52,053,091
Pandas cumcount() when np.nan exists
<p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame([[1, 2, np.nan], [1, np.nan, 3], [2, 2, 3], [3, 4, np.nan]]) </code></pre> <p>when I <code>groupby</code> all the 3 columns and then <code>cumcount</code>, as expected, all the returned value sho...
<p><code>groupby</code> omit <code>NaN</code>s rows so possible solution should be replace them to value which not exist in data, e.g. <code>-1</code>.</p> <p>Btw, <code>cumcount</code> seems create with omited rows separated group.</p> <pre><code>for i, df in df.groupby([0, 1, 2]): print (df) 0 1 2 2 2...
python|pandas
0
357,142
52,115,239
Pandas group by then count & sum based on date range +/- x-days
<p>I want to get a count &amp; sum of values over +/- 7 days period of a column after the dataframe being grouped to certain column</p> <p>Example data (edited to reflect my real dataset):</p> <pre><code>group | date | amount ------------------------------------------- A | 2017-12-26 04:20:20...
<p>Here is problem need loop for each row and for each groups:</p> <pre><code>t = pd.Timedelta(7, unit='d') def f(x): return x.apply(lambda y: x.loc[x['date'].between(y['date'] - t, y['date'] + t, inclusive=...
python|pandas|dataframe
5
357,143
52,222,980
Label file in tensorflow object detection training
<p>I want to create my own <code>.tfrecord</code> files using <code>tensorflow object detection API</code> and use them for training. The record will be a subset of original dataset so the model will detect only specific categories. The thing I don<code>t understand and can</code>t find any information about is, <stro...
<p>I had the same problem with my label map. After Googling a bit, I found your question here and also this excerpt from the TensorFlow Object Detection <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/using_your_own_dataset.md" rel="nofollow noreferrer">repository</a>:</p> <blo...
tensorflow|classification|object-detection
1
357,144
52,035,728
Convert torch t7 model to pytorch
<p>I have a torch t7 model which I want to convert it to a pytorch model. I used this method:</p> <pre><code>model = load_lua('xxx.t7', unknown_classes=True) </code></pre> <p>However, I get the following error:</p> <pre><code>AttributeError: type object 'torch.cuda.FloatStorage' has no attribute 'from_buffer' </code...
<p>There is a very useful converter. I used it lots of time.</p> <p>How to use; create a convert_torch.py file and paste below code in it. then run the code with .t7 argument.</p> <p><strong>python convert_torch.py -m xxx.t7</strong></p> <pre><code>from __future__ import print_function import os import math import ...
lua|pytorch|torch
-4
357,145
52,048,317
How to represent a single point on a matlplotlib plot
<p>I have a graph which represents the sentiments of the values in a column of pandas dataframe. Given a sentence, I want to highlight the corresponding sentiment value on the graph/plot. I am looking for an output similar to the image below:</p> <p><a href="https://i.stack.imgur.com/mBJ3e.jpg" rel="nofollow noreferre...
<p>You can use <code>pyplot.scatter</code> and pass single values in for <code>x</code> and <code>y</code>. Here's an example:</p> <pre><code>from matplotlib import pyplot as plt import numpy as np fig = plt.figure() x_data = np.linspace(0,3.5,100) y_data = [-x * (x - 3.2) for x in x_data] plt.plot(x_data, y_data, ...
python|pandas|matplotlib|plot
0
357,146
52,279,892
Batch Normalization causes huge difference between training and inference loss
<p>I followed the instruction on Tensorflow's web page for <a href="https://www.tensorflow.org/api_docs/python/tf/layers/batch_normalization" rel="nofollow noreferrer">tf.layers.batch_normalization</a> to set the <code>training</code> be <code>True</code> when training and <code>False</code> when inference (valid and t...
<p>Since you have not provided the complete code, or a link of it, I need to ask the following :</p> <blockquote> <p>How are you feeding the train_flag ?</p> </blockquote> <p>The correct way is to set <code>train_flag</code> to be a <code>tf.Placeholder</code>. There are other ways but this is the simplest approach...
python|tensorflow|batch-normalization
2
357,147
52,409,306
pandas.DataFrame.plot() not showing x axis after update
<pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.style.use('seaborn-white') </code></pre> <p>burndown dataframe:</p> <pre><code> Forecast Actual Baseline 11422 11422 February 2018 11422 11325 March 2018 11420 10...
<p>You are passing the dataframe index (<code>burndown_data.index</code>) as the first argument to <code>plt.xticks()</code>. According to the <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.xticks.html" rel="noreferrer">docs</a>, the first argument should be:</p> <blockquote> <p>A list of positions at...
python|pandas|matplotlib
5
357,148
52,062,951
How to add rows with calculations of specific columns in pandas
<p>I have a dtaframe and I'd like add at it's end 2 rows that will indicate how many cells were between a range of numbers. I'd like to do it to all columns, besides the first and last (I have a big dataframe with a lot of columns). For example, I have the following small scale dataframe:</p> <pre><code> start posi...
<p>IIUC, using <code>pd.cut</code> with <code>value_counts</code> get the range count , then we using <code>append</code> </p> <pre><code>newdf=df.iloc[:,1:-1].apply(lambda x : pd.cut(x,[0,9,100],labels=['0-9','10-100']).value_counts()) df.append(newdf.rename_axis('startposition',axis=0).reset_index()) Out[216]: ...
python|pandas
3
357,149
52,384,806
Imputer on some columns in a Dataframe
<p>I am trying to use Imputer on a singe column called age to replace missing values.But I get the error as " Expected 2D array, got 1D array instead:"</p> <p>Following is my code</p> <pre class="lang-python prettyprint-override"><code>import pandas as pd import numpy as np from sklearn.preprocessing import Imputer...
<p>The Imputer is expecting a 2-dimensional array as input, even if one of those dimensions is of length 1. This can be achieved using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="noreferrer"><code>np.reshape</code></a>:</p> <pre><code>imputer = Imputer(missing_values='NaN', s...
python|pandas|machine-learning|scikit-learn|imputation
9
357,150
52,142,035
Error "Kernel already used" when using trained RNN to make prediction
<p>Thanks for looking into this question!</p> <p>I am trying to train an LSTM network which predicts the next 5-day stock prices based on past 30-day stock prices. I have trained the model based on 265 samples. The variables are defined as follow:</p> <pre><code># Variables x = tf.placeholder("float", [265, 30]) y = ...
<p>Like the error says, you need to mention <code>reuse=True</code> such that the learned states can be used later for prediction. Do this:</p> <pre><code>rnn_cell = rnn.MultiRNNCell([rnn.BasicLSTMCell(n_hidden,reuse=tf.AUTO_REUSE), rnn.BasicLSTMCell(n_hidden,reuse=tf.AUTO_REUSE)]) </code></pre> <p>Also, this model l...
python|tensorflow|lstm|prediction|rnn
1
357,151
52,138,783
TF one hot encode tensor object
<p>Running a simple logistic regression following the mnist simple example my code:</p> <pre><code>x = np.array(xHotdog + xNotHotdog) y = np.array(yHotdog + yNotHotdog) print("y shape before: "+str(y.shape)) y = tf.one_hot(indices=y, depth=2) print("y shape after: "+str(y.shape)) y.eval() return x,y </code></pre>...
<p>You want to pass <code>Tensor object</code> to feed_dict and it raise an error. As mentioned in <a href="https://www.tensorflow.org/api_docs/python/tf/Session#run" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>The optional <strong>feed_dict</strong> argument allows the caller to <strong>override the</st...
tensorflow
0
357,152
52,213,628
numpy get sub matrix from 2d matrix
<p>I have a matrix of 400 columns , by 1000 rows</p> <p>what the best way to extract a sub matrix from it starting at say row 10, column 30 ending at row 390 column 960 ?</p> <p>Buzz</p>
<p>If your matrix is called <code>arr</code>, use:</p> <pre><code>arr[10:391,30:961] </code></pre> <p>Remember that python is zero indexed!</p> <p>For example, on this matrix with 10 rows and 5 columns:</p> <pre><code>&gt;&gt;&gt; arr array([[0.41296756, 0.14399754, 0.12606098, 0.61114244, 0.83243229], [0.91...
python|numpy|matrix
5
357,153
52,101,829
Trying to sum up rows with Pandas in a somewhat complicated manner
<p>I have the DataFrame:</p> <pre><code>df = np.DataFrame = {'Year' : [2010, 2011, 2012, 2013, 1922, 1923, 1924, 1925], 'ID' : ['A', 'A', 'A', 'A', 'B', 'B', 'B'], 'Data1' : [1, 2, 3, 4, 2, 3, 4], 'Data2' : [2, 2, 2, 2, 3, 3, 3]} df Year ID Data...
<p>use <code>assign</code> and <code>groupby</code></p> <pre><code>df = df.assign(**df.groupby('ID')['Data1', "Data2"].cumsum()) print(df) Year ID Data1 Data2 0 2010 A 1 2 1 2011 A 3 4 2 2012 A 6 6 3 2013 A 10 8 4 1922 B 2 3 5 1923 B ...
python|pandas
1
357,154
52,056,369
Python/Pandas for solving grouped mean, median, mode and standard deviation
<p>I have the following data:</p> <pre><code>[4.1, 4.1, 4.1, 4.2, 4.3, 4.3, 4.4, 4.5, 4.6, 4.6, 4.8, 4.9, 5.1, 5.1, 5.2, 5.2, 5.3, 5.3, 5.3, 5.4, 5.4, 5.5, 5.6, 5.6, 5.6, 5.7, 5.8, 5.9, 6.2, 6.2, 6.2, 6.3, 6.4, 6.4, 6.5, 6.6, 6.7, 6.7, 6.8, 6.8] </code></pre> <p>I need to build its count/frequency table like this bas...
<p>What about the following for your bins and labels issue:</p> <pre><code>bins = [4.1, 4.6, 5.1, 5.6, 6.1, 6.6, 7.1] labels = ['{}-{}'.format(x, y-.1) for x, y in zip(bins[:], bins[1:])] </code></pre> <p>Then instead of your values as a list, make them a <code>Series</code></p> <pre><code>sr = pd.Series([4.1, 4.1,...
python|pandas|numpy|statistics
3
357,155
52,432,124
Bin a dataframe according to two features
<p>I have a data frame consisting of 4 columns; date-time, wind speed, wind speed and wind direction. I need to bin the data in wind speed channels according to wind direction (12 sectors) and for every wind speed bin (1m/s, 2m/s, 3m/s and so on) and then calculate the mean of them. It would be easy if I needed to bin ...
<p>Here is a recipe:</p> <ul> <li>Convert your directions and speeds to bin indices if they are not already. You can use <code>numpy.searchsorted</code> for that.</li> <li>Flatten the 2D bin indices using <code>numpy.ravel_multi_index</code>.</li> <li>Use <code>numpy.bincount</code> on the flattened indices, once with...
python|numpy
0
357,156
52,101,276
Group rows of a pandas Series or DataFrame when rows can belong to multiple groups
<p>The <code>groupby</code> method of pandas is great when items/rows of a <code>Series</code>/<code>DataFrame</code> object each belong to one group. But I have a situation where each row can belong to zero, one, or multiple groups.</p> <p>An example with some hypothetical data:</p> <pre class="lang-none prettyprint...
<h3>explode your <code>'Count'</code> column by lengths of <code>'Tags'</code></h3> <pre><code>df.Count.repeat(df.Tags.str.len()).groupby(np.concatenate(df.Tags)).sum() fruit 25 red 15 vegetable 10 Name: Count, dtype: int64 </code></pre> <hr> <h3><code>numpy.bincount</code> and <code>pandas.facto...
python|pandas|pandas-groupby
2
357,157
52,336,754
Both fast and very slow scipy.signal.resample with the same input size
<p>According to the documentation of <a href="https://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.signal.resample.html" rel="nofollow noreferrer"><code>scipy.signal.resample</code></a>, the speed should vary according to the length <strong>of input</strong>:</p> <blockquote> <p>As noted, resample uses ...
<p>The docstring, somewhat misleadingly, states one part of the story. The resampling process consists of FFT (input size), zero-padding, and inverse FFT (output size). So an inconvenient output size will slow it down just as much as an inconvenient input size will. </p> <p>Cris Luengo suggested using direct interpola...
python|numpy|scipy|fft|resampling
3
357,158
52,022,597
f1_score: ValueError: Can't handle mix of multilabel-indicator and multiclass-multioutput?
<pre><code>#coding=utf-8 import numpy as np from sklearn.naive_bayes import GaussianNB from sklearn.metrics import f1_score y_true = np.array([[1, 0, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 0], [0, 0, 0], ...
<p>What do you mean by changing the 1 to 2 in the y_pred? For multi-label y_pred, you should use one hot encoding where each column denotes a class, and each entry only takes 0/1. The error stems from mixing up binary encoding with class labels.</p>
python|arrays|numpy
1
357,159
52,100,251
How to calculate the mean and standard deviation of multiple dataframes at one go?
<p>I've several hundreds of pandas dataframes and And the number of rows are not exactly the same in all the dataframes like some have 600 but other have 540 only. </p> <p>So what i want to do is like, i have two samples of exactly the same numbers of dataframes and i want to read all the dataframes(around 2000) from ...
<p>One solution that comes into mind is writing a function that finds outliers based on <code>upper</code> and <code>lower bounds</code> and then slices the <code>data frames</code> based on outliers index e.g.</p> <pre><code>df1 = pd.DataFrame({'wave': [1, 2, 3, 4, 5]}) df2 = pd.DataFrame({'stlines': [0.1, 0.2, 0.3,...
python|pandas|dataframe
1
357,160
52,248,704
How to handle specific values in a very specific way in a pandas dataframe?
<p>I have a pandas dataframe that looks like this:</p> <pre><code> TIMESTAMP TAIR 0 2011-06-01 00:00:00 24.3 1 2011-06-01 00:05:00 24.5 2 2011-06-01 00:10:00 24.2 3 2011-06-01 00:15:00 24.1 4 2011-06-01 00:20:00 24.2 5 2011-06-01 00:25:00 -999 6 2011-06-01 00:30:...
<h3>Using <code>mask</code> and <code>ffill</code>:</h3> <pre><code>df.assign(TAIR=df.TAIR.mask(df.TAIR.le(-999)).ffill()) </code></pre> <p></p> <pre><code> TIMESTAMP TAIR 0 2011-06-01 00:00:00 24.3 1 2011-06-01 00:05:00 24.5 2 2011-06-01 00:10:00 24.2 3 2011-06-01 00:15:00 24.1 4 2011-06-01 00...
python|python-3.x|pandas
4
357,161
52,227,540
Read all csv files quickly and update shared dictionary
<p>I'm new to python and pandas but here's what I want to do. I want to read through all the csv files in a directory and retrieve one cell of data from the file and update a count on a dictionary, with the retrieve value being a key in the dictionary. I have to do this for ~6000 csv files. How can I do this quickly?</...
<p>You can optimize your logic significantly by:</p> <ul> <li>Reading only the first row.</li> <li>Reading only the required column.</li> <li>Creating a lazy iterable from the first value of the desired column.</li> <li>Feeding the resulting iterable to <code>collections.Counter</code>.</li> </ul> <p>Here's some code...
python|pandas|csv|dictionary|counter
1
357,162
52,025,597
How to update dot product in numpy?
<p>I don't know how to update a dot product.<br> More specifically, I have a class in which I define in <code>totv = np.dot(x, values)</code> in the <code>__init__</code> function, where <code>x</code> and <code>values</code> are two NumPy arrays.<br> Then in one the following methods I change one value in the array <c...
<p>So I assume you have a situation like the following:</p> <pre><code>import numpy as np class my_class(): def __init__(self, x, values): self.x = x self.values = values self.totv = np.dot(x, values) def update_x(self, i, v): self.x[i] = v inst = my_class(np.array([1,2,3]), np...
python|numpy
1
357,163
52,377,790
transform method of pandas can not pass multi methods
<p>I want to pass 2 methods to <code>transform</code> method of pandas as the API says it can pass a list of functions or dict of column names -> functions. I pass a list of functions, but it does not work:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'rti':['a','a','b','c','b','c','a'],'ts...
<p>Seems like <code>transform</code> do not accept list of function , Open issue in <a href="https://github.com/pandas-dev/pandas/issues/17309" rel="nofollow noreferrer">github</a> </p> <pre><code>df.groupby('rti').agg(['mean','sum']).reindex(df.rti) Out[12]: rs ts mean sum ...
python|pandas
2
357,164
52,164,461
Construct new column from existing columns without re specifying dataframe in pandas
<p>If you want to create a new column in a dataframe from other columns, you can write it pretty concise in R. In Python however I have not find a way yet to do this because I have to state the dataframe everytime I use a column if I'm not mistaken. I there a way to state once which dataframe to use, after which you on...
<p>Try df.apply</p> <pre><code>df = pd.DataFrame({'A': [1, 2, 3]}) Then df['B'] = df.apply(lambda x:x['A'], axis=1) df['C'] = df.apply(lambda x:x['A']+x['B'] , axis=1) </code></pre> <p>Output</p> <pre><code> A B C 0 1 1 2 1 2 2 4 2 3 3 6 </code></pre>
python|r|pandas|dataframe|assign
1
357,165
52,158,559
Pybaseball: Extract standings data and save to disk using pandas
<p>What I am trying to do is take this output from pybaseball which is set in as a list.</p> <blockquote> <p>[ Tm W L W-L% GB 1 Boston Red Sox 94 44 .681 -- 2 New York Yankees 86 51 .628] </p> </blockquote> <p>and put it into a csv file using pandas. So far these are the are the queries I have tried I have the info...
<p>Looks like <code>standings()</code> returns a <code>list</code> of <code>dataframes</code>:</p> <pre><code>from pybaseball import standings import pandas as pd data = standings() print type(data) print type(data[0]) </code></pre> <p>Output:</p> <pre><code>&lt;type 'list'&gt; &lt;class 'pandas.core.frame.DataFram...
python|pandas
0
357,166
52,105,659
Pandas.read_csv "unexpected end of data" Error
<p>I'm trying to read a dataset using pd.read_csv() am getting an error. Excel can open it just fine.</p> <p><code>reviews = pd.read_csv('br.csv')</code> gives the error ParserError: Error tokenizing data. C error: EOF inside string starting at line 312074</p> <p><code>reviews = pd.read_csv('br.csv', engine='python',...
<p>For me adding this fixed it:</p> <p><code>error_bad_lines=False </code></p> <p>It just skips the last line. So instead of </p> <p><code>reviews = pd.read_csv('br.csv', engine='python', encoding='utf-8')</code></p> <p><code>reviews = pd.read_csv('br.csv', engine='python', encoding='utf-8', error_bad_lines=False)...
python|pandas
29
357,167
52,189,676
How to set element of 3D tensorflow Tensor c++
<p>I have the following 3D tensor below:</p> <pre><code>auto inputX = Tensor(DT_DOUBLE, TensorShape({1,1,9})); </code></pre> <p>How would I set a value to an element in the tensor?</p> <p>Additionally for the 1D tensor below how would I set a value?</p> <pre><code>auto inputY = Tensor(DT_INT32, TensorShape({1})); <...
<p>You can access the data as an <a href="http://eigen.tuxfamily.org/index.php?title=Tensor_support" rel="noreferrer">Eigen tensor</a> (or more precisely an <code>Eigen::TensorMap</code>) through the <a href="https://www.tensorflow.org/api_docs/cc/class/tensorflow/tensor#tensor_20" rel="noreferrer"><code>tensor</code><...
c++|tensorflow
6
357,168
52,030,631
Remove the automatic two spaces between columns that Pandas DataFrame.to_string inserts
<p>I'm looking for a solution to remove/turn off the 2 spaces between columns that <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_string.html" rel="nofollow noreferrer"><code>df.to_string</code></a> creates automatically.</p> <p>Example:</p> <pre><code>from pandas import DataFra...
<p>You can use the <code>pd.Series.str.cat</code> method, which accepts a <code>sep</code> keyword argument. By default <code>sep</code> is set to <code>''</code> so there is no separation between values. Here are the docs: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.cat.html" rel=...
python|pandas|dataframe|formatting|display
3
357,169
52,346,241
Better way to insert elements into numpy array
<p>I have a numpy array and I have a list of elements I want to insert at specific locations (not contiguous) into that array. The indices are in another numpy array.</p> <pre><code>target answer: [1,2,3,4,5] original array: [1,3,5] elements to insert: [2,4] indices: [1,3] </code></pre> <p><code>numpy.insert(arr,[1,3...
<p>Use range-offsetted indices with <code>np.insert</code> -</p> <pre><code>np.insert(a, add_idx - np.arange(len(add_idx)), add_val) </code></pre> <p>Sample run -</p> <pre><code>In [20]: a Out[20]: array([1, 3, 5]) In [21]: add_idx Out[21]: [1, 3] In [22]: add_val Out[22]: [2, 4] In [23]: np.insert(a, add_idx - n...
python|arrays|python-2.7|numpy|scipy
3
357,170
52,391,463
Pandas referencing index column by name
<p>I'm using pandas <code>pandas-0.23.4-cp36-cp36m-manylinux1_x86_64.whl</code> and I noticed that when you set a column as an index column, you can no longer reference it by name. Is there any way to reference the column after you've set it as an index? The code below raises <code>KeyError</code>.</p> <pre><code>impo...
<p>You can pass the argument <code>drop=False</code> when setting the index to keep it as a column in the DataFrame:</p> <pre><code>df.set_index('tscol', inplace=True, drop=False) </code></pre>
python|pandas
3
357,171
52,260,609
pandas filter column values by multiple values
<p>I have df with multiple columns such as MLB, NBA, NHL, NFL, TESTNBA i would like to return a list where the columns have the string MLB or NBA in it. so like below: </p> <pre><code>df_check = ['MLB', 'NBA', 'TESTNBA'] value_cols = [col for col in df.columns if df_check in col] </code></pre> <p>The above fails wit...
<p>You may use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><strong><code>pandas.DataFrame.filter</code></strong></a>:</p> <p><strong><em>Setup</em></strong></p> <pre><code>df = pd.DataFrame(columns=['MLB', 'NBA', 'NHL', 'NFL', 'TESTNBA']) ...
python|pandas|filtering
1
357,172
52,365,468
How to use Pandas dataframe as map without common index
<p>I have a dataframe that contains mapping information as below:</p> <pre><code>dfMap = pd.DataFrame({'BId': ['Banana', 'Apple', 'Guava', np.nan, np.nan], 'NId': [np.nan, 'GOne', np.nan, 'GFive','GTwo'], 'Id': ['Banana', 'Apple', 'Guava', 'GFive', 'GTwo']}) print(dfMap) ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> by condition with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> if only <code>BI</c...
pandas
1
357,173
52,252,879
axis 0 is out of bounds for array of dimension 0
<p>I am trying to create a watermark identifier but receiving the error </p> <blockquote> <p>AxisError: axis 0 is out of bounds for an array of dimension 0</p> </blockquote> <p>it seems to me matrix issue but I am unable to understand it. can anyone please make me understand this error code</p> <p>below are my cod...
<p>So the error is in the first function. All the rest of the code is irrelevant.</p> <p>It's taking the <code>median</code> of a <code>map</code> call. In python3, <code>map(...)</code> isn't evaluated; you need <code>list(map(...))</code>. </p> <p>My guess is that <code>median</code> does <code>np.array(map....)...
numpy|opencv|python-3.6
4
357,174
52,341,766
KeyError: 'Date'
<pre><code>import pandas as pd import numpy as np from nsepy import get_history import datetime as dt start = dt.datetime(2015, 1, 1) end = dt.datetime.today() infy = get_history(symbol='INFY', start = start, end = end) infy.index = pd.to_datetime(infy.index) infy.head() infy_volume = infy.groupby(infy['Date'].dt.yea...
<p>Here you have the <code>date</code> column as index so use</p> <pre><code>infy.groupby(infy.index.year).Volume.sum().reset_index() </code></pre> <p>If you want to <code>groupby</code> with year and month use</p> <pre><code>infy_volume = infy.groupby([infy.index.year, infy.index.month]).Volume.sum() infy_volume.in...
python|python-3.x|pandas|numpy
2
357,175
52,006,223
Numpy mask from cylinder coordinates
<p>I generated the coordinates of a cylinder. Its two faces connect two arbitrary points already given.</p> <p><a href="https://i.stack.imgur.com/GHsKJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GHsKJ.png" alt="plot of cylinder"></a></p> <p>Is it possible to build a 3D numpy mask of the filled...
<p>In the end I looped through the coordinates of tube and faces. I got the coordinates following this link: <a href="https://stackoverflow.com/questions/52061831/3d-points-from-numpy-meshgrid-coordinates">3D points from Numpy meshgrid coordinates</a> </p> <pre><code>tube = np.stack((X.ravel(), Y.ravel(), Z.ravel()), ...
python|numpy|geometry|mask
0
357,176
52,083,501
How to compute correlation ratio or Eta in Python?
<p>According the answer to this <a href="https://stats.stackexchange.com/questions/73065/correlation-coefficient-for-non-dichotomous-nominal-variable-and-ordinal-numeric">post</a>,</p> <blockquote> <p>The most classic &quot;correlation&quot; measure between a nominal and an interval (&quot;numeric&quot;) variable is Et...
<p>The answer above is missing root extraction, so as a result, you will receive an eta-squared. However, in the main <a href="https://towardsdatascience.com/the-search-for-categorical-correlation-a1cf7f1888c9" rel="nofollow noreferrer">article</a> (used by User777) that issue has been fixed.<br /> So, there is an arti...
python-3.x|pandas|statistics|correlation|categorical-data
4
357,177
60,566,113
Mapping Substrings from dataframe to return values as a new column
<p>If I have a postal code column, I want to be able to associate substrings of each row to certain Regions. I thought about using a dictionary </p> <p>dict = { 'SW1': 'London','NE':'London','W1A':'Other','CT':'Other'}</p> <pre><code>Postal Code SW1E 5Z NE99 1AR SW1 W1A 1ER CT21 4JF </code></pre> <p>Desired table:...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>series.str.extract</code></a> based on the dictionary keys and map them back to create a new column.</p> <pre><code>df['Region']=(df['Postal Code'].str.extract('('+'|'.join(mydict....
python|pandas|dictionary|substring|partial
0
357,178
60,546,944
Unpacking lists of dicts column-wise with unique names in Python/Pandas
<p>Suppose I have <code>df</code> below:</p> <pre><code>df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [ [{'X': 'x1', 'Y': 'y1'}], [{'X': 'x2', 'Y': 'y2'}, {'X': 'x3', 'Y': 'y3'}], [] ]}) df A B 0 a [{'X': 'x1', 'Y': 'y1'}] 1 b [{'X': 'x2', 'Y': 'y2'}, {'X': 'x3', 'Y': 'y3'}] 2 c [] </cod...
<p>Idea is use list comprehension with nested dictionary comprehension for list of dicts with new keys generated with <code>enumerate</code>, pass to <code>Dataframe</code> constructor and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>Data...
python|pandas|dataframe|nested
2
357,179
60,498,999
'Line2D' object has no property 'kind'
<p>I just started learning pandas, when I wanted to make a bar plot of the mean of the stations in year of 2013 on creating a <code>fig, ax = plt.subplots()</code> object and adding the plot to the created ax' I am getting this error while running this part of the code 'Line2D' object has no property 'kind'</p> <pre...
<p>For your first question, you have to use <code>data.plot(x, y, kind='bar')</code>, not <code>ax.plot()</code>. </p> <pre><code>fig,ax = plt.subplots(1) ax = data['2013'].mean().plot(kind='bar') ax.set_xlabel('x label name') # replace with the labels you want ax.set_ylabel('Mean') plt.xticks(rotation=30) plt.show(...
pandas|datetime|subplot
6
357,180
60,605,538
Python Pandas - copying data from one sheet and appending at the end of another
<p>I have a workbook called TEMPLATE.xlsx. In this workbook i have two tabs, ALL_DATA_RAW and WEEKLY_DATA_RAW. get my data from an API and feed it into Weekly_Data tab by opening TEMPLATE workbook, deleting the WEEKLY_DATA_RAW, then recreating that same tab and storing the df from API into that tab. </p> <pre><code>bo...
<p>For your first issue you can create a temp val to hold all your data without changing it and for the next issue if im understanding correctly is to combine/concatenate excel files data. Look at this video and let me know if that is what youre looking for <a href="https://www.youtube.com/watch?v=kWaerL6-OiU" rel="nof...
python|excel|python-3.x|pandas
1
357,181
60,495,486
Plot the Decision Boundary of a Neural Network in PyTorch
<p>I've been trying to plot the decision boundary of my neural network which I used for binary classification with the sigmoid function in the output layer but with no success, I found many posts discussing the plotting of the decision boundary of a scikit-learn classifier but not a neural network built in PyTorch. Bel...
<p>You could define a mesh of dots and then predict each dot. According to the result, we can find out the dots with different predictions on each side. Thus, by connecting the dots, we have an approximate decision boundary. However, this could be computationally expensive if the area to the plot is large or a detailed...
python|matplotlib|neural-network|pytorch
0
357,182
60,566,316
Why does the length of the array given to np.random.shuffle() affect np.random.uniform()?
<p>Simple example, changing the <em>values</em> inside the <code>aa</code> array does not change the result of <code>np.random.uniform()</code>:</p> <pre><code>import numpy as np np.random.seed(12345) aa = np.array([3., 56., 7]) np.random.shuffle(aa) print(np.random.uniform()) </code></pre> <p>But changing its <em>le...
<p>Python uses a pseudo-random number generator, which produces a deterministic sequence of values. Re-seeding will yield the exact same sequence, but if you use different amounts, you'll end up at different places in the sequence.</p> <p>Shuffling <code>n</code> items calls the random number generator <code>n-1</cod...
python|numpy|random
2
357,183
60,646,797
How to convert a grouped pandas series to a numpy array
<p>The <code>df</code> below contains integers grouped by time. I’m trying to convert these to a <code>numpy</code> array.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ 'Time' : [1,1,1,2,2,2,3,3,3], 'A' : [3, 4, 5, 2, 5, 6, 1, 6, 7], 'B' : [2, 4, 5, 2, 5, 5, 2, 6, 5], ...
<p>use to to list before converting </p> <pre><code>np.array(df.groupby('Time')['A'].apply(list).tolist()) </code></pre> <p>Out:</p> <pre><code>array([[3, 4, 5], [2, 5, 6], [1, 6, 7]]) </code></pre>
python|pandas|numpy
2
357,184
60,674,883
Difference of Keras' ZeroPadding2D in TensorFlow v1 and v2?
<p>I recently finished the Deep Learning Course in Coursera by Andrew Ng for Convolutional Networks. The last assignment concludes face recognition. I want to migrate the code from this assignment, which uses TensorFlow 1.2.1, to a recent version (I am using TensorFlow 2.2.0).</p> <p>Let's observe following code from ...
<p>Replacing the code,</p> <pre><code>X = ZeroPadding2D((3, 3))(X_input) </code></pre> <p>with </p> <pre><code>X = ZeroPadding2D(padding = ((3, 3), (3,3)), data_format='channels_first')(X_input) </code></pre> <p>will give you the expected results.</p> <p>Complete working code is shown below:</p> <pre><code>from t...
tensorflow|keras|deep-learning|conv-neural-network|tensorflow2.0
0
357,185
60,640,066
How to combine horizontally many CSV files using python csv or pandas module?
<p><strong>Hello!</strong> I would like to combine horizontally many CSV files (the total number will oscillate around 120-150) into one CSV file by adding one column from each file (in this case column called “grid”). All those files have the same columns and number of the rows (they are constructed the same) and are ...
<p>For the part of CSV i think you need another list define OUTSIDE the loop. Something like</p> <pre><code>import os import sys dirname = os.path.dirname(os.path.realpath('__file__')) import glob import csv extension = 'csv' files = [i for i in glob.glob('*.{}'.format(extension))] out_merg = ('merged_csv_file_direc...
python|pandas|csv
1
357,186
60,577,038
Is there a more elegant way of creating these numpy arrays?
<p>I feel like I'm creating too much arrays and wasting resources, so I'm looking for a cleaner and more efficient approach for the following problem:</p> <p>Suppose we have an oscillating graph, and we know the positions of the minimums (<code>min_x˛</code>) and maximums (<code>max_x</code>). We pick a reference poin...
<p>Here how I would change the <code>min_max</code> code without writing so many temporary variables and avoiding list comprehensions:</p> <pre><code>def min_max(ref_point, min_x, max_x): max_freq = ref_point - max_x min_freq = ref_point - min_x # Faster sort neg_freq = np.sort(np.append(max_freq[max...
python|performance|numpy
1
357,187
60,624,291
rendering pandas dataframe ot html with highlighted cells
<p>I have a pandas daraframe which I am rendering to html:</p> <pre><code>df = pd.DataFrame() df['parm A'] = [9.5, 8.2, 13] df['parm B'] = [True, False, True] html = df.to_html() path = "C:\\path" file_name = "file.html" #make file name specific to patient and plan name text_file = open(file_name, "w") text_file.wri...
<p>one solution would be to use pandas styling, here goes:</p> <pre><code>import pandas as pd df = pd.DataFrame() df['parm A'] = [9.5, 8.3, 13] df['parm B'] = [True, False, True] def red_green(s): return ['background-color: green' if (v&lt;10 and v) else 'background-color: red' for v in s] html = df.style.apply(...
python|html|pandas
1
357,188
60,494,388
passing values with df.insert
<p>I wanna insert data into a data frame like: </p> <pre><code>df = pd.DataFrame(columns=["Date", "Title", "Artist"]) </code></pre> <p>insertion happens here:</p> <pre><code>df.insert(loc=0, column="Date", value=dateTime.group(0), allow_duplicates=True) df.insert(loc=0, column="Title", value=title, allow_duplicates=...
<p>The error seems to be from your <code>value=dateTime.group(0)</code> value. Can you elaborate on what is structure of dateTime?</p> <p>Plus, df.insert() inserts a column rather than adding the data to a dataframe. </p> <p>You should first transform your data into a series object and then use df.concat() to concate...
python|pandas|dataframe
0
357,189
60,495,218
i am trying to perform outer join
<p>I am trying to join perform outer join and get the error at</p> <blockquote> <p>Use an outer join to get comments from users who have not posted about anorexia/obesity.</p> </blockquote> <p>I also use <code>.set_index</code> in the join but it gives me an error at the line:</p> <pre><code>neither_df = neither_d...
<p>The error implies that the column you are trying to use as the column to join on (author) has different data type in every table - the first (chunk) is a string and the second (both_authors) is an int. You should convert the type of the first dataframe's column in one of the following ways:</p> <pre><code>chunk['au...
python|pandas
0
357,190
60,554,813
Strange Move Assignment Operator Signature
<p>I came across an unfamiliar move assignment operator signature in Pytorch' tensor backend (ATen, <a href="https://github.com/pytorch/pytorch/blob/877c96cddfebee00385307f9e1b1f3b4ec72bfdc/aten/src/ATen/TensorOperators.h#L14" rel="nofollow noreferrer">source</a>). Just out of curiosity, what does the <code>&amp;&amp;<...
<p>Objects of a class used as expressions can be rvalues or lvalues. The move assignment operator is a member function of a class.</p> <p>This declaration</p> <pre><code>Tensor &amp; Tensor::operator=(Tensor &amp;&amp; rhs) &amp;&amp; </code></pre> <p>means that this move assignment operator is called for rvalue ob...
c++|pytorch|rvalue-reference|rvalue|move-assignment-operator
4
357,191
60,417,487
Use row index number as string in new column rows
<p>I would like to add a column to my <code>DataFrame</code> in which each row includes a string with the row index + 1. This is what I have attempted:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame.from_records([{'some_column': 'foo'}, {'some_column...
<p>Use:</p> <pre><code>df.assign(new_column='some string '+(df.index+1).astype(str)) some_column new_column 0 foo some string 1 1 bar some string 2 </code></pre> <p>or</p> <pre><code>df['new_column']='some string ' + (df.index+1).astype(str) </code></pre> <p><strong>Alternative</strong></p> ...
python|pandas
2
357,192
60,688,635
Move rows not null to start from first column in Pandas
<p>In Pandas, I would like to shift rows in my dataframe to eliminate every cell with a value less than 1, in order to start each row with non null values in the first column. For example, the original data:</p> <pre><code>Name first_column second_column third_column ... first 0 0 1 ... second 1 ...
<p>IIUC</p> <pre><code>df=df.mask(df.eq(0)).T.apply(lambda x : sorted(x,key=pd.isnull)).T Name first_column second_column third_column 0 first 1 NaN NaN 1 second 1 3 5 2 third 3 8 NaN 3 fourth 5 ...
pandas|jupyter-notebook
2
357,193
60,595,374
TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category
<p>I'm trying to create a new column in a pandas data frame representing the sum of each row (in this case, this number represents the number of passengers in a particular year from the Seaborn Flights dataset that comes with the library upon import. Here is my code:</p> <pre><code>import pandas as pd import seaborn ...
<p>There is <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.CategoricalIndex.html" rel="noreferrer"><code>CategoricalIndex</code></a>, so error, because <code>total</code> is not exist in <code>categories</code>.</p> <p>Possible solution is convert columns to strings:</p> <pre><code>flights_...
python|pandas|seaborn
9
357,194
60,493,396
Is it possible to have a test on tensor size inside a tensorflow tf.function?
<p>I don't understand why the following doesn't work:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf @tf.function def my_func(x): res = x[0] + x[1] if tf.size(x) == 3: res += x[2] return res print(my_func(tf.ones((3,)))) print(my_func(tf.ones((2,)))) </code></pre> <p>...
<p>So I read more on the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/limitations.md#autograph-reference" rel="nofollow noreferrer">limitations of autograph</a>. In particular in <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/...
python|python-3.x|tensorflow
0
357,195
60,733,886
Update DataFrame index by matching column value
<p>Consider the following <code>pandas.DataFrame</code>:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({ ... "sym": ["a", "b", "c"], ... "del": [1, 2, 3] ... }) </code></pre> <p>And consider the following <code>dict</code>:</p> <pre><code>&gt;&gt;&gt; d = [{"sid": 99, "sym": ...
<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 dictionary, then replace missing values by original index values:</p> <pre><code>d = [{"sid": 99, "sym": "b"}, {"sid": 88, "sym": "c"}] d1 = {x['sym']:x['sid'] f...
python|pandas
2
357,196
60,745,582
How can I extract correctly weights from my CNN?
<p>First of all I trained my CNN-architecture:</p> <pre><code>adam = optimizers.Adam(learning_rate=0.0001, beta_1=0.9, beta_2=0.999, amsgrad=False) model = Sequential() model.add(Conv2D(20, (3,3), activation='relu', input_shape =(5,5,1), padding='same', kernel_initializer='he_normal')) model.add(Conv2D(30, (3,3), act...
<p>The two "float32-elements" you have are corresponding to the weights of filter and biases of the conv layer. The <strong>weights of filter</strong> will have shape (3, 3, 1, 20) and <strong>biases</strong> will have shape (20), because you have 20 filters, and one bias value for each fiter. </p> <p>(3, 3, 1, 20) ...
python|tensorflow|keras|output|conv-neural-network
1
357,197
60,386,760
Find the missing rows by comparing before and after when merging dataframes
<p>I want to find the rows that disappeared by comparing before and after when merging dataframes.</p> <p>previous dataframe:</p> <p>(Each row is unique)</p> <pre><code> index date code col2 0 10/01 1111 B 1 11/02 2222 A 2 12/11 5555 B 3 12/15 1111 B </code></pre> <p>current da...
<p>You simply need to do an <code>outer</code> join and set <code>indicator</code> to <code>TRUE</code>. Then you need to filter the required rows by your indicator column. </p> <pre><code>import pandas as pd df_prev = pd.DataFrame({'code':[111,222,555,666], 'col':['A','B','B','C']}) df_after = pd.D...
python-3.x|pandas
2
357,198
60,623,716
How to change data in a column using the longer length of a string in PANDAS?
<p>I have a dataframe with two columns: name and id. In some cases the names are repeated, and can also be abbreviated, but they'll always have the same ID, example:</p> <pre><code> NAMES ID 1. Peter Elliot 12345678 2. Peter Elliot 12345678 3. Peter E. 12345678 4. Lucas Kershaw 87654321 5....
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.len.html" rel="nofollow noreferrer"><code>Series.str.len</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>groupby.tr...
pandas|dataframe|format|string-length
2
357,199
60,513,614
How to control differential chain rule in Keras
<p>I have a convolutional neural network with some layers in keras. The last layer in this network is a custom layer that is responsible for sorting some numbers those this layer gets from previous layer, then, the output of custom layer is sent for calculate loss function. </p> <p>for this purpose (sorting) I use som...
<p>A few things:</p> <ul> <li>It's impossible to train without a derivative, so, there is no solution if you want to train this model </li> <li>It's not necessary to "compile" if you are only going to predict, so you don't need custom derivation rules</li> </ul> <p>If the problem is really in that layer, I suppos...
python|tensorflow|keras
1