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
367,700
58,451,263
Create a tensor of multiple images with tf.browser.fromPixels with Tensorflow JS
<p>I want to create a feature <strong>tensor of multiple images</strong>, using <a href="https://js.tensorflow.org/api/latest/?hl=de#browser.fromPixels" rel="nofollow noreferrer">tf.browser.fromPixels</a>.</p> <pre><code>const image1 = new ImageData(1, 1); image1.data[0] = 100; image1.data[1] = 150; image1.data[2] = 2...
<p>You can concatenate tensors with <a href="https://js.tensorflow.org/api/0.6.1/#concat" rel="nofollow noreferrer">tf.concat(tensors, axis?)</a></p> <pre class="lang-js prettyprint-override"><code>const a = tf.tensor1d([1, 2]); const b = tf.tensor1d([3, 4]); a.concat(b); </code></pre> <p>Or with multiple tensors</p>...
image|tensorflow|tensor|tensorflow.js
2
367,701
58,275,253
TensorFlow 2.0 Keras layers with custom tensors as variables
<p>In TF 1.x, it was possible to build layers with custom variables. Here's an example:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import tensorflow as tf def make_custom_getter(custom_variables): def custom_getter(getter, name, **kwargs): if name in custom_variables: ...
<h2>Answer based on the comment below</h2> <p>Given you have:</p> <pre><code>kernel = createTheKernelVarBasedOnWhatYouWant() #shape (784, 64) bias = createTheBiasVarBasedOnWhatYouWant() #shape (64,) </code></pre> <p>Make a simple function copying the code from <code>Dense</code>:</p> <pre><code>def custom_dense(x): ...
python|tensorflow|keras|tensorflow2.0
2
367,702
58,198,147
Keep First and Last entry of a Duplicate in a Dataframe Column
<p>I have a big dataframe with many duplicates in it. I want to keep the first and last entry of each duplicate but drop every duplicate in between.</p> <p>I've already tried to get this done by using df.drop_duplicates with the parameters 'first' and 'last' to get two dataframes and then merge them again to one df so...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.nth.html" rel="nofollow noreferrer"><code>GroupBy.nth</code></a> for avoid duplicates if group with length is <code>1</code>:</p> <pre><code>df = pd.DataFrame({ 'a':[5,3,6,9,2,4], 'Path':list('aaabbc...
python|pandas|dataframe|duplicates
3
367,703
58,368,528
Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext
<p>Anyon know Why I keeo getting this error in Jupyter Notebooks??? I've been trying to load my Tensorflow model into Apache Spark vis SparlFlowbut I can't seem to figure out how to get past this error. Any help would be much appreciated.</p> <p>First Jupyter cell: </p> <pre><code>from sparkflow.graph_utils import bu...
<p>Seems like you have too many running SparkSessions. In the default configuration you can only have 16, because there are 16 retries to get a port for Spark's job overview page.</p> <p>This could be because you work on a busy cluster with many users running jobs, or, e.g., because you have a lot of Jupyter notebooks ...
python|apache-spark|tensorflow|pyspark|jupyter-notebook
1
367,704
58,533,569
Scraping two pages at the same time : pandas error
<p>I want to save movie reviews and movie's title from those two pages.</p> <pre><code>https://movie.naver.com/movie/bi/mi/pointWriteFormList.nhn?code=~ https://movie.naver.com/movie/bi/mi/basic.nhn?code=~ </code></pre> <p>And when I ran this code, and opened the csv file.</p> <blockquote> <p>ValueError: Shape of ...
<p>One thing you could try for cleaning it up is to first convert to string and then place constraints based on the html like the below:</p> <pre><code>title = str(soup.find('h3', 'h_movie')) start = '" title="' end = ' , 2018"&gt;' newTitle = title[title.find(star...
python|pandas|web-scraping|beautifulsoup|web-crawler
1
367,705
58,477,429
I do not understand the behavior of pandas.drop, since I get different results from dropna (too many rows are dropped)
<p>I have a DataFrame with some NA and I want to drop the rows where a particular column has NA values.</p> <p>My first trial has been: - Identifying the rows where the specific column values were NA - Pass them to pandas.drop()</p> <p>In my specific case, I have a DataFrame of 39164 rows by 40 columns. If I look to ...
<p>This is because your index is not unique, look for example for index 0, you have forty rows with this index</p> <pre><code>data_idx0 = data.iloc[0] data_idx0.shape # (40,) </code></pre> <p>If at least one of the rows with index 0 has <code>surface_reelle_bati</code> missing, all the forty rows will disappear from ...
python|pandas
1
367,706
58,464,654
Count the frequency of each element categorical values in python
<p>Is there a simple way to do this in Python?</p> <p>For example I have:</p> <pre><code>x = np.array(['a', 'b', 'a', 'b', 'b', 'u']) </code></pre> <p>Desired outcome:</p> <pre><code>[2, 3, 2, 3, 3, 1] </code></pre>
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>np.unique</code></a> with <code>return_counts</code> and <code>return_inverse</code> enabled:</p> <pre><code>_, inverse, count = np.unique(x, return_inverse=True, return_count=True) result = count[in...
python|numpy|frequency
3
367,707
58,573,526
How to insert a new column based on condition (NaN)
<p>I'm pretty new on Python and here's my issue. It's pretty basic !</p> <p>I'm trying to create a new column (called "<strong>SectorCode</strong>") based on another column (called "<strong>Sector</strong>"). For example, if the column "<strong>Sector</strong>" contains "<strong>Materials</strong>" Then it should disp...
<p>You are using one <code>=</code> which stands for assignment when you need to use two <code>==</code> to test for a condition. </p>
python|pandas|conditional-statements
1
367,708
58,424,594
How to extract features from a pytorch pretrained fine-tuned model
<p>I need to extract features from a pretrained (fine-tuned) BERT model. </p> <p>I fine-tuned a pretrained BERT model in Pytorch using huggingface transformer. All the training/validation is done on a GPU in cloud.</p> <p>At the end of the training, I save the model and tokenizer like below:</p> <pre><code>best_mode...
<p><a href="https://pytorch.org/docs/stable/torch.html?highlight=load#torch.load" rel="nofollow noreferrer">torch.load()</a> returns a <code>collections.OrderedDict</code> object. Checkout the <a href="https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-model-for-inference" rel="nofollow no...
machine-learning|pytorch
1
367,709
58,233,787
Why time per step continuously decreasing with increasing in number of epoch?
<p>While training deep learning model, with every increase in number of epoch, the time taken to complete one step is continuously decreasing. What made this increase in efficiency as the data are same?</p> <p>And why in first epoch, it very large as compare to other epochs? Any answer or reference for the same will b...
<p>Partial answer:</p> <p>The first epoch is slower due to a variety of initialization overhead: your entire model initializes to the selected values or distributions, the model layers are instantiated, etc.</p> <p>Later epochs may accelerate for any of a variety of reasons. The most common, in the work I do, is tha...
tensorflow|keras|deep-learning|loss-function
0
367,710
58,474,813
Interpolate without looping
<p>Let's say an array sig:</p> <p><code>sig = np.array([1,2,3,4,5])</code></p> <p>Another array k which consists of indexes:</p> <pre><code>k = np.array([1,2,0,4]) </code></pre> <p>I want to find an array that interpolates between <code>s[k[i]-1] and s[k[i]]</code> only if <code>k[i]!= 0 and k[i] != len(k)</code> ...
<p>For a (very) limited amount of cases like here, an approach to vectorize such code is to build a linear combination of each case and the corresponding calculation.</p> <p>So, set up vectors</p> <ul> <li><code>alpha = (k == 0)</code> to match the first case,</li> <li><code>beta = (k &gt; 0)</code> to match the seco...
python|numpy|vectorization
1
367,711
58,602,232
Data annotation, dataframe merge
<p>I need to annotate data (a liste of names in a column) with the content of a column of a second dataframe (containing some atributes of these names). Like dataframe 1 :</p> <pre><code>id name col ---------------------------- 29834 Marie Peer 890384 Marie Peach 30047 Susan Peer </code></pre>...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a> with <code>join</code> for second DataFrame, so possible use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html...
python|pandas|dataframe|dictionary
0
367,712
58,363,431
Pandas Compare - How to compare 2 date columns in 2 separate dataframes
<p>I have once csv with missing dates, I have created a new df of that same date range, without the missing dates. I want to compare the two csvs and place an NaN wherever there are blank dates in the original csv:</p> <p>Example:</p> <pre><code> DateTime Measurement Dates 0 2016-10-09 00:00:00 1021.9...
<p>If I understand your correctly you want to resample your <code>DateTime</code> column to a daily frequency and fill the gaps with <code>NaN</code>:</p> <pre><code># Use this line if your DateTime column is not datetime type yet # df['DateTime'] = pd.to_datetime(df['DateTime']) dates = pd.date_range(df['DateTime']....
pandas|csv|date|compare
0
367,713
58,223,646
Problems producing desired luigi output
<p>I am trying to create a pipeline that takes in 3 files, takes n amount of rows from each file (represented by obs_num) compares each of the values in the files to a random float between 0 and 1 and either returns the obs_num if it is greater than the random number or false if not. I then append these values to a li...
<p>Check your formatting. In your state machine file, your <code>with</code> statement is at the class level for some reason and the <code>output</code> method is at the namespace level.</p>
python|pandas|luigi
0
367,714
58,349,485
Need an efficient way to create one dataframe from a generator of json objects?
<p>I have a generator:</p> <pre class="lang-py prettyprint-override"><code>gen = ([{'Key': x, 'Data': {'value': i}} for i in range(3)] for x in ['A', 'B', 'C']) </code></pre> <p>I'd like to create one dataframe in the form:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame([ {'Key': 'A', 'Dat...
<p>I would use <code>pd.io.json.json_normalize</code> and <code>from_iterable</code></p> <pre><code>from itertools import chain &gt;&gt;&gt; df = pd.io.json.json_normalize(chain.from_iterable(gen)) </code></pre> <hr> <pre><code> Key Data.value 0 A 1 1 A 2 2 B 0 3 B ...
python|pandas
2
367,715
58,547,151
Error with numpy array calculations using int dtype (it fails to cast dtype to 64 bit automatically when needed)
<p>I'm encountering a problem with incorrect numpy calculations when the inputs to a calculation are a numpy array with a 32-bit integer data type, but the outputs include larger numbers that require 64-bit representation.</p> <p>Here's a minimal working example:</p> <pre><code>arr = np.ones(5, dtype=int) * (2**24 + ...
<p>Type casting and promotion in numpy is fairly complicated and occasionally surprising. <a href="https://hackmd.io/NF7Jz3ngRVCIQLU6IZrufA" rel="nofollow noreferrer">This recent unofficial write-up by Sebastian Berg</a> explains some of the nuances of the subject (mostly concentrating on scalars and 0d arrays).</p> <p...
python|arrays|numpy|integer|numpy-ndarray
3
367,716
58,221,268
Count number of repeated elements in a row in a numpy array
<p>I'm looking for a quick way to do the following: Say I have an array </p> <pre><code>X = np.array([1,1,1,2,2,2,2,2,3,3,1,1,0,0,0,5]) </code></pre> <p>Instead of a simple frequency of elements I'm looking for the frequency in a row. So first 1 repeats 3 times, than 2 5 times, than 3 2 times , etc. So if <code>freq...
<p>Here's one NumPy way for performance efficiency -</p> <pre><code>In [14]: m = np.r_[True,X[:-1]!=X[1:],True] In [21]: counts = np.diff(np.flatnonzero(m)) In [22]: unq = X[m[:-1]] In [23]: np.c_[unq,counts] Out[23]: array([[1, 3], [2, 5], [3, 2], [1, 2], [0, 3], [5, 1]]) </code...
python|arrays|numpy
4
367,717
58,276,632
Is it bad practice to have more than 1 geometry column in a GeoDataFrame?
<p>I'm trying to create a GeoDataFrame with 2 zip codes per row, whose distances from each other I want to compare. I took a list of approx 220 zip codes and ran an itertools combination on them to get all combo's, then unpacked the tuples into two columns</p> <pre><code>code_combo = list(itertools.combinations(df_wit...
<p>Looking at the <code>__init__</code> method of a GeoDataFrame at <a href="https://github.com/geopandas/geopandas/blob/master/geopandas/geodataframe.py" rel="nofollow noreferrer">https://github.com/geopandas/geopandas/blob/master/geopandas/geodataframe.py</a>, it looks like a GDF can only have one column at a time. T...
gis|polygon|series|geopandas|shapely
3
367,718
58,525,908
How to train features in different scales in deep learning model
<p>I'm new in deep learning and I built a very simple model to try to train my data. I have two features input: <code>sex</code> and <code>age</code>. <code>sex</code> is <code>0</code> or <code>1</code> and <code>age</code> is between <code>25</code> and <code>60</code>. Output is just <code>0</code> means this person...
<p><strong>An alternative.</strong></p> <p>If the age has discrete values in the range <code>(25-60)</code>, then one possible way would be to learn embeddings for those two attributes, <code>sex</code> and <code>age</code>.</p> <p>For example,</p> <pre><code>class Net(nn.Module): def __init__(self): sup...
python|deep-learning|pytorch
0
367,719
58,403,855
Cleanse survey data and sum the responses to be in a python dataframe
<p>Columns of my dataframe are the survey questions and the rows are the responses. The unique response choices were (1 - Strong Disagree, 2 - Disagree, 3 - Neutral, 4- Agree, 5- Strongly Agree). The rows have all the respondents selections and I ideally would like the columns to be the unique response choices with a s...
<p>This is a bit quick and dirty but it might help</p> <p><strong>EDIT</strong> Updated to transform the tally into a pandas data frame </p> <p>Setup example dataframe</p> <pre><code>df = pd.DataFrame ({ 'question_1' : ['1 - strongly agree','1 - strongly agree','2 - agree'], 'question_2' : ['3...
python|pandas|dataframe|pandas-groupby|survey
1
367,720
58,301,646
Train with target data generated within the model
<p>How can I get the loss function used by <code>tf.keras.Model.fit(x, y)</code> to compare two outputs within the graph instead of one output with externally supplied target data, <code>y</code>?</p> <p><a href="https://i.stack.imgur.com/dbNcY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dbNcY.p...
<h2>1 - Easy, best - maybe not good for memory</h2> <p>Why not just get the expected items for the loss already?</p> <pre><code>new_y_train = non_trainable_ops_model.predict(original_y_train) nn_model.fit(x_train, new_y_train) </code></pre> <p>This sounds definitely the best way if your memory can handle this. Si...
tensorflow|keras|tf.keras
2
367,721
58,255,039
MultiWorkerMirroredStrategy() not working on Google AI-Platform (CMLE)
<p>I'm getting the following error while using <strong>MultiWorkerMirroredStrategy()</strong> for training Custom Estimator on Google AI-Platform (CMLE). </p> <pre><code>ValueError: Unrecognized task_type: 'master', valid task types are: "chief", "worker", "evaluator" and "ps". </code></pre> <p>Both <strong>MirroredS...
<p>I got into same issue. As far I understand MultiWorkerMirroredStrategy config values are different from other strategies and from what CMLE provides by default: <a href="https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras#multi-worker_configuration" rel="nofollow noreferrer">https://www.tensorflo...
tensorflow|google-cloud-platform|google-cloud-ml|tensorflow-estimator|gcp-ai-platform-training
2
367,722
58,505,920
How do I create a column in this Dataframe using Pandas?
<p>I have a dataframe that has comma separated values as the row content. Now I want to choose the first character of the content from each row and create a column out of those. <a href="https://i.stack.imgur.com/0XqSI.png" rel="nofollow noreferrer">Dataframe Image</a></p> <p>For example, the first value of each row i...
<p>If your comma separated values were in a .csv file to begin with the easiest way is:</p> <pre><code>df = pd.read_csv('name.csv') </code></pre> <p>This way you get a dataframe with all the desired columns. To access a single columns just use</p> <pre><code>df['first column name'] </code></pre> <p>If you created t...
python|pandas|dataframe
0
367,723
58,512,113
How to count class label frequency in a data frame using pandas?
<p>I have a data frame like this what is the easy method to count class label frequency of a particular class using the panda's data frame. </p> <pre><code>index f1 f2 f3 f4 f5 f6 class_label 0 4 4 2 3 3 1 0 1 1 4 2 1 3 1 0 2 4 1 2 1 3 1 0 3 2...
<p>Try using <a href="https://www.w3resource.com/pandas/series/series-value_counts.php" rel="nofollow noreferrer">value_counts</a>. It's a useful way Pandas has to compute the frequency count.</p> <p>As simple as <code>index.value_counts()</code>.</p>
python|pandas|dataframe
0
367,724
58,493,568
Pandas grouping extremely slow for aggregations min and max
<p>I have dataframe with datetime index, and shape:</p> <pre><code>df.shape (311885, 38) </code></pre> <p>Aggregate functions .sum(), .mean() and .median() work fine:</p> <pre><code>%%time df.groupby(pd.Grouper(freq='D')).mean() CPU times: user 77.6 ms, sys: 16 ms, total: 93.7 ms Wall time: 92.7 ms </code></pre> <p...
<p>As Quang Hoang pointed out in comment, I had string column which caused .min() and .max() to be slow. Without it, everything is fast.</p>
python|pandas
1
367,725
58,211,251
AttributeError: 'Series' object has no attribute 'to_numeric'
<p>I'm trying to sort dataframe by values. got an AttributeError: 'Series' object has no attribute 'to_numeric'. version '0.20.3', so to numeric should work, but not. Please help. </p> <pre><code>import pandas as pd tables = pd.read_html("https://www.sec.gov/Archives/edgar/data/949012/000156761919015285/xslForm13F...
<pre><code>import pandas as pd tables = pd.read_html("https://www.sec.gov/Archives/edgar/data/949012/000156761919015285/xslForm13F_X01/form13fInfoTable.xml") len(tables) ren=tables[3] ren.drop(ren.index[[0,1,2]], inplace=True) ren[3] = pd.to_numeric(ren[3], errors='coerce') ren.sort_values([3],ascending=False, inplace=...
pandas|dataframe
3
367,726
58,348,656
Specific linear classifier in TensorFlow: input element as vector
<p>How can I implement such linear classifier in TensorFlow:</p> <pre><code>x1*w1 + x2*w2 + x3*w3 = y_pred, </code></pre> <p>where x1, x2, x3 - vectors and w1, w2 and w3 - scalars?</p> <p>I have nice tutorial for case where x1, x2, x3 - scalars (<a href="https://www.easy-tensorflow.com/tf-tutorials/linear-models/lin...
<p>This question is ill-posed. You say you want x_1, x_2, x_3 to be vectors, however it's not clear what you would do with w_1, w_2, w_3. There are two possibilities.</p> <ul> <li><p>If you want to keep them as <em>scalars</em>, as your question seems to imply, then the model is not really a vector model, you're just d...
python|tensorflow|logistic-regression|multilabel-classification
2
367,727
58,478,230
How to return match with a string that contains parentheses in pandas?
<p>I have part of my code extracting an element from a column <code>Ranks</code> by matching a string <code>name</code> with elements in another column <code>Names</code>:</p> <p><code>rank = df.loc[df['Names'].str.contains(name), 'Ranks'].iloc[0]</code></p> <p>The code is working as intended except for some few case...
<p>If you use <code>str.contains</code>, you need to escape <code>'('</code> and <code>')'</code> in <code>name</code> because they are special chars in regex as follows</p> <pre><code>name = 'Banana \(1998\)' df['Names'].str.contains(name) Out[655]: 0 False 1 True 2 False Name: Names, dtype: bool df.loc[d...
python|pandas
6
367,728
58,467,111
How to update numpy array based based on coordinates
<p>I have an image that is given as below, which I am trying to convert into a binary image. </p> <p>To convert this image into a binary image, I did:</p> <pre><code>image[image &gt; 0] = 255 </code></pre> <p>This creates a binary image with colored region having only white pixels. But I also want to convert the pix...
<p>If I understood correctly your problem a more elaborated approach should be taken to get the desired result.</p> <p>First of all the approach to use a simple threshold creates a noisy approach.</p> <p>I used a modified image of your sample:<br> <a href="https://i.stack.imgur.com/xlo1z.jpg" rel="nofollow noreferrer...
python|numpy|opencv|computer-vision
2
367,729
69,206,148
make df from matching columns
<p>I have 2 dataframes df1 and df2 having columns as <code>df1['date','customer_id','category_name']</code> and <code>df2['date','customer_id','category_name']</code>. I want values from df1 which matches in df2 on columns 'customer_id' &amp; 'category_name'.</p> <p>So I tried this:</p> <pre><code>df_final = df1[(df1['...
<p>Try using <code>merge</code></p> <pre><code>df_final = pd.merge(df1, df2, on=[&quot;customer_id&quot;, &quot;category_name&quot;], how=&quot;left&quot;) </code></pre>
python|pandas|dataframe
0
367,730
69,080,342
Creating a new column in one dataframe by selecting from another dataframe
<p>I have one dataframe that contains daily sales, but it contains hundreds of rows for each date due to some categorical grouping. Below is a rough idea of the dataframe structure.</p> <pre><code>2021-05-04 A 56 2021-05-04 B 40 2021-05-05 B 40 2021-05-07 A 20 </code></pre> <p>I have another dataframe that cont...
<p>Just join the datasets on the date: <code>df1.merge(df2)</code></p>
python|pandas|dataframe
0
367,731
69,105,479
What's the best way to set the diagonals of a particular dimension to 1?
<p>Let's say I have a tensor:</p> <pre><code>q = np.arange(5*3*3).reshape(5,3,3) </code></pre> <p>I want to set the 3x3 diagonals to be 1, across axis 0 (i.e. where <code>j=k</code>).</p> <p>I thought this should do it:</p> <pre><code>np.apply_along_axis(lambda x: np.fill_diagonal(x,1), 0, q) </code></pre> <p>but it do...
<p>Using the same index array in both dimensions selects a diagonal:</p> <pre><code>In [13]: q = np.arange(5*3*3).reshape(5,3,3) In [14]: i=np.arange(3) In [15]: q[:,i,i] Out[15]: array([[ 0, 4, 8], [ 9, 13, 17], [18, 22, 26], [27, 31, 35], [36, 40, 44]]) In [16]: q[:,i,i]=1 In [17]: q Ou...
python|numpy
2
367,732
69,020,579
Filter based on pairs within a group - if value represent at the end
<pre><code>Group Code 1 2 1 2 1 4 1 1 2 4 2 1 2 2 2 3 2 1 2 1 2 3 </code></pre> <p>Within each group there are pairs. In Group 1 for example; the pairs are (2,2),(2,4),(4,1)</p> <p>I want to filter these pairs based on code number 2 OR 4 being present at the END ...
<p>Using your own suggested code, you can modify it to achieve your goal:</p> <pre><code>idx = df.groupby(&quot;Group&quot;)['Code'].shift(-1).isin([2,4]) df[idx | idx.shift()] </code></pre> <p>First you groupby <code>'Group'</code> and then <code>shift</code> one up and check for values 2 or 4. Finally, you want both ...
python|pandas|dataframe|numpy|filter
2
367,733
69,197,673
Error while loading excel file into pandas : xlrd.biffh.XLRDError: Workbook is encrypted
<p>I am downloading a file using python and read it. But while reading the xls file it throws <code>xlrd.biffh.XLRDError: Workbook is encrypted</code> I am able to open the file manually but not in python</p> <p>My code</p> <pre><code>df = pd.read_excel(filepath) </code></pre> <p>Can somebody help me on this! . I have...
<p>XLRD is not capable of handling file with encryption on it's own, but there is another Python library that actually can unencrypt a lot of MS Office files including the one you are trying to read .xls. It's called <a href="https://github.com/nolze/msoffcrypto-tool" rel="nofollow noreferrer">msoffcrypto-tool</a></p>
python-3.x|pandas
1
367,734
68,886,210
How can I use Python and Pandas to parse through text and return the strings I want in separate data cells?
<p>So I have compiled a list of NFL game projections from the 2020 season for fantasy relevant players. Each row contains the team names, score, relevant players and their stats like in the text below. The problem is that each of the player names and stats are either different lengths or written out in slightly differe...
<p>You can get split the full string using the '-' (dash/minus sign) as the separator. Then use indexing to get different parts.</p> <p>Using <code>str.split(sep='-')[0]</code> gives you the name. Here, the <code>str</code> would be the row, for example <code>M.Trubisky- 234/2TDs</code>.</p> <p>Similarly, <code>str.spl...
python|pandas|string|parsing
0
367,735
69,262,652
Pytorch function calling
<p>I am trying to compute a trignometric function using pytorch, but having issues while calling it via function, below is my code:-</p> <pre><code>def func(x,y): return torch.exp(torch.sin(x)/x-y) func(torch.tensor[2,3]) Error:- TypeError - Traceback (most recent call last) &lt;ipython-input-16-beb818f912f5&gt; ...
<p>You need to do it with unpacking:</p> <pre><code>func(*torch.tensor[2,3]) </code></pre>
python|pytorch
1
367,736
69,072,391
how to fill the missing values where start date has been first day of month?
<p>i have dataframe like this:</p> <pre><code>tst= Date % on Merchant % on Customer Merchants Location 2021-08-04 0.0 0.10 Zwarma - The Shawarma Maker Palani 2021-08-05 0.0 0.10 Zwarma - The Shawarma Maker Palani 2021-08-06 0.0 0.10 Zwarma - The Shawarma Maker Palani 2021-08-01 0.0 0.12 ...
<ul> <li>create date range for days at bringing of month for <strong>Merchants</strong> where they are missing</li> <li>outer join to original data frame and <code>fillna(method=&quot;bfill&quot;)</code></li> </ul> <pre><code>import pandas as pd import io df = pd.read_csv(io.StringIO(&quot;&quot;&quot;Date % on Mer...
python|pandas|pandas-groupby|data-science|pandas-resample
0
367,737
69,104,317
How to properly write if-then lambda statement for pandas df?
<p>I have the following code:</p> <pre><code>data = [[11001218, 'Value', 93483.37, 'G', '', 93483.37, '', '56117J100', 'FRA', 'Equity'], [11001218, 'Value', 3572.73, 'G', 3572.73, '', '56117J100', '', 'LUM', 'Equity'], [11001218, 'Value', 89910.64, 'G', 89910.64, '', '56117J100', '', 'WAR', 'Equity'],...
<p>You can modify the function a bit to perform on a chunk/slice of a dataframe, based on group using <code>groupby</code> since you are performing the action per group. A modified version of the function you have written would look something like this:</p> <pre class="lang-py prettyprint-override"><code>def logic_buil...
python|pandas|if-statement|lambda|apply
0
367,738
69,018,462
Pandas: number of rows where df['A'] == df['B'] or df['B'] == []
<p>Consider following dataframe <code>df</code> with columns <code>A</code> and <code>B</code>. I am trying to find the number of rows where <code>df['A'] == df['B']</code> or <code>df['B'] == []</code>. How can I do this?</p> <pre><code> A B m:QueryId 970000000 [0, 1,...
<p>Try with :</p> <pre><code>df[df['A'].eq(df['B'])|~df['B'].astype(bool)] </code></pre> <p>For count of such rows:</p> <pre><code>(df['A'].eq(df['B'])|~df['B'].astype(bool)).sum() </code></pre>
python|pandas|dataframe|slice
2
367,739
68,942,953
Python Pandas df issue: "bound method NDFrame.head of Empty DataFrame"
<p>I'm building an empty dataframe for a basic calendar table, then populating with pd.date_range values in one column. The problem is the dataframe comes up as empty after append. Here's my code:</p> <pre><code>def date_calendar(table, startdate, enddate, datefreq): # create a df df = pd.DataFrame({ 'Year': [...
<p>When appending series to df, you need to assign the result back to <code>df['Date']</code>.</p> <pre><code>def date_calendar(startdate, enddate, datefreq): # create a df df = pd.DataFrame({ 'Year': [], 'FY Year': [], 'Quarter': [], 'MonthNum': [], 'Yea...
python|pandas|dataframe
1
367,740
69,096,902
How can I concatenate the slicing window data for different trials during time series data preparation?
<p>I am preparing the time series data for LSTM training. I have time-series data for different participants and have sliced them using sliding windows. I was wonder how to concatenate them to form the final dataset for model training.</p> <pre><code>import numpy as np import tensorflow as tf participant1 = np.arange(...
<p>tf.concat needs tensor value, not dataset. For dataset:</p> <pre><code>dataset = input1.concatenate(input2) </code></pre>
python|tensorflow|time-series|lstm|data-preprocessing
1
367,741
68,929,785
How to apply mask to image tensors in PyTorch?
<p>Applying mask with NumPy or OpenCV is a relatively straightforward process. However, if I need to use masked image in loss calculations of my optimization algorithm, I need to employ exclusively PyTorch, as doing otherwise interferes with gradient computations. Assuming that I have an image tensor <code>[1, 512, 512...
<p>First of all, the definition of the function <code>selective_mask</code> is far for what You may call 'straightforward'. The key point in using numpy (and torch, which is designed to be mostly compatible) is to take advantage of the vectorization of operations and to avoid using loops, which are not parallelizable.<...
python|image|numpy|machine-learning|pytorch
2
367,742
69,016,846
Plot HIST of a pandas DataframeGroupbySeries
<p>I'm working with a small dataframe with this <a href="https://content.codecademy.com/PRO/paths/data-science/python-portfolio-project-starter-files.zip" rel="nofollow noreferrer">codecademy: data</a></p> <p>I'm trying to print data to make a small analysis with the following code:</p> <pre class="lang-py prettyprint-...
<ul> <li>To produce a histogram for each column based on gender: <ul> <li><code>'children'</code> and <code>'smoker'</code> look different because the number is discrete with only 6 and 2 unique values, respectively.</li> <li><code>data.groupby('sex').hist(layout=(1, 4), figsize=(12, 4), ec='k', grid=False)</code> alon...
python|pandas|matplotlib|seaborn|histogram
1
367,743
68,917,921
Converting object type column to float type converts all to Nan?
<p>While converting my object type columns to Float type, all my values are turned to Nan.</p> <p>I checked the dtype of columns post conversion which shows all are float type. Hence succesful in that regard. <strong>But Why does it produces Nan values</strong>.</p> <p>This is the code I'm using. Both versions of code ...
<p><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 parameter <code>errors='coerce'</code> returns <code>NaN</code> with invalid parsing for entries that can't be converted to float values:</p> <p><a href="https://p...
python|pandas|object
3
367,744
69,295,817
Why do you multiply the two images to see the correlation?
<p>I have some questions about the CP Viton module:</p> <pre><code>feature_A = feature_A.transpose(2,3).contiguous().view(b,c,h*w) feature_B = feature_B.view(b,c,h*w).transpose(1,2) # perform matrix mult. feature_mul = torch.bmm(feature_B,feature_A) print(feature_mul.size()) #torch.Size([4, 192, 192]) </code></pre> <...
<p>The spatial correlation consists of computing the dot product of feature vectors of every <code>(feature_A[k,:,i], feature_B[k,:,j])</code> feature pair. As such you first need to flatten the spatial dimension which results in a dimension of size <code>h*w</code> on both tensors. Your two operands will have a shape ...
image|pytorch|correlation
0
367,745
68,909,283
How to customize pandas pie plot with labels and legend
<p>Tried plotting a pie chart using:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np data = {'City': ['KUMASI', 'ACCRA', 'ACCRA', 'ACCRA', 'KUMASI', 'ACCRA', 'ACCRA', 'ACCRA', 'ACCRA'], 'Building': ['Commercial', 'Commercial', 'Industrial', 'Commercial', 'Industrial', 'Commer...
<ul> <li><code>legend=True</code> adds the legend</li> <li><code>title='Air Termination System'</code> puts a title at the top</li> <li><code>ylabel=''</code> removes <code>'Air Termination System'</code> from inside the plot. The label inside the plot was a result of <code>radius=1.5</code></li> <li><code>labeldistanc...
python|pandas|matplotlib|pie-chart
3
367,746
69,147,788
Weights & Biases with Transformers and PyTorch?
<p>I'm training an NLP model at work (e-commerce SEO) applying a <code>BERT</code> variation for portuguese language (<code>BERTimbau</code>) through <code>Transformers</code> by Hugging Face.</p> <p>I didn't used the <code>Trainer</code> from Transformers API. I used <code>PyTorch</code> to set all parameters through ...
<p>Scott from W&amp;B here. Although you're not using the <a href="https://docs.wandb.ai/guides/integrations/huggingface" rel="nofollow noreferrer">HuggingFace WandbCallback</a>, you can still take advantage of <code>wandb</code> easily using our Python API.</p> <p>All you need to do is call <code>wandb.log({'val_loss'...
python|google-cloud-platform|pytorch|huggingface-transformers|wandb
1
367,747
69,291,709
Multiply every item in a column in pandas with another df generating new columns
<p>I'm trying to multiply every column in a dataframe like so:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>col1</th> <th>...</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>1</td> <td>...</td> </tr> <tr> <td>1</td> <td>1</td> <td>...</td> </tr> <tr> <td>...</td> <td>...</td> <...
<p>This is an idea to take advantage of matrix multiplication for speed. The order of the columns is a bit different than what you wanted, but hopefully this is still useful</p> <pre><code>import pandas as pd import itertools import scipy as scp # Create a large matrix, A, to multiply df1 against # Df1*A = Y # # Y nee...
python|pandas|dataframe|numpy
1
367,748
68,936,169
How to prune the k% lowest weight by pytorch?
<p>Here I learn from the paper called Deep compression [Han et. al.] using resnet18</p> <p>I also work the following code, the weight times the mask so that it is the after_weight pruned by the k% lowest weight to zero. But that code doesn't work for me. Any efficient solution?</p> <pre><code>prune = float(0.1) def pru...
<p>You can use <a href="https://pytorch.org/tutorials/intermediate/pruning_tutorial.html" rel="nofollow noreferrer"><code>torch.nn.utils.prune</code></a>.</p> <p>It seems you want to remove 10% of every <code>Conv2D</code> layer. If that is the case, you can do it this way:</p> <pre class="lang-py prettyprint-override"...
python|pytorch|pruning
1
367,749
69,089,817
Combining two dataframes using buffer in geopandas
<p>I have two dataframes (not exact data but similar): df1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Lon</th> <th>Lat</th> <th>Timestamp</th> </tr> </thead> <tbody> <tr> <td>4.44</td> <td>61.41</td> <td>2021-04-28 00:00:00</td> </tr> <tr> <td>4.48</td> <td>62.45</td> <td>2021-04-28 0...
<ul> <li>there's not much within 100m in the sample dataset. Increasing distance mean more <code>sjoin()</code></li> <li>using <strong>GeoPandas</strong> capability with CRS and <code>buffer()</code>. It's import that a UTM geometry is used for distances. Hence projection to UTM and back to EPSG:4326</li> <li>have sh...
python|pandas|geopandas
2
367,750
69,096,945
Import torch ModuleNotFoundError
<p><a href="https://i.stack.imgur.com/uuGJ5.png" rel="nofollow noreferrer">enter image description here</a></p> <p>the import torch in my Jupiter notebook is not work, but in my terminal is works fine.</p>
<p>This looks like an interpreter configuration problem, your jupyter notebook is maybe using another interpreter while your terminal is using another. For eg, if you are using anaconda the default env is (base), so to add a certain module to your environment, you go to anaconda prompt and do this:</p> <pre><code>$ con...
python|visual-studio|jupyter-notebook|pytorch
0
367,751
68,920,854
I can't find any grammatical errors
<p><a href="https://i.stack.imgur.com/fpf5a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fpf5a.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/RrbSQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RrbSQ.png" alt="enter image description h...
<p>I don't have enough reputation to write a comment so I just write my finding here.</p> <p>You are missing a close bracket in the line <code>history = model.fit_generator(...)</code> , the line before the return statement</p>
tensorflow
0
367,752
69,291,526
Dataframe comes out with only one column
<p>First of all apologies for my lack of coding knowledge here!! Any pointers would be greatly appreciated!!</p> <p>This is the code I have written to read the data from NDBC weather buoy 41049. My plan here is to get the data which works, clean out the spaces and replace them with commas and then create a dataframe ...
<p>Pandas can read directly from a url. And is prepared to read white separated columns with one or many spaces. Besides that you may want to skip the first row in the file:</p> <pre><code>import pandas as pd data = pd.read_csv( &quot;https://www.ndbc.noaa.gov/data/realtime2/41049.spec&quot;, delim_whitespace=...
python|pandas|beautifulsoup
1
367,753
68,923,534
Fill NaN with distinct known values within the column
<p>I have a dataframe that has a column that is labeling a location. The table looks like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Don't Care</th> <th>Id</th> <th>Dont Care</th> </tr> </thead> <tbody> <tr> <td>x</td> <td>123</td> <td>x</td> </tr> <tr> <td>x</td> <td>nan</td> <td...
<p>if you're using a pandas dataframe</p> <p>then use</p> <pre class="lang-py prettyprint-override"><code>df = df.fillna(method=&quot;ffill&quot;) </code></pre>
python|pandas
0
367,754
69,003,144
invalid index to scalar variable error in solve of system of 5 ode in python
<p>I wrote the following code to solve 5 differential equations in Python. But I get the following error: invalid index to scalar variable I was very tried and searched, but I did not find that where is it? Can anyone tell me where should I fix?</p> <pre><code>from scipy.integrate import odeint import numpy as np impor...
<p>The problem is this line in the function <code>ode</code>:</p> <pre><code> x = x[2] </code></pre> <p>You have reassigned the variable <code>x</code>, so after this statement is executed, <code>x</code> is the scalar that had been stored in the original array <code>x</code>. You'll have to use a different name fo...
python|numpy|jupyter|ode|triangular
2
367,755
69,263,970
Pandas create a new column containing calculated results, applied onto mutliple columns
<p>I need some help to modify my function and how to apply it in order to iterate an ifelse condition through multiple features.</p> <p>Suppose we have the following table <code>t1</code></p> <pre><code>import pandas as pd names = {'name': ['Jon','Bill','Maria','Emma'] ,'feature1': [2,3,4,5] ,'feature...
<p>I think here is best avoid loops, use <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a> for test and assign mask only for selected columns from list, for pass function with input <code>DataFrame</code> is used <a href="http://pandas.p...
python|pandas
1
367,756
69,266,639
How to compute distance for a matrix and a vector?
<p>In python, given one matrix of size <code>2*3</code> like <code>A=[[x11,x12,x13],[x21,x22,x23]]</code> and a column vector <code>b=[mu1;mu2]</code>. If I want to compute the Euclidean distance between each column of <code>A</code> and vector <code>b</code>. For example, for the first column, the distance 'd1` is giv...
<p>You can use point-wise substraction, then square and sum the two columns:</p> <pre><code>&gt;&gt;&gt; np.sum((A-b)**2, 1) </code></pre> <p>As noted by <a href="https://stackoverflow.com/users/6400526/gilad-green">@Gilad Green</a>, if <code>b</code> is shaped <code>(n, 1)</code> then a transpose will be required:</p>...
python|numpy|distance
2
367,757
69,150,912
vlookup equivalent to fill existing table using pandas
<h3>Scenario:</h3> <ul> <li>there are more than three pivot table in python</li> <li>one existing table in which i want to fill value as per row and and as per column from different pivot table</li> </ul> <p>I made sample in excel ,want to automate in python. (In python using pivot After making pivot column name change...
<p>Use <code>reduce</code> and <code>pd.merge</code>:</p> <pre><code>import pandas as pd from functools import reduce names = ['Ni', 'Pi', 'Si'] df = reduce(lambda piv1, piv2: pd.merge(piv1.loc[piv1['Name'].isin(names)], piv2, on='Name', how='left'), [pivot1, pivot2...
pandas|join|vlookup
0
367,758
69,098,847
how to load dictionary from npy file efficiently in Python
<p>I have a file in .npz format. Data stored in dictionary formatlooks like:</p> <pre><code>{'ffa7e85e21c9000215574a8e2c24c30d': array([[ 0.07772359, 0.04581502, -0.00930751, ..., -0.05222392, 0.02600432, 0.00974964], [ 0.1211272 , -0.0978327 , 0.01816959, ..., -0.02647112, -0.02802687, -0...
<p>I suggest you use python's context manager <code>with</code>:</p> <pre class="lang-py prettyprint-override"><code>with np.load('file.npz') as d: k = d.keys() v = d.values() </code></pre>
python|python-3.x|numpy|dictionary|npz-file
0
367,759
68,987,018
How do you split a row into multiple rows based on delimiter and have them tie back to another column as key:value pairs?
<p>Stack community!</p> <p>I have a CSV file where 1 row contains messy data coming from another data source. Example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Packet number</th> <th style="text-align: left;">Actions</th> </tr> </thead> <tbody> <tr> <td styl...
<p>It appears that there are some formatting errors in your sample data, but assuming that these are indeed formatting errors, I reckon the following should work.</p> <p>First, <code>.explode()</code> the DataFrame on the 'data' column, resulting in separate lines for each action per ID.</p> <p>Then, each of these line...
python|pandas
0
367,760
69,074,224
pandas: Sum group by month from given day
<p>I have the dataframe below by day, i want to sum group by month . How can i do it please?</p> <pre><code>date, Revenue, Fourniture 2021-07-01, 200, 5 2021-07-08, 300, 12 2021-08-01, 400, 10 2021-08-18, 200, 12 2021-08-30, 100, 10 2021-08-31, 400, 5 </code></pre> <p><strong>Expected output</strong></p> <pre><code>202...
<p>You can group by year-month by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>.groupby()</code></a> and take the sum by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.sum.html#pandas.c...
python|pandas
1
367,761
69,033,140
TypeError: 'DataFrame' object is not callable using Pandas in Python
<p>I have a question…</p> <p>I’ve programmed these:</p> <pre><code># Dependencies import pandas as pd from numpy import where from matplotlib import pyplot # Load Data names = [“Frequency”,”Comments Count”,”Likes Count”,”Text nwords”] dataset = pd.read_csv(“Posts.csv”, encoding=”utf-8″, sep=”;”, delimiter=None, names...
<p>By doing this:</p> <pre class="lang-py prettyprint-override"><code>dataset = pd.read_csv(“Posts.csv”, encoding=”utf-8″, sep=”;”, delimiter=None, names=names, delim_whitespace=False, header=0, engine=”python”) </code></pre> <p>You are creating a pandas DataFrame that is read from the CSV file and stored in the variab...
python|pandas|dataframe|cluster-analysis
1
367,762
68,952,597
How can I convert a datatime into a time decimal in Python, in a dataframe?
<p>I have two columns, Picking End Time and Picking Start Time.</p> <p><strong>First I converted them to datetime</strong></p> <pre class="lang-py prettyprint-override"><code>data['Picking Start Time'] = pd.to_datetime(data['Picking Start Time']) data['Picking End Time'] = pd.to_datetime(data['Picking End Time']) </cod...
<p>First remove:</p> <pre><code>data['Picking Time'] = data['Picking Time'].astype(str).map(lambda x: x[7:]) </code></pre> <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.total_seconds.html" rel="nofollow noreferrer"><code>Series.dt.total_seconds</code></a> and if necessary di...
python|pandas
1
367,763
69,030,054
Add a column matching other two columns, one contains representative values
<p>I have three data frames as follows:</p> <pre><code>df1 col1 CAND_SNP 1 a1 1 a2 1 a3 1 a4 2 b1 3 c1 3 c2 3 c3 df2 col1 LEAD_SNP 1 a1 2 b1 3 c1 df3 snp col2 a3 x1 a21 x2 a31 x3 a41 x4 b11 x5 c11 x6 c21 x7 c31 x8 </code></pre> <p>I need to ma...
<p>If I understand correctly, you can group <code>df1</code> by <code>col1</code> and look up whether a value of <code>col2</code> exists in <code>col1</code> of <code>df3</code>. Then merge with <code>df2</code>:</p> <pre><code>df1['col3'] = df1.groupby('col1')['CAND_SNP'].apply(lambda s: s.isin(df3['snp'])) df2 = df2...
python|pandas
2
367,764
69,081,227
Create a simple PyTorch neural network with a normalized weights
<p>I want to create a simple PyTorch neural network with the sum of its weights equal to <code>1</code>. To understand my question here is a to give an example:</p> <p><a href="https://i.stack.imgur.com/mIrUA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mIrUA.jpg" alt="enter image description here...
<p>You can simply normalize by the sum of all initialized weights:</p> <pre><code>&gt;&gt;&gt; layer = nn.Linear(4, 1, bias=False) &gt;&gt;&gt; layer.weight Parameter containing: tensor([[-0.2565, 0.4753, -0.1129, 0.2327]], requires_grad=True) </code></pre> <p>Normalize <code>layer.weight</code>:</p> <pre><code>&gt;&...
neural-network|pytorch
0
367,765
68,906,059
How to plot a zero-one 2d matrix that will look like a scatter?
<p>Might be a strange question, but I am wondering if it's possible to replace a 2d matrix made up of ones and zeros with a scatter plot of say, black dots where all the ones are but nothing for zeros:</p> <p>Unfortunately I don't have the best reproducible answer, but I have a 2D array made up for zeros and ones (size...
<p>Here's what I would do. I didn't plot all the points to reduce the computational demand of creating the figure. you might want to do that if you have a lot of points to plot. either way, you can change that according to your need.</p> <pre><code>import numpy as np from matplotlib import pyplot as plt np.random.seed(...
python|numpy|matplotlib|jupyter
1
367,766
69,218,408
every element is 1x1 matrix in python, How do i make it so that every element is not seperate?
<p>print(s0[3][0][0]) gives me 1</p> <p>but print(s0[3][0]) gives me [1]</p> <p>how do i make it so that print(s0[3][0]) gives me 1?</p> <p>S0 is a numpy matrix of 100 rows</p> <pre><code>S0 = [[[ 1. ] [-0.91903376] [ 0.18724527]] [[ 1. ] [ 0.87834638] [-0.88794145]] [[ 1. ] [-0.7532...
<p>Take some time to read <code>numpy</code> basics. The key here is <code>shape</code>. You have a 3d array:</p> <pre><code>In [122]: arr = np.arange(9).reshape(3,3,1) In [123]: arr Out[123]: array([[[0], [1], [2]], [[3], [4], [5]], [[6], [7], [8]]]) I...
python|numpy|machine-learning
1
367,767
69,255,421
Python numpy methods/attributes faster than numpy functions?
<p>I recently noticed that some <code>numpy</code> array attributes/methods seem to be significantly faster than the corresponding <code>numpy</code> functions. Example for <code>np.conj(x)</code> vs. <code>x.conjugate()</code>:</p> <pre><code>import numpy as np import time np.random.seed(100) t0_1 = 0 t0_2 = 0 for i...
<p><code>numpy</code> functions often delegate the action to a method, if it exists. But they must also check that the argument is an array, and so on. <code>ufuncs</code> also have some extra 'baggage' that handles parameters like <code>out</code>, <code>where</code>. So time differences don't (necessarily) scale w...
python|function|performance|numpy|methods
3
367,768
69,209,722
Is there a way to create a dataframe for each unique value in a pandas column and then write each one to a different sheet in the same Excel file?
<p>I'm working with a dataset that contains a count of the number of vehicles passing by a sensor each hour over the course of several days. A subset of the data is below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>SET NAME</th> <th>DIRECTION</th> <th>DATE INTERVAL</th> <th>START TIME<...
<p>As jfaccioni said in their comment it was simply due to the slashes in the date column</p> <pre><code>with pd.ExcelWriter(&quot;combined_count.xlsx&quot;) as writer: for date, data in combined_count.groupby('DATE'): data.to_excel(writer, sheet_name = date.replace('/', '_')) </code></pre> <p>The above cod...
python|excel|pandas
0
367,769
69,274,269
Matplotlib - Show only data that are above a certain value
<p>I am using <em>Matplotlib</em> and <em>Pandas</em> to plot data.</p> <p>However, I want to show on the graph only data that are above a certain value.</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas as pd # Importing the data using Pandas BE = pd.read_csv(&quot;BE-4YRS...
<p>You can do it with:</p> <pre><code>BE_CFT_18to21 = BE_CFT_18to21[BE_CFT_18to21.percent &gt; 75] </code></pre>
python|pandas|matplotlib
0
367,770
69,267,788
How do convert from MMM-YYYY to YYYY-MM-DD, setting DD to the last day of month in a data frame?
<p>I have a similar question on date conversion using data frame.</p> <p>My data frame has two date string columns, <code>hiredate</code> and <code>end_date</code>, having different date formats, <code>DD-MMM-YYYY</code>and <code>MMM-YY</code>, respectively.</p> <p>The column <code>end_date</code> has no <code>DD</code...
<p>You can convert <code>end_date</code> to datetime according to the format <code>'%B-%y'</code> and add a <code>MonthEnd(0)</code> offset:</p> <p>Input data:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df empno ename hiredate end_date 0 1 sreenu 17-Jun-2021 May-22 </code></pre> ...
python|pandas|date-conversion
3
367,771
68,969,346
Count number of occurrences of first column value respectively across each row
<pre><code>data = [['BAL', 'BAL', 'NO', 'DAL'], ['DAL', 'DAL', 'TEN', 'SF']] df = pd.DataFrame(data) </code></pre> <p>I want to count the number of occurrences of the value in the first column in each row, across that row.</p> <p>In this example, the number of times &quot;BAL&quot; appears in the first row, &quot;DAL&q...
<p>We can compare the first column to all the remaining columns with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>DataFrame.eq</code></a> then <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.sum.html" rel="nofollow noreferrer"><co...
python|pandas|dataframe
3
367,772
69,116,857
Difference between tf.add() and tensorflow.keras.layers.Add()
<p>I have implemented a Deep Learning model (FCN-8s) in tensorflow and initially used <code>tf.add(x,y)</code> to perform the tensor addition. However, when plotting the architecture, the addition layers seem to be disconected from the rest <a href="https://i.stack.imgur.com/uBiu0.png" rel="nofollow noreferrer"><img sr...
<p><code>tf.add</code> and <code>tensorflow.keras.layers.Add</code> have different implementation methods.</p> <p>In <strong>gen_math_ops.py</strong> (a file generated by the system)</p> <p>tf.add</p> <pre><code>_result = pywrap_tfe.TFE_Py_FastPathExecute( _ctx._context_handle, tld.device_name, &quot;Add&qu...
tensorflow|deep-learning
1
367,773
69,223,974
what is the best way to modify a particular line of a csv file without erasing everything?
<p>I have a csv file open with notepad :</p> <p><a href="https://i.stack.imgur.com/K4IVk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K4IVk.png" alt="enter image description here" /></a></p> <p>I want to modify my csv to replace line 4 with 'Temperature Level Wave Degre':</p> <p><a href="https://i...
<p>Here is a solution using python, however as I mentioned in my comment, there are likely more efficient command line tools (I would use <code>awk</code>)</p> <pre><code>with open(filename, 'r+') as f: lines = f.readlines() # read lines and store in list lines[3] = 'Temperature Level Wav...
python-3.x|pandas|dataframe
1
367,774
69,193,587
for-loop doesn't give the expected results
<p>I have a pretty simple for loop which doesn't give the expected results. It runs through a ndarray column row-by-row and should categorize e.g. the statements ' Heavy Vehicle' or ' Car' to numeric values (I know they are also strings).</p> <pre><code>for k in range(0, data.shape[0]): if data[k, 1] == ' Car' or '...
<h2>String are also boolean objects in Python!</h2> <p>You are basically doing <code>False Or True</code>, so <code>True</code> for each cycle.</p> <p>Try this:</p> <pre><code>print(Bool(&quot;&quot;)) # Empty String is False print(Bool(&quot;String&quot;)) # Full String is True </code></pre> <p>You shoul...
python|numpy
4
367,775
69,175,925
Is there a way to apply a numpy function that takes two 1d arrays as arguments on each row of two 2d arrays together?
<p>I am trying to run something like:</p> <pre><code> np.bincount(array1, weights = array2, minlength=7) </code></pre> <p>where both <code>array1</code> and <code>array2</code> are 2d n numpy arrays of shape (m,n). My desired goal is that <code>np.bincount()</code> is run n times with each row of array1 and array2</p> ...
<p>A simple solution is simply to use <strong>comprehension lists</strong>:</p> <pre class="lang-py prettyprint-override"><code>result = [np.bincount(v, weights=w) for v,w in zip(array1, array2)] </code></pre> <p>Because the resulting arrays can have a different size (and actually do have a different size in your examp...
python|arrays|numpy
2
367,776
69,006,887
Return multiple values from a pandas rolling apply function
<p>I have a <code>function</code> that needs to return multiple values:</p> <pre><code>def max_dd(ser): ... compute i,j,dd return i,j,dd </code></pre> <p>if I have code like this that calls this function passing in a <code>series</code>:</p> <pre><code> date1, date2, dd = df.rolling(window).apply(max_dd) </co...
<p>Rolling apply can only produce single numeric values. There is no support for multiple returns or even nonnumeric returns (like something as simple as a string) from rolling apply. Any answer to this question will be a work around.</p> <p>That said, a viable workaround is to take advantage of the fact that <code>rol...
python|pandas|multiple-return-values
5
367,777
68,933,736
dataframe string type cannot use replace method
<pre><code>df = pd.DataFrame({'a': ['asdf']}, dtype=&quot;string&quot;) df[&quot;a&quot;].replace({&quot;a&quot;:&quot;b&quot;}, regex=True) not chagend df = pd.DataFrame({'a': ['asdf']}, dtype=&quot;object&quot;) df[&quot;a&quot;].replace({&quot;a&quot;:&quot;b&quot;}, regex=True) changed </code></pre> <p>I want to...
<p>If you see the difference by checking with <code>df.dtypes</code> it's evident that you r datatype is ultimately is an <code>object</code> but column is only string hence you need to apply <code>pandas.Series.str.replace</code> to get your results.</p> <p>However, when you choose <code>dtype=&quot;object&quot;</code...
python|pandas|string|dataframe
1
367,778
68,895,503
Python - Read a file with strings and integers
<p>I am trying to read a text file in Python containing 4 columns and several rows. This file has strings and floats. But once I load it, this file returns a 2d list that includes only one column of all items in string format. The output I would like is to have is exactly as the filedemo shows. Note: I need a way that ...
<p>It's unclear exactly what filedemo looks like. And I suspect your <code>split()</code> command should really be <code>split(',')</code>. So I'm assuming that filedemo is this:</p> <pre><code>name,name,name 1,2,3 name,name,name 4,5,6 other,other,other </code></pre> <p>And I'm assuming your problem with your <code>ope...
python|numpy-ndarray
2
367,779
69,117,389
Transform pandas DataFrames groups - completely, not just a Series
<p>I want to transform each group in a pandas' DataFrame. By group I mean not a single column of the DataFrame, but the entire group. Here is an example of what I mean:</p> <pre><code>df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar'], 'B' : ['one', 'one', 'two', 'two', 'one', 'two']...
<p>In your solution <code>transform</code> function working with each column separately, so not possible select columns by names. Need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>GroupBy.apply</code></a>:</p> <pre><code>df = ...
python|pandas|dataframe|method-chaining
1
367,780
68,915,447
Append matrices to a numpy array
<pre><code>testMat1 = np.array([[1,2,3,4],[4,5,6,7]]) testMat2 = np.array([[7,8,9,10],[10,11,12,13]]) testMat3 = np.array([[2,4,6,8],[3,5,7,9]]) </code></pre> <p>Here are three matrices of shape <code>(2, 4)</code></p> <p>How do I combine them into a multidimensional array with shape <code>(3, 2, 4)</code>?</p> <p><cod...
<p>You can use <code>np.vstack()</code> to vertically stack the arrays.</p> <p>In your case the command would look like this: <code>combined = np.vstack(([testMat1], [testMat2], [testMat3]))</code> which will give you the shape <code>(3, 2, 4) </code></p> <p>You can continuously add more arrays and update it by using:...
python|arrays|numpy|multidimensional-array|append
1
367,781
68,918,811
Fast pathfinding and distance matrix in 2d grid
<p><strong>Context:</strong> I'm working on a warehouse simulation that supports different floor designs and simulates one or multiple agents that are tasked with order picking. One order can consist of more than one product. The routing for picking products is solved as a capacitated <a href="https://en.wikipedia.org/...
<p>I know link-only answers are usually discouraged, but &quot;what algorithms can make A* faster&quot; is a hugely complicated topic that's been an active area of research nonstop for the past 50 years. So it's not really possible to give anything more than a vague summary in a Stackoverflow answer.</p> <p>For 2D grid...
python|numpy|path-finding
2
367,782
68,934,288
pd dataframe addings rows by id
<p>I have df with some ids, days number and running sum:</p> <pre><code>data = {'id': [0, 0, 0, 1, 1, 2, 1], 'day' : [0, 2, 1, 1, 4, 2, 2], 'running_sum': [1,4,2,1,6,6,3]} df_1 = pd.DataFrame(data) id day running_sum 0 0 0 1 1 0 2 4 2 0 1 2 3 1 1 1 4 1 4 6 5 2 2 6 6 1 2 ...
<p>Let's see if this logic is what you have in mind:</p> <p>Set <code>id</code> and <code>day</code> as index:</p> <pre><code>df_1 = df_1.set_index(['id', 'day']) </code></pre> <p>Build a new index to reindex <code>df_1</code> while introducing new numbers; luckily the index is unique, so reindex works fine:</p> <pre><...
python|pandas
3
367,783
69,214,313
Compare multiple string columns return different column
<p>I have a dataframe with four string columns</p> <pre><code>col1 col2 col3 col4 A. A. A. B. A. A. A. A. A. A. B. B. </code></pre> <p>Would like the response like this.</p> <pre><code>col1 col2 col3 col4 Changed A. A. A. B. B A. A. A. A. A. A. B. B. B </code>...
<p>Take the last column if not all values are identical:</p> <pre><code>df['Changed'] = df['col4'].mask(df.eq(df['col1'], axis=0).all(1), '') </code></pre> <p>Output:</p> <pre><code> col1 col2 col3 col4 Changed 0 A. A. A. B. B. 1 A. A. A. A. 2 A. A. B. B. B. </code></pre>
python|pandas|dataframe
1
367,784
44,691,778
Time difference in hours of a column of pandas dataframe
<pre><code>id time_taken 1 2017-06-21 07:36:53 2 2017-06-21 07:32:28 3 2017-06-22 08:55:09 4 2017-06-22 08:04:31 5 2017-06-21 03:38:46 </code></pre> <p><code>current_time = 2017-06-22 10:08:16</code></p> <p>i want to create df2 where time difference of time_taken columns is greater than 24 hours with cur...
<p>You can convert <code>Timedelta</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.total_seconds.html" rel="nofollow noreferrer"><code>total_seconds</code></a> and compare or compare with <code>Timedelta</code>, filter by <a href="http://pandas.pydata.org/pandas-docs/stable/ind...
python|pandas
1
367,785
44,403,916
(pandas) Why does .bfill().ffill() act differently than ffill().bfill() on groups?
<p>I think I'm missing something basic conceptually, but I'm not able to find the answer in the docs.</p> <pre><code>&gt;&gt;&gt; df=pd.DataFrame({'a':[1,1,2,2,3,3], 'b':[5,np.nan, 6, np.nan, np.nan, np.nan]}) &gt;&gt;&gt; df a b 0 1 5.0 1 1 NaN 2 2 6.0 3 2 NaN 4 3 NaN 5 3 NaN </code></pre> <p>Using...
<p>I think you need:</p> <pre><code>print (df.groupby('a')['b'].apply(lambda x: x.ffill().bfill())) 0 5.0 1 5.0 2 6.0 3 6.0 4 NaN 5 NaN Name: b, dtype: float64 print (df.groupby('a')['b'].apply(lambda x: x.bfill().ffill())) 0 5.0 1 5.0 2 6.0 3 6.0 4 NaN 5 NaN Name: b, dtype: float6...
pandas|group-by|pandas-groupby
11
367,786
44,416,069
Pandas: Filter by values within multiple columns
<p>I'm trying to filter a dataframe based on the values within the multiple columns, based on a single condition, but keep other columns to which I don't want to apply the filter at all. </p> <p>I've reviewed these answers, with the third being the closest, but still no luck:</p> <ul> <li><a href="https://stackoverf...
<p>You first want to substitute your <code>'NONE'</code> with <code>np.nan</code> so that it is recognized as a null value by <code>dropna</code>. Then use <code>loc</code> with your boolean series and column subset. Then use <code>dropna</code> with <code>axis=1</code> and <code>how='all'</code></p> <pre><code>df.r...
python|pandas|filter
3
367,787
44,427,116
Get the daily maximum gives strange results
<p>I have a data set of temperature recorded every 15 minutes. The file looks like that (~50000 rows)</p> <pre><code>02/01/2016;05:15:00;10.800 02/01/2016;05:30:00;10.300 02/01/2016;05:45:00;9.200 02/01/2016;06:00:00;9.200 02/01/2016;06:15:00;8.900 02/01/2016;06:30:00;8.900 02/01/2016;06:45:00;9.400 02/01/2016;07:00:0...
<p>There is problem your data are not numeric in last column.</p> <p>Solution is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a> for convert bad data to <code>NaN</code>s:</p> <p>Also for better working with DataFrame is ...
python|pandas|numpy
2
367,788
44,449,972
how to install tensorflow for windows 7 32bit system?i installed python 3.5(32 bit) into my system and also installed anaconda 3.4.4(32 bit)
<p>i have only 32bit system so i installed python 3.5 (64 bit ) error occurs .so i installed python 32bit successfully after that i followed by that document(<a href="http://tensorflow.org/install/" rel="nofollow noreferrer">http://tensorflow.org/install/</a>…) i tried this into command prompt </p> <pre><code>C:\Users...
<p>If using TensorFlow is not a hard requirement, you can consider changing back-ends for Keras. You will be able to use Theano as a back end, which has support for 32-bit windows. Find instructions for that here: <a href="https://keras.io/backend/" rel="nofollow noreferrer">https://keras.io/backend/</a><br> I understa...
python-3.x|tensorflow|anaconda
4
367,789
44,437,518
How the least square method work with a given function
<p>I have some data and I have used below numpy function to make the fitting. The fitting was fine but I need some explanation how it works. What does p[1],p[2],p[0] stands for.It will be nice if I get the mathematical expression for that. what actually the least square is doing?</p> <pre><code>fitfuncvx = lambda p, ...
<p><strong>What are <code>p[0], p[1], p[2]</code>?</strong></p> <p>The <code>scipy.optimize</code> functions typically return an array of parameters <code>p</code>. For example, given a linear equation:</p> <p><a href="https://i.stack.imgur.com/GbiY7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com...
python|numpy|math
1
367,790
44,650,494
How to extract a sub-column from a pandas DataFrame?
<p>I have a table with three columns: <strong>A, B</strong> and <strong>C</strong>. Each column is further divided into two sub-columns: <em>Name</em> and <em>Rule</em>.</p> <p>I need to plot three pie charts out the <em>Name</em> sub-columns using matplotlib, but I don't know how to extract the sub-column. This is wh...
<p>You might want to read on Multiindexing and <a href="https://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers" rel="noreferrer">Slicing</a>.</p> <pre><code>import pandas as pd import numpy as np arrays = [['A', 'A', 'B', 'B', 'C', 'C'], ['Name', 'Rule', 'Name', 'Rule', 'Name', 'Rule']] tu...
python|pandas|matplotlib
5
367,791
44,515,532
Tensorflow resize_image_with_crop_or_pad
<p>I want to call <code>tf.image.resize_image_with_crop_or_pad(images,height,width)</code> to resize my input images. As my input images are all in form as 2-d numpy array of pixels, while the image input of <code>resize_image_with_crop_or_pad</code> must be 3-d or 4-d tensor, it will cause an error. What should I do?<...
<p>Let's suppose that you got <code>images</code> that's a <code>[n, W, H]</code> numpy nd-array, in which <code>n</code> is the number of images and <code>W</code> and <code>H</code> are the <code>width</code> and the <code>height</code> of the images.</p> <ol> <li><p>Convert images to a tensor, in order to be able t...
python|tensorflow
2
367,792
44,614,653
tensorflow reading data from database
<p>I am new to tensorflow. I have a large amount of data in my data base and I want a way to train a tensorflow model on the data. I understand how to do this if I was writing the data to a csv file and then reading the data from csv. But how do I do this directly from the data base. I can connect to the database from...
<p>Let's reiterate the problem :</p> <ul> <li>it is impossible to load all the data into memory (even if the data is trimmed of all unneeded meta data)</li> <li>it is not possible (for technical or policy reasons) to first query the database then save the results to disk as a csv file then work with the csv file.</li>...
python|database|tensorflow|bigdata
0
367,793
44,414,905
Can't do matrix multiplication with tensorflow
<p>In Tensorflow, I would like to do matrix multiplication using this code:</p> <pre><code>_X = np.array([[1, 2, 3], [4, 5, 6]]) _Y = np.array([[1, 1], [2, 2], [3, 3]]) X = tf.convert_to_tensor(_X) Y = tf.convert_to_tensor(_Y) res = tf.matmul(X, Y) </code></pre> <p>However, I am getting this error:</p> <pre><code>T...
<p>Here is the docs for <code>tf.matmul</code>:</p> <blockquote> <p>Both matrices must be of the same type. The supported types are: <code>float16</code>, <code>float32</code>, <code>float64</code>, <code>int32</code>, <code>complex64</code>, <code>complex128</code>.</p> </blockquote> <p>Changing the data type to...
python|tensorflow
2
367,794
44,514,673
Installing Tensorflow with Anaconda Windows 7
<p>So currently, I have projects that related to Machine learning. I want to install tensorflow in my Laptop (as I know, there is a tensorflow that can run in CPU). I follow this guide <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup#anaconda_installation" rel="nofollow noreferrer">https://www.te...
<p>Tensorflow for Windows with CPU mode in Anaconda is quite straight forward. I will explain the steps for you.</p> <ol> <li>Create Anaconda Environment and enter it (You have done this already!)</li> <li><strong>Inside</strong> your environment, run <code>pip install tensorflow=1.2.0rc2</code> I notice that you are ...
tensorflow
0
367,795
44,509,300
Using pyodbc with SQL join statement in Python
<p>I am trying to join 2 tables in Python. (Using Windows, jupyter notebook.) </p> <p>Table 1 is an excel file read in using pandas.</p> <pre><code>TABLE_1= pd.read_excel('my_file.xlsx') </code></pre> <p>Table 2 is a large table in oracle database that I can connect to using pyodbc. I can read in the entire table su...
<p>Something like this might work. First do:</p> <pre><code>MyIds = set(table_1['id']) </code></pre> <p>Then:</p> <pre><code>SQL1 = "CREATE TEMPORARY TABLE MyIds ( ID int );" </code></pre> <p>Now insert your ids:</p> <pre><code>SQL2 = "INSERT INTO MyIds.ID %d VALUES %s" for element in list(MyIds): cursor.execu...
python|pandas|join|pyodbc
2
367,796
44,813,343
TPOT: Pickling Error When Using TPOTRegressor
<p>I have a DataFrame called <code>X</code> and a set of target values called <code>Y</code>. </p> <p>For most of my models, I do something like this (just an example):</p> <pre><code>from sklearn.linear_model import LassoCV clf = LassoCV() score = cross_val_score(estimator = clf, X = X, y = Y, cv = KFold(n_splits =...
<p>If you are using Python 2, try:</p> <pre><code>import dill </code></pre> <p>So that lambda functions can be pickled.... Worked for me...</p> <p>in Python 3, you might need:</p> <pre><code>import dill as pickle </code></pre>
python|pandas|machine-learning|scikit-learn|tpot
1
367,797
44,439,079
Python Pandas Columns variables
<p>Now my code is reading csv files. I have to do the next steps: if CP3 and CP4 have values then it's false if don't it's true and finally i need to keep values but i want it to return in boolean, if it's filled or not.</p> <pre><code>df1 = pd.read_csv("JonnyTheBoy10.csv", usecols=['ART_TIPO', 'ART_DESIG', 'PORTA', '...
<p>This gave you the result you want, you're free to store it wherever you find it appropriate:</p> <pre><code>res = ~(df1["CP4"] &amp; df1["CP3"]) </code></pre> <p>The "~" operator inverse the "&amp;" (and) operator.</p>
python|csv|pandas|row|multiple-columns
0
367,798
44,544,207
What's the easiest way to replace categorical columns of data with codes in Pandas?
<p>I have a table of data in .dta format which I have read into python using Pandas. The data is mostly in the categorical data type and I want to replace the columns with numerical data that can be used with machine learning, such as boolean (1/0) or codes. The trouble is that I can't directly replace the data because...
<p>I do it the following way:</p> <pre><code>df_dumm = pd.get_dummies(feature).head() df_dumm.columns = ['smkevr', 'cignow', 'dnnow', 'dnever', 'complst'] print (df_dumm.head()) </code></pre>
python|pandas
0
367,799
44,438,180
String startswith a particular text
<p>I'm trying to read a csv file and I've to do column operations based on some condition. Its completely ignoring my if condition and executes else statement. Its a pain after lot of troubleshooting, i'm unable to rectify it.</p> <p><strong>Here is the code:</strong><br> <em>Tweet is my column name for tweets...</em>...
<p>In pandas working with arrays, so need <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with boolean mask created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow nore...
python|string|pandas|if-statement|twitter
2