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
374,500
48,248,816
how to create and save a pycharm project from an existing python program?
<p>I recently installed TensorFlow on a Ubunu 14.04 machine using virtual environment and installed PyCharm to analyze TensoFlow Python programs. </p> <p>I downloaded <code>mnist_softmax.py</code>, the first tutorial program under <code>~/TF</code>. I opened it with PyCharm and set the Python interpreter to the one in...
<p>I found creating a project and adding the source file makes pychamr remember the project as working previous project in the list.</p>
python|tensorflow|pycharm
0
374,501
48,370,603
drop columns in pandas dataframe based on mask
<p>I have a dataframe with various number of values in each columns. I created a mask that tells me how many values in each column with the following code from another post > I get the following results</p> <pre><code>count_year_mask = df_mth_return.notnull().sum() results in series like this AAPL US Equity 312 ...
<p>You can filter columns with <code>loc</code>:</p> <pre><code>df_mth_return.loc[:, count_year_mask&gt;=180] </code></pre> <p>Or:</p> <pre><code>df_mth_return.loc[:, ~count_year_mask&lt;180] </code></pre>
python|pandas
3
374,502
48,226,221
What is the function in TensorFlow that is equivalent to expand() in PyTorch?
<p>Let's say I have a 2 x 3 matrix and I want to create a 6 x 2 x 3 matrix where each element in the first dimension is the original 2 x 3 matrix.</p> <p>In PyTorch, I can do this:</p> <pre><code>import torch from torch.autograd import Variable import numpy as np x = np.array([[1, 2, 3], [4, 5, 6]]) x = Variable(tor...
<p>The equivalent function for <strong>pytorch</strong> <code>expand</code> is <strong>tensorflow</strong> <code>tf.broadcast_to</code></p> <p>Docs: <a href="https://www.tensorflow.org/api_docs/python/tf/broadcast_to" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/broadcast_to</a></p>
python|tensorflow|pytorch
7
374,503
48,414,408
Find accuracy of DNNRegressor with tensorboard
<p>Is there a way to show the accuracy of this DNNRegression model after each iteration in tensorboard? The only way I have seen it is using the "session" method, not using tf.estimator. Also, is there is a way to find the final accuracy of the model without resorting to doing it by hand? I tried the evaluation method,...
<p>To see the final accuracy you need to call <code>estimator.evaluate(..)</code> which returns an evaluate matrics (loss, accuracy...)</p> <p>check this link</p> <p><a href="https://www.tensorflow.org/versions/master/api_docs/python/tf/estimator/DNNRegressor" rel="nofollow noreferrer">https://www.tensorflow.org/vers...
tensorflow|tensorboard|tensorflow-estimator
0
374,504
48,115,731
How to compare names with and without orthographic accent in pandas?
<p>In Python 3 and pandas I have a dataframe with full names. My default encoding is utf-8. The names are in the Portuguese language, therefore they have spelling accentuation</p> <pre><code>perfis_deputados.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 513 entries, 0 to 512 Data columns (total 10 col...
<p>You can define and apply function to your DF like this : </p> <pre><code>import unidecode def f(str): return (unidecode.unidecode(str)) perfis_deputados["nome_completo"].apply(f) </code></pre>
python|pandas|spelling
1
374,505
48,022,794
Tensorflow: difference get_tensor_by_name vs get_operation_by_name?
<p>The answer <a href="https://stackoverflow.com/questions/38673771/tensorflow-difference-of-get-collection-get-tensor-by-name-and-get-operation-b">here</a> says that one returns an operation while the other returns a tensor. That is pretty obvious from the name and from the documentation. However, suppose I do the fol...
<p>Short answer: you can use both, <code>get_operation_by_name()</code> and <code>get_tensor_by_name()</code>. Long answer:</p> <h2><code>tf.Operation</code></h2> <p>When you call</p> <pre><code>op = graph.get_operation_by_name('logits') </code></pre> <p>... it returns an instance of type <a href="https://www.tenso...
tensorflow|deep-learning|tensorflow-serving
5
374,506
48,118,436
Numpy attributes not recognized in Numba
<p>Numba offers JIT for Python. In its documentation it says "One objective of Numba is having a seamless integration with NumPy."</p> <p>So why including some of the simplest features from numpy isn't possible:</p> <pre><code>import numpy as np from numba import * @jit(nopython=True) def testfun(x): y = np.size(x...
<p>The following works:</p> <pre><code>@nb.jit(nopython=True) def testfun(x): y = x.size return y </code></pre> <p>Certain attributes are supported, but you should look at when the corresponding function is:</p> <p><a href="http://numba.pydata.org/numba-doc/latest/reference/numpysupported.html#attributes" re...
python|numpy|scipy|jit|numba
4
374,507
48,044,405
split pandas column prepending with actual column name
<blockquote> <pre><code>&gt;&gt;&gt;table1 col1 col2 row1 A A row2 B A row3 A B row4 B A </code></pre> <p>I want to convert only one column in the above dataframe into following DataFrame using one-hot expression or any other methods</p> <pre><code...
<p>Use <code>pd.get_dummies</code></p> <pre><code>In [211]: pd.get_dummies(table1) Out[211]: col1_A col1_B col2_A col2_B row1 1 0 1 0 row2 0 1 1 0 row3 1 0 0 1 row4 0 1 1 0 </code></pre>
python|python-3.x|pandas|dataframe
1
374,508
48,196,567
How to find negative imaginary parts of values in an array then turning them to positive?
<p>I have a function <code>a=x*V</code> where <code>x</code> assumes thousands of values as <code>x = arange(1,1000,0.1)</code> and <code>V</code> is a combination of other constants. These make <code>a</code> always complex (has nonzero real and imaginary parts). However, because <code>a</code> depends on other values...
<p>IIUC:</p> <pre><code>In [35]: a = np.array([1+1j, 2-2j, 3+3j, 4-4j]) In [36]: a.imag *= np.where(a.imag &lt; 0, -1, 1) In [37]: a Out[37]: array([ 1.+1.j, 2.+2.j, 3.+3.j, 4.+4.j]) </code></pre>
python|numpy|math
2
374,509
48,383,962
Python: eliminate extra comma (Error tokenizing data. C error: Expected 3 fields in line 29, saw 4)
<p>The error cause by 'Food, Beverage &amp; Tobacco' which has extra comma that cause pandas unable to read the csv file. it cause error </p> <blockquote> <p>Error tokenizing data. C error: Expected 3 fields in line 29, saw 4</p> </blockquote> <p>How can I elegantly eliminate extra comma in the csv file for 'GICS i...
<p>The file from the URL in your post contains additional commas for some items in the <code>GICS industry group</code> column. The first occurs at line 31 in the file:</p> <pre><code>ABUNDANT PRODUCE LIMITED,ABT,Food, Beverage &amp; Tobacco </code></pre> <p>Normally, the 3rd item should be surrounded by quotes to e...
python|pandas|csv
2
374,510
48,181,613
How can i find the equation of a line passing 2 points and point passing by line -python
<p>i have two points:</p> <pre><code>(283,240,302) (150,150, 50) </code></pre> <p>I want to know equation of the two point , and i want to find (x,y,z) distance R from point(150,150,50)</p> <p><img src="https://i.stack.imgur.com/NCrtj.png" alt="enter image description here"></p>
<p>The easiest way would be using vectors : compute <code>AB</code> vector, and the use proportionality to compute <code>AC</code> vector. Then compute C position from <code>AC</code>:</p> <pre><code>A = (150, 150, 50) B = (283, 240, 302) from math import sqrt AB = [A[i] - B[i] for i in range(3)] length_AB = sqrt(su...
python|arrays|algorithm|numpy|jupyter-notebook
0
374,511
48,321,437
Get minimun value of a column by comparing previous n rows in Pandas
<p>I want to get the min value of a column by compare the value in current row with the value in previous 2 rows, I know this can be done by creating 2 columns with the shift(-1) and shift(-2) and return the min value of the row, but I would like to know if there is any way to do it better if I extend the range from pr...
<p>You need rolling min with window 3 i.e </p> <pre><code>df['new'] = df['score'][::-1].rolling(3,min_periods=1).min()[::-1] score new 0 12.0 4.0 1 11.0 4.0 2 4.0 4.0 3 15.0 6.0 4 6.0 6.0 </code></pre>
python|pandas
3
374,512
48,373,962
pandas groupby not working as expected
<p>I have a dataframe:</p> <pre><code> &gt;&gt;&gt; d6 Out[57]: Date sym Last M1 M2 dist code 52735 2017-11-23 C 0.10 4.72 -9.27 677.93 4250 - 12/15/2017 52736 2017-11-23 P 684.20 1.43 -106.09 677.93 4250 - 12/15/2017 53144 2017-11-23...
<p>The problem is happened to the second <code>bfill</code>(It will back fill nan for whole dataframe , rather than each subgroup),below will work for you </p> <pre><code>df.groupby(['code','Date']).apply(lambda x : x.ffill().bfill()) </code></pre> <p>For example, we usually think this will return sum of sum for each...
python|pandas|group-by|fillna
3
374,513
48,302,876
dtype changes after set_value/at
<p>I'm facing a weird issue on Pandas now, not sure if a pandas pitfall or just something I'm missing...</p> <p>My pd.Series is just</p> <p><code>foo False False False </code></p> <p><code>&gt; a.foo.dtype dtype('bool') </code></p> <p>When I use a <code>dataframe.set_value(index, col, None)</code>, my whole Series ...
<p>I think the problem is related to the fact that I was trying to assign a <code>None</code> to a <code>bool</code> Series, then it just tries to convert to a different type (why not object?)</p> <p>Fixed changing the dtype to <code>object</code> first: <code>dataframe.foo = dataframe.foo.astype(object)</code>.</p> ...
python|pandas
1
374,514
48,157,575
What to do when pip & conda overlap?
<p>I have a reasonable understanding of the difference between <code>conda install</code> &amp; <code>pip install</code>; How <code>pip</code> installs python only packages &amp; <code>conda</code> can install non-python binaries. However, there is some overlap between these two. Which leads me to ask:</p> <p><stro...
<p>The Tensorflow maintainers actually publish the wheels of TensorFlow on PyPI that's why it's the recommended <em>official</em> way. The <code>conda</code> packages are created by the Anaconda staff and/or the community. That doesn't mean the conda packages are bad, it just means that the TensorFlow maintainers don't...
python|numpy|pip|conda
15
374,515
48,017,236
np where statement gets: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
<p>I am writing for following line of code:</p> <pre><code>holiday['real_or_not'] = np.where((holiday['transferred']=='False',1,0)) holiday </code></pre> <p>Minimum reproducible example: </p> <pre><code>date type locale locale_name description transferred 2012-03-02 False locale Manta F...
<p>First, you need to remove the extra parenthesis. Because it creates a tuple and you give <code>np.where</code> one argument, the tuple, instead off three arguments. This means this tuple is interpreted as as the condition because the second and third argument are optional:</p> <pre><code>where(condition, [x, y]) <...
python|python-2.7|pandas|numpy|where
1
374,516
48,478,780
pandas DataFrame.groupby and apply custom function
<p>I have a DataFrame with many duplicates (I need Type/StrikePrice pair to be unique) like this:</p> <pre><code> Pos AskPrice Type StrikePrice C 1500.0 10 281.6 C 1500.0 11 281.9 C 1500.0 12 281.7 &lt;- I need this one P 1400.0 30 1200.5 P ...
<p>First <code>reset_index</code> for unique indices, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.idxmax.html...
python|pandas|pandas-groupby
3
374,517
48,558,107
Converting float to string in pandas dataframe
<p>I have a dataframe in pandas containing datetime and float data.</p> <pre><code>time price1 price2 2018-02-01T00:00:00.000Z 1.4526547885 1.654775563 </code></pre> <p>I need to convert the columns to string format such that the price1 and price2 columns shows number u...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="noreferrer"><code>dt.strftime</code></a> for formating <code>datetime</code>s and then custom format of <code>float</code>s:</p> <pre><code>df['time'] = df['time'].dt.strftime('%Y,%m,%d %H:%M:%S') cols =...
python|python-3.x|pandas
13
374,518
48,828,962
Reducing GPU memory consumption of tensor flow model
<p>I am trying to get the code in this git rep working: <a href="https://github.com/cvikasreddy/skt" rel="nofollow noreferrer">https://github.com/cvikasreddy/skt</a> The training data is a 7mb text file. I have a Nvidia GTX 750ti with 1gb of memory. When I try to train on this machine, the trainer crashes because of r...
<p>You can run everything on the CPU by adding </p> <pre><code>with tf.device('/cpu:0'): </code></pre> <p>and the correct indentation before the definition of your graph. It'll be slower but you should have more than enough memory. You could also put most of your ops on the CPU, and choose a few to put on the GPU. Yo...
python|tensorflow
1
374,519
48,833,889
when does input pipeline returns a new data batch?
<p>I am using an input pipeline with queues and <code>TFRecordReader</code> to read a tfrecord file and use the data directly into a <code>dynamic_rnn</code> function. So for example if i have this last step of the input pipeline:</p> <pre><code>xb, yb = tf.train.shuffle_batch([x, y], batch_size, capacity, min_after_d...
<p><code>.shape</code> on a <code>Tensor</code> does not run it when graph building, nor does <code>print</code>, those just fetch Python metadata. Even then, referencing a <code>Tensor</code> multiple times gives you one value per <code>session.run</code> call (unless it's in a <code>tf.while_loop</code> or other cont...
tensorflow|input|pipeline|rnn
0
374,520
48,511,766
Conditional Function to a pandas dataframe, if vs else change the value
<p>I been trying to get my code to work but I am having some trouble here. It would be great if someone could assist me</p> <p>DF</p> <pre><code> Col1 Col2 2017-01-01 Coffee 2017-01-01 Muffin 2017-01-01 Donut 2017-01-01 Toast </code></pre> <p>How can I cha...
<pre><code>In [265]: df.loc[~df.Col2.isin(['Coffee','Muffin']), 'Col2'] = 'Other' In [266]: df Out[266]: Col1 Col2 0 2017-01-01 Coffee 1 2017-01-01 Muffin 2 2017-01-01 Other 3 2017-01-01 Other </code></pre>
python|pandas|conditional
1
374,521
48,838,171
Intuition behind Neural Network Results?
<p>I am attempting to build a neural network to classify poisonous mushrooms, however the results are not correct. The model compiles successfully, however can someone provide intuition as to why it is the training results are so seemingly accurate after only a few epochs. This does not seem correct, was an error made ...
<p>One epoch is a lot of iterations (n=training_set_size/batch_size). Considering that you have so many layers and no regularization i would suspect overfitting.</p>
tensorflow|machine-learning|neural-network|keras|classification
0
374,522
48,518,306
Converting objects into Panda dataframe?
<p>I have a data frame with columns</p> <ul> <li>created_at</li> <li>id</li> <li>data (I am having trouble parsing through this column)</li> </ul> <p>Each object in the data column is a dictionary. I want to have each object in the dictionary be a standalone column. Any help or direction to a package would be appreci...
<p>Here a subset of your dictionnary example : </p> <pre><code>d = { 'backers_count': 37, 'blurb': 'Nano Art will make and market customized pieces, in a variety of materials, featuring etchings smaller than an eyelash.', 'category': { 'color': 16760235, 'id': 21, 'name': 'D...
python|pandas|parsing|dictionary|dataframe
1
374,523
48,793,413
How to connect tensoflow to jupyter notebook?
<p>I have installed <code>Anaconda</code> with <code>jupyter notebook</code> in <code>/home/serg/anaconda/bin</code> and installed <code>tensoflow</code> in <code>./.local/lib/python3.5/site-packages/tensorflow</code>. My operation system is <code>Ubuntu 16.04</code>.</p> <p>Is it possible to use <code>tensorflow</cod...
<p>Looks like you may have installed stuff in the wrong order.</p> <p>I run TensorFlow in Jupyter notebook all the time, I don't get your issue? If you have installed Anaconda and it is active eg when you type python, you get the Anaconda version of python, you just install TensorFlow with Pip (following instructions ...
tensorflow|anaconda|jupyter-notebook
0
374,524
48,868,660
TensorFlow - predicting next word - loss function logit na target shape
<p>I'm trying to create a language model. I have <code>logit</code> and target of size: <code>[32, 312, 512]</code></p> <p>Where: </p> <ul> <li><code>.shape[0]</code> is <code>batch_size</code></li> <li><code>.shape[1]</code> is <code>sequence_max_len</code></li> <li><code>.shape[2]</code> is <code>vocabulary size</c...
<p>The api documentation says about labels,</p> <blockquote> <p>labels: Each row labels[i] must be a valid probability distribution</p> </blockquote> <p>If you are predicting each character at a time, you would have a probability distribution (probability of being each character sum up to 1) over your vocab size 51...
tensorflow|neural-network|recurrent-neural-network|seq|language-model
1
374,525
48,874,483
Python Pandas read_sql - call previously specified date
<p>I have a sql query and I want to specify the date outside of the where query so it can be changed as needed. The following code isn't working and I'm not sure what else to try.</p> <pre><code>startdate='2018-01-01' test=pd.read_sql("""select * from database.table where date &gt; :startdate ; """ , connection) </co...
<p>How about this</p> <pre><code>test=pd.read_sql('select * from database.table where date &gt; {}'.format(startdate) , connection) </code></pre>
python|pandas
0
374,526
48,583,002
How to open a .tsv file in Jupyter? Jupyter.Notebook tried suggestions, but it doesn't work
<p>How can I open a <code>.tsv</code> file in Jupyter.<br> The data is stored under <code>C:/User/anna/</code>. </p> <p>This is my code:</p> <pre><code>import pandas as pd df=pd.read_csv('C:/User/anna/train') </code></pre> <p>But I get this error message:</p> <blockquote> <p>FileNotFoundError: File b'C:/Users/ann...
<p>it's actually to do with pandas, by default the separator is comma, not tab. try the code below:</p> <pre><code>df=pd.read_csv('C:/User/anna/train', sep='\t') </code></pre>
pandas|csv|jupyter-notebook|jupyter
3
374,527
48,630,060
Select N rows above and below a specific row in pandas
<p>I have this data frame and I want to select 10 rows before and after on a specific column. I have reached up to this point but I was wondering how to make it more elegant in a lambda python expression as I need to run this on a loop 10 thousand times.</p> <pre><code>import pandas as pd df = pd.DataFrame(data=np.ra...
<p>Really simple using <code>index.get_loc</code>. Get the index of the label, and slice accordingly. </p> <pre><code>idx = df.index.get_loc('2015-01-17') df.iloc[idx - 10 : idx + 10] A 2015-01-07 0.262086 2015-01-08 0.836742 2015-01-09 0.094763 2015-01-10 0.133500 2015-01-11 0.285372 2015-01-...
python|pandas|dataframe|indexing
20
374,528
48,453,143
Using sequences of images for as an input for time distributed conv2d
<p>I'm currently attempting to build a model that uses image sequences and classifies each item in the sequence (not retaining state between sequences) in Keras with a TF backend; however, I'm running into an issue with the input shape for the first layer.</p> <p>the model looks like this: </p> <pre><code>model.add(T...
<p>According to Keras documentation, you have to update the input_dim to be</p> <pre>model.add(TimeDistributed(Conv2D(64, (3, 3), activation='relu'), input_shape=(10, 224, 224, 3))) </pre> <p>and then use an image generator that fits the new shape of data. you can use the tweaked one in this <a href="https://gist.githu...
python|tensorflow|machine-learning|neural-network|keras
1
374,529
48,788,708
Tensorflow, delete element from matrixs
<p>I want know how to delete an element from a matrix in a tensor. </p> <pre><code>a = tf.Variable(initial_value=[[0, 0, 0, 0],[2, 2, 2, 2],[1, 1, 1, 1]]) b = tf....(a) #desired output of b, if I want to remove the second element in dim 1 of "a" [[0, 0, 0, 0],[1, 1, 1, 1]] #desired output of b, if I want to remove th...
<p>Slice and then Stack</p> <pre><code>a = tf.Variable(initial_value=[[0, 0, 0, 0],[2, 2, 2, 2],[1, 1, 1, 1]]) b = tf.stack([a[0], a[2]]) #[[0, 0, 0, 0],[1, 1, 1, 1]] c = tf.stack([a[0], a[1]]) #[[0, 0, 0, 0],[2, 2, 2, 2]] </code></pre>
python|tensorflow
0
374,530
48,689,113
Dynamic - Automated multiplication - Pandas dataframes
<p>after spending quite a while search and reading on Stackoverflow and around the web, I am desperate...</p> <p>I have a Pandas DataFrame with some imported data (spectra). The first column is the wavelength while the others are the various spectra (the data). The names of the columns are imported from a list that re...
<p><strong>Question 1</strong></p> <p>To multiply your wavelength column by every other column in your DataFrame, you can use:</p> <pre><code>df.iloc[:, 1:] = df.iloc[:, 1:].mul(df['Wavelength'], axis=0) </code></pre> <p>This assumes your wavelength column is the first column.</p> <p><strong>Question 2</strong></p>...
python|pandas|dataframe|multiplication
1
374,531
48,852,577
Tensorflow fileio reading from GCS bucket via Dataflow: SSL no alternative certificate subject name matches target host name
<p>I am running a slightly modified version of the <a href="https://github.com/GoogleCloudPlatform/cloudml-samples/tree/master/flowers" rel="nofollow noreferrer">cloudml flowers sample</a> to classify my own images where I encounter a problem in the preprocess part. It seems when pointing to my own images which are in ...
<p>Google(TensorFlow) APIs do not support double wildcard format, e.g., <code>*.*.storage.googleapis.com</code>. They just support one wildcard certificate e.g., <code>*.storage.googleapis.com</code> . In your case, when you use "$BUCKET.com.storage.googleapis.com”, more than one identity of a given type is present i...
python|tensorflow|ssl-certificate|google-cloud-storage|google-cloud-dataflow
2
374,532
48,472,331
Evaluating a classifier in TensorFlow
<p>I was walking through <a href="https://pythonprogramming.net/convolutional-neural-network-kats-vs-dogs-machine-learning-tutorial/" rel="nofollow noreferrer">this tutorial</a>.</p> <p>I couldn't figure out how to evaluate the classifier, especially finding its sensitivity, specificity, AUC, ...etc.</p> <p>I found t...
<p>So as I see it, the tutorial is about classifying pictures, it's a dog or a cat. After completion of the training, you will be evaluated with a test data set (pictures that were not used in the training) for these test data points will make a prediction for the two classes (for example: cat: 0.08 dogs: 0.92) and the...
python|tensorflow|statistics|evaluation|auc
0
374,533
48,456,459
What is the correct way to read txt file using command line in Pandas
<p>I am new to python and I am having error like this with my code, which is to scan IP address list and show only the malware IP lists: import os from datetime import datetime, date, timedelta import subprocess import pyjq import pandas as pd</p> <pre><code># Initializes the variables for the director...
<p><strong>1)</strong> There is a module within the standard library called CSV. It is probably better to use that when creating CSV's. Used like this:</p> <pre><code>import csv with open("file.csv", 'w') as f: writer = csv.writer(f, delimiter=',') writer.writerow(ResultDir + "/srciplist-" + ToDay + ".csv") <...
python|pandas
0
374,534
48,646,485
Append a "layer" to 3D-Array with Numpy
<p>I have a numpy array with dimensions <code>12 x 12 x 4</code>. Now I'm trying to add an extra layer to this cube resulting in a <code>12 x 13 x 4</code> array. This 13th layer should contain the corresponding indices from the first axis, so for example addressing <code>[7, 13, :]</code> results in <code>[7, 7, 7, 7]...
<p>You have the right idea. A slight simplification:</p> <pre><code>layer = np.repeat(np.arange(3)[:,None,None], data.shape[2], axis=2) result = np.concatenate((data, layer), axis=1) </code></pre>
numpy|numpy-ndarray
2
374,535
48,629,632
Merging a pandas dataframe with a pivot table
<p>I have 2 pieces of data that I want to merge. <br><br> <code>df1</code> is a pandas dataframe that contains a list of contracts, where <code>year</code> is the year the contract was was executed, and <code>o_id</code> refers to the id of the organization that this contract is from.<br><br> <code>df2</code> is a pivo...
<p>First reshape <code>df2</code> by <code>stack</code> and <code>join</code> <code>df1</code>, then replace values by <code>NaN</code>s by custom function:</p> <pre><code>df = (df1.drop('c_id', 1) .join(df2.stack(0).reset_index(level=1), on='o_id') .set_index(['o_id','year', 'level_1'])) def f(x): ...
python|pandas|merge
2
374,536
48,600,521
Recovering parameters for wald distribution: from numpy to scipy
<p>could someone please help with a questions around the parametrization of scipy distributions and how to transform them? </p> <p>I basically would like to recover distribution parameters of data that I simulate with numpy... </p> <pre><code>some_data = np.random.normal(loc=81, scale=7, size=100000) </code></pre> <...
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.wald.html" rel="nofollow noreferrer"><code>numpy.random.wald</code></a> has two parameters, <code>mean</code> and <code>scale</code>. <code>scale</code> is, as the name suggests, a <em>scale parameter</em>, in the sense of a <a href="https://...
python|numpy|scipy|statistics|distribution
2
374,537
48,786,388
numpy ravel function return issue
<p>When ravel() returns a contiguous 1D array of all the elements in nD array, I observed it just returned only unique elements of X1 as mentioned. Am I missing anything?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-...
<p>This is a printing issue. You can tune this behavior with <code>numpy.set_printoptions</code>:</p> <pre><code>In [404]: np.array([arange(10)]*10).ravel() Out[404]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5,...
python|numpy
0
374,538
48,688,382
Pandas module in SPSS Modeler
<p>I need to put a certain code developed in Python 3 into a SPSS Modeler node (using the Extension Transform node). This code uses pandas and the default installation of Modeler doesn't include this module.</p> <p>I tried to make SPSS to point to my own Python installation (which includes pandas module) by modifying ...
<p>You can install new packages to your existing SPSS Modeler 18.1 Version by going to your installation path, e.g. "C:\Program Files\IBM\SPSS\Modeler\18.1" and then into the folder python. There you open a windows command shell in admin mode. Now enter </p> <blockquote> <p>python.exe -m pip install pandas</p> </blo...
python|pandas|pyspark|spss-modeler
4
374,539
48,822,061
If statement string data from dataframe does not work for larger years
<p>I have a problem with an if statement with my data from the dataframe. Somehow performing an if statement for years > 3years somehow all values larger than 9Y are not showing up and it is not clear why. The output looks like the following:</p> <blockquote> <pre><code>4Y 5Y 6Y 7Y 8Y 9Y 4Y 5Y 6Y 7Y 8Y 9Y </code></pre...
<p>There is problem you compare strings lexicographically, so <code>10Y &lt; 3Y</code>. Solution is convert values to integers.</p> <pre><code>df['mask'] = df['year'].str.extract('(\d+)', expand=False).astype(int) &gt; 3 </code></pre> <hr> <pre><code>print (df) date year values mask 0 2015-02-09 1Y...
python|pandas|loops|dataframe
3
374,540
48,633,293
Matplotlib: Drawing contour lines independent of x and y
<p>I am trying to draw contour lines (elevation) associated with x and y coordinates. I have read examples <a href="https://matplotlib.org/examples/pylab_examples/contour_demo.html" rel="nofollow noreferrer">here</a> on how you draw contours on Matplotlib when z is defined by x and y but how can I draw contour lines th...
<p>Given that there are only 6 data points, a contour plot drawn from those may not be very informative. Still, the concept would be the same for more points. </p> <p>Of course one cannot draw contour lines where x,y and z are independent. If you have 6 z points, you need 6 x points and 6 y points - which you have. So...
python|arrays|numpy|matplotlib|contour
2
374,541
48,599,207
Python: How to get Dataframes with get_groups in for loops
<p>I have grouped a DataFrame using <code>data.groupby('column)</code> and now I want to create a dataframe from each group:</p> <pre><code>for i in data_group.indices: i = data_group.get_group(i) </code></pre> <p>I can print the dataframes out within the for-loop, but I can't access them otherwise... Somehow the...
<p>You can store them in a list </p> <pre><code>g=data.groupby('column') l=[] for x,df in g : l.append(df) </code></pre> <p>Or using <code>get_group</code></p> <pre><code>g.get_group('groupkey') </code></pre>
python|pandas|dataframe
1
374,542
48,471,688
Using tensorflow's Dataset pipeline, how do I *name* the results of a `map` operation?
<p>I have the map function below (runnable example), which inputs a <code>string</code> and outputs a <code>string</code> and an <code>integer</code>.</p> <p>in <code>tf.data.Dataset.from_tensor_slices</code> I named the original input <code>'filenames'</code>. But when I return the values from the map function <code>...
<p>I'm posing a final solution to this question for posterity sake. The code below is a copy/paste example that works under the most complex conditions this question addresses (note that the other two answers aren't copy/pastable code samples):</p> <p>The goal of the code is:</p> <ul> <li>Take a list of (big) files a...
python|dictionary|tensorflow|mapping|tensorflow-datasets
6
374,543
48,736,176
Cross product between columns of two matrices
<p>Given two matrices <a href="https://i.stack.imgur.com/Gngz8.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gngz8.gif" alt="enter image description here"></a> and <a href="https://i.stack.imgur.com/zck2c.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zck2c.gif" alt="enter image...
<p>Here is another way to do it:</p> <pre><code>np.sum(x*y, axis=0) </code></pre> <p>Efficiency: </p> <pre><code>x = np.random.randint(0, 10, size=(30, 400)) y = np.random.randint(0, 10, size=(30, 400)) %timeit np.sum(x*y, axis=0) # 38.4 µs ± 942 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) %timeit f...
python|numpy|matrix
3
374,544
48,797,147
Drop string that is all zeros - pandas python
<p>I have a dataframe of strings that looks like this: </p> <pre><code>In [58]: d['upin'].head() Out[58]: 0 'H8409 1 'H8409 2 .31961 3 .31961 4 000000 Name: upin, dtype: object </code></pre> <p>I want to drop the rows that have only zeros, i.e. the last row in this example. I haven't found a nice reg...
<p>This should work if I understood your problem correctly:</p> <pre><code>df = pd.DataFrame() df['pin'] = ["00000","F4923","'222R","0","00001"] ndf = df[~(df['pin'].str.contains('^0+$'))] </code></pre>
python|regex|pandas
3
374,545
48,453,509
Transform all elements positionally below 0 into 0 in a matrix (Python)
<p>This is a matrix :</p> <pre><code>matrix = [[1, 1, 1, 0], [0, 5, 0, 1], [2, 1, 3, 10]] </code></pre> <p>I want to change all the element <em>positionally</em> below 0 into 0 (on the same column).</p> <p>The resulting matrix will be :</p> <pre><code>matrix = [[1, 1, 1, 0], [0, 5, ...
<h1>Method 1 (Original)</h1> <pre><code>import numpy as np def transform(matrix): mat = np.asarray(matrix) mat[np.logical_not(np.not_equal(mat, 0).cumprod(axis=0))] = 0 # Alternatively: # mat[~(mat != 0).cumprod(axis=0, dtype=np.bool)] = 0 # or, # mat[~((mat != 0).cumprod(axis=0, dtype=np.bool)...
python|python-3.x|numpy|linear-algebra
2
374,546
48,860,117
Why PerformanceWarning when indexed lookup on sorted index?
<p>Does anyone know why this gives a PerformanceWarning?</p> <pre><code>d=pd.DataFrame( [ [1,2,3], [1,2,4], [1,None,5], [2,3,5], ], columns=['i','j','k'] ) print d.dtypes d = d.set_index(['i','j'])['k'] d = d.sort_index() print d.loc[(2,3)] # PerformanceWarning: indexing p...
<p>It turns out this is an open bug:</p> <ul> <li><a href="https://github.com/pandas-dev/pandas/issues/19771" rel="noreferrer">https://github.com/pandas-dev/pandas/issues/19771</a></li> <li><a href="https://github.com/pandas-dev/pandas/issues/17931" rel="noreferrer">https://github.com/pandas-dev/pandas/issues/17931</a...
python|pandas
5
374,547
48,442,775
Comparing computational speed of these two short codes
<p>In the two versions of the code, both v1 and v2 are large vectors (length ranging from 1,000 1,000,000 with len(v1)=len(v2)). I expected <strong>code 2</strong> to be much master than <strong>code 1</strong>, but it turns out <strong>code 1</strong> is much faster and I do not know why. Could you please explain why ...
<p>The <code>np.dot()</code> calls also require loops through the vectors, but these loops are implemented (typically) natively / in C++. Loops implemented explicitly in python (as in your code 2) are notoriously slow in comparison to such C++-based loops.</p>
python|algorithm|performance|numpy
5
374,548
70,939,265
Duplicated rows when merging on pandas
<p>I have a list that contains multiple pandas dataframes.</p> <p>Each dataframe has columns 'Trading Day' and Maturity. However the name of the column Maturity changes depending on the maturity, for example the first dataframe column names are: 'Trading Day', 'Y_2021','Y_2022'.</p> <p>The second dataframe has 'Trading...
<p>Given your actual output and what you want, you should be able to just:</p> <pre><code>output.ffill().bfill().drop_duplicates() </code></pre> <p>To get the output you want.</p>
pandas|merge|rows
0
374,549
70,952,419
Avoiding iterating through a dataframe to get a total column, using a second dataframe as data
<p>Considering the two dataframes</p> <pre><code>&gt;&gt;&gt; df1 Dr Cr Opening Balance 0 B2 B2 0.0 1 B1 B1 100.0 2 D1 D1 0.0 3 F1 F1 -100.0 &gt;&gt;&gt; df2 Date Amount Dr Cr 0 2021-12-01 452.25 B1 D1 1 2022-01-01 100.00 B1 D1 2 2022-01-02...
<p>One of more straight-forward and relatively debug friendly approach is to group <code>df2</code> based on <code>Dr</code> and <code>Cr</code>, <code>join</code> the results to <code>df1</code> and add/subtract the values:</p> <pre><code>dr = df2.groupby('Dr')['Amount'].sum().rename('Dr Amount') cr = df2.groupby('Cr'...
python|pandas|dataframe
2
374,550
70,742,726
Pandas Selection of rows not working propelry
<p>I am trying to delete rows of a df which are not part of an other columns entry from another table. For further explanation: I have a table with transactions including materialnumbers and another table with production information also including materialnumbers. I want to delete every row where a materialnumber is co...
<p>You probably want to be using the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html" rel="nofollow noreferrer">merge</a> function in pandas opposed to isin.</p> <p>The code below is a simple demonstration of how to use the function</p> <p>We use <code>how='left'</code> so that onl...
python|pandas|dataframe|data-manipulation
0
374,551
70,816,859
How can we retrieve the epoch number from Keras ModelCheckpoint?
<p>While training my ML model, I applied CSVlogger and the ModelCheckpoint callbacks so basically all epochs metric results are logged by the CSVlogger and only best model saved.</p> <p>However with <em>save_best_only</em> for ModelCheckpoint, how can we get/log the epoch number when the model is updated by ModelCheckp...
<blockquote> <p>Hi I also use another by the callback methods , I can easily extract information as these below :</p> </blockquote> <pre><code>lossvalue: 1.1057155132293701 accvalue: 0.6833927035331726 val_loss: None val_acc: None epoch: 1 step: 64 step: 10009601 best acc: 0.0 </code></pre> <blockquote> <p>Anyway you d...
tensorflow|keras|deep-learning|callback|tensorflow2.0
0
374,552
71,052,394
replace values by different conditions in a dataframe
<p>I have a dataframe like this:</p> <pre><code>df_test = pd.DataFrame({'ID1':['A','B','C','BA','BA','AB','&gt;','&gt;','&gt;','&gt;'], 'ID2':['','','','','','','mh','mh','nn','nn']}) df_test </code></pre> <p><a href="https://i.stack.imgur.com/rAZk9.png" rel="nofollow noreferrer"><img src="https:...
<p>You can use <code>.str[-1]</code> regardless of the length of the strings in the column to select the last character, and use <code>&lt;column&gt;.where(cond, other_col)</code> to fill in values that don't match <code>cond</code> with those values from <code>other_col</code>:</p> <pre><code>df_test['ID1'] = df_test....
pandas|dataframe
2
374,553
70,970,506
Creating a new dataframe column based on operations applied to nested arrays in another column?
<p>Let me start off by saying this unfortunately cannot be solved by doing something as simple as df[A] = df[B] - df[C].</p> <p>I have a column containing arrays (let's call it df[A]). I want to z-score the items in each array (with respect to only the values in that array), then store this new array of z-scored values...
<p>You need an apply function for sure. This might either solve it or give you an insight:</p> <pre><code>df.apply(lambda x: (x['A'][0] - x['A'][0].mean()) / x['A'][0].std()) </code></pre>
python|arrays|pandas|dataframe
0
374,554
70,838,701
Output of vgg16 layer doesn't make sense
<p>I have a vgg16 network without the last max pooling, fully connected and softmax layers. The network summary says that the last layer's output is going to have a size of <code>(batchsize, 512, 14, 14)</code>. Putting an image into the network gives me an output of <code>(batchsize, 512, 15, 15)</code>. How do I fix ...
<p>The output shape should be <code>[512, 14, 14]</code>, assuming that the input image is <code>[3, 224, 224]</code>. Your input image size is <code>[3, 244, 244]</code>. For example,</p> <pre class="lang-py prettyprint-override"><code>image = torch.zeros((1,3,224,224)) # torch.Size([1, 512, 14, 14]) output = vgg16wit...
machine-learning|pytorch|computer-vision
2
374,555
70,787,375
Pandas: aggregate and join if different string
<p>I have the following table:</p> <pre><code>data = [['abc', 'bin_1', &quot;bin_2&quot;], ['abc', 'bin_1', &quot;bin_1&quot;]] data = pd.DataFrame(data, columns = ['name', 'bin1', 'bin2']) </code></pre> <p>And I want to merge the columns <code>bin1</code> and <code>bin2</code>. As you see, there can be the same cell v...
<p>Use <code>set</code>s if order is not important:</p> <pre><code>data[&quot;bin&quot;] = data[['bin1', 'bin2']].agg(lambda x: ' | '.join(set(x)), axis=1) print (data) name bin1 bin2 bin 0 abc bin_1 bin_2 bin_1 | bin_2 1 abc bin_1 bin_1 bin_1 </code></pre> <p>Or <code>dict.fromkeys</co...
python|pandas
0
374,556
70,863,943
How to add title to each subplot
<p>I want to add title for each subplot. I want to assign a separate title to each subplot from a list of title in same sequence.</p> <p>title_list = ['Table1', 'Table2',, 'Table3', 'Table4', 'Table5, 'Table6']</p> <p>Hence assign title for df1 as 'Table1', df2 as 'Table2'.. and so on.</p> <p>My Code as below:</p> <pre...
<p>You can use the method <code>set_title()</code> on the axis object:</p> <pre><code>axes[r, c].set_title(f&quot;This is row={r} and column={c}&quot;) </code></pre> <p>I also added a call <code>fig.tight_layout()</code> to fix the spacing between subplots.</p> <p><a href="https://i.stack.imgur.com/wAeez.png" rel="nofo...
python|python-3.x|pandas
1
374,557
70,885,645
selecting random elements from each column of numpy array
<p>I have an n row, m column numpy array, and would like to create a new k x m array by selecting k random elements from each column of the array. I wrote the following python function to do this, but would like to implement something more efficient and faster:</p> <pre><code>def sample_array_cols(MyMatrix, nelements):...
<p>One alternative is to randomly generate the indices first, and then use <code>take_along_axis</code> to map them to the original array:</p> <pre><code>arr = np.random.randn(1000, 5000) # arbitrary k = 10 # arbitrary n, m = arr.shape idx = np.random.randint(0, n, (k, m)) new = np.take_along_axis(arr, idx, axis=0) <...
python|arrays|numpy
1
374,558
70,746,737
TypeError: nll_loss_nd(): argument 'input' (position 1) must be Tensor, not tuple
<p>So I'm trying to train my BigBird model (BigBirdForSequenceClassification) and I got to the moment of the training, which ends with below error message:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\######&quot;, line 189, in &lt;module&gt; train_loss, _ = train() File &quot;C:\User...
<p>Ok, so it seems like I should have used BigBirdModel instead of BigBirdForSequenceClassification - issue solved</p>
python|pytorch|huggingface-transformers|bert-language-model
0
374,559
71,030,620
split a workbook into different workbooks with worksheets using python pandas
<p>I have a list of transactions from the last 7 years in one big excel file. I m trying to create an excel workbook for each year that includes each months as worksheet.</p> <p>Im using a column called 'date' that has each transactions recorded as MM/DD/YYY. I split that column to single out my years and months but Im...
<p>I know this is a bit late, but perhaps better late than never...</p> <p>I'm not sure what issue you ran into b/c it doesn't really say, but I suspect your issue was b/c you created a new writer for each sheet instead of each workbook. You also tried to write all months for all years and didn't create a new DF for e...
python|excel|pandas|dataframe
0
374,560
70,762,615
'DataFrame' object has no attribute 'to_delta'
<p>My code used to work. Why does my code not work anymore? I updated to the newer Databricks runtime 10.2 so I had to change some earlier code to use pandas on pyspark.</p> <pre><code># Drop customer ID for AutoML automlDF = churn_features_df.drop(key_id) # Write out silver-level data to autoML Delta lake automlDF.to...
<p>I was able to get it to work as expected using <code>to_pandas_on_spark()</code>. My working code looks like this:</p> <pre><code># Drop customer ID for AutoML automlDF = churn_features_df.drop(key_id).to_pandas_on_spark() # Write out silver-level data to autoML Delta lake automlDF.to_delta(mode='overwrite', path=a...
pyspark|databricks|delta-lake|pyspark-pandas
1
374,561
70,937,513
RuntimeError: mat1 and mat2 shapes cannot be multiplied (4x73034 and 200x120)
<p>Building a Neural Network layers for Skin detection dataset, and got a error here. I know i have done some mistake but cannot figure it out. Error is am getting is after taking image size 224*224 and channels 3: <em>RuntimeError: mat1 and mat2 shapes cannot be multiplied (4x73034 and 200x120)</em></p> <pre><code>imp...
<p>As <a href="https://stackoverflow.com/users/3999668">Anant</a> said, you need to match the flattened conv2 dimension (73034) to be the input dimension for the fc1 layer.</p> <pre class="lang-py prettyprint-override"><code>self.fc1 = nn.Linear(73034, 120) </code></pre> <p>The formula to calculate the output of each c...
python|machine-learning|deep-learning|pytorch|conv-neural-network
2
374,562
70,933,814
SageMaker custom model output path for tensorflow when creating from s3 artifacts
<p>I'm running the following code to create an endpoint with a preexisting model:</p> <pre><code>from sagemaker.tensorflow import serving sagemaker_session = sagemaker.Session() clf_sm_model = serving.Model(model_data='s3://mybucket/mytrainedmodel/model.tar.gz', entry_point=&quot;in...
<p>The SageMaker Python SDK repackages your model to include your <code>entry_point</code> and <code>source_dir</code> files and uploads this &quot;new&quot; tar ball to the SageMaker default bucket.</p> <p>You can change this behavior by setting the <code>default_bucket</code> in your <code>sagemaker_session</code> as...
tensorflow|amazon-sagemaker
3
374,563
70,950,970
How to read large csv from Azure container using Python Azure Function?
<p>I need to read a larger csv efficiently from container using Python Azure Function.</p> <p>I am using the below code for reading csv, it works fine for small csv but there must be some other way to read larger csv efficiently.</p> <pre><code># Container Connection. container_client1 = ContainerClient.from_connection...
<p>One of the workaround is to process the file in chunks, resulting in lower memory use while parsing.</p> <pre class="lang-py prettyprint-override"><code>chunksize = 10 ** 6 for chunk in pd.read_csv(filename, chunksize=chunksize): process(chunk) </code></pre> <p><strong>NOTE:-</strong> <code>chunksize</code> para...
python|pandas|azure|azure-functions|azure-blob-storage
0
374,564
71,028,228
GPT-3 long input posts for Question Answering
<p>From my understanding, GPT-3 is &quot;trained&quot; for a specific task by including some labelled examples before the desired/test example. In Question Answering, this includes a context and a question. In this situation, the input prompt can become long. How do people address this?</p> <p>I am using the Hugging Fa...
<p>Unfortunately GPT-3 and GPT-J both have a 2048 token context limitation, and there's nothing you can do about it.</p> <p>On my <a href="https://nlpcloud.io" rel="nofollow noreferrer">NLP Cloud</a> API, the solution I suggest in general is to fine-tune GPT-J. Fine-tuning GPT-J is like giving ton of context to the mod...
deep-learning|nlp|huggingface-transformers|nlp-question-answering|gpt-3
0
374,565
70,918,256
Begginer/ numpy where and copy
<p>I am trying to copy values from one Field2 into Field1 if Field1 is null or NaN. I have tried below where statement as per documentation, but it cuts outliners instead of copyting the value.</p> <p><code>dataframe=np.where(dataframe['field1'].isnull(),np.copy(dataframe['field2']),1)</code></p> <p>I have interpreted ...
<p>You don't need <code>np.copy</code>, nor <code>np.where</code>. Use pandas' <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.mask.html" rel="nofollow noreferrer"><code>Series.mask</code></a> instead</p> <pre><code>dataframe['field1'] = dataframe['field1'].where(dataframe['field1'].isnull(), ...
python|pandas|numpy
4
374,566
70,833,201
Iterating over a DataFrame and appending the score into a column
<p>When I run this code below, it returns <code>'float' object has no attribute 'encode'</code> Im not sure what Im doing wrong, but I want to get the VADER sentiment values for the Titles (which is in a large dataframe) but Im not sure where im going wrong, or how to convert the type of variable to make the object ite...
<p>Without your data to work on, it is har to know. I saw you posted the same question elsewhere and some data so I tested it on:</p> <pre><code> index text 0 0 I can’t believe Bitcoin is going to hit 100k b... 1 1 What new Bitcoin related project are you the m....
python|pandas|list|dataframe|vader
0
374,567
70,897,989
How to use pandas.Series.str.contains to return true value for row after row that contains the given condition
<p>I am using the following code to make a mask of a data frame. The mask means that I return TRUE for all values in a row where one cell in that row has a certain condition, for instance where one cell value is exactly 21.</p> <pre><code> mask_pipe21 = np.column_stack([output[col].str.contains(&quot;^21$&quot;, regex=...
<p>Try</p> <pre><code>s1 = pd.Series(['Mouse', 'dog', 'house and parrot', '23', np.NaN]) s1.str.contains('og').shift(1) &gt;&gt;&gt; 0 NaN 1 False 2 True 3 False 4 False </code></pre> <p>This is not 100% your wanted output. Therefor you maybe want to change the NaN values afterwards.</p>
python|pandas|dataframe|contains
1
374,568
70,881,899
Turning secondary keys into primary keys in dataframe
<p>Pandas Dataframe: Turning secondary keys into primary keys in Python</p> <p>I would like to pass the secondary keys of this plot as primary key. Currently, the primary key is 'ustar' but I want 'time', 'latitude' and 'longitude' to be the primary keys. How do I do this?</p> <pre><code>ustar = ds['ustar'].to_datafram...
<blockquote> <p>I would like to put 'ustar' at the same level as 'time', 'longitude' and 'latitude' in the dataframe</p> </blockquote> <p>I think you want to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer">reset your index</a></p> <pre><co...
python|pandas
0
374,569
70,833,621
How can I convert all values in a column like '€226.5M' or '€100.1K' (type object) to 226.5 or 0.1001 (type float) while working with Pandas?
<p>I have this DataFrame and I know I should use the replace method, but I don't in which way. I want all values in the column to be floats in million euros, so I would erase the '€', also the 'M' and if a value has a 'K' instead of an 'M', erase the K and make the number 1000 times smaller. Thanks!</p> <p><a href="htt...
<p>Create a custom function to convert string values to numeric:</p> <pre><code>mappings = {'M': 1, 'K': 0.001} def to_numeric(sr): df = sr.str.extract('([^€KM]+)([KM]?)') return df[0].astype(float) * df[1].map(mappings).astype(float) # Convert your columns df['Value'] = to_numeric(df['Value']) df['Wage'] = t...
python|pandas|replace
-1
374,570
70,867,360
Explode data frame columns into multiple rows
<p>I have a large dataframe <code>a</code> that I would like to split or explode to become dataframe <code>b</code> (the real dataframe <code>a</code> contains 90 columns).</p> <p>I tried to look up for solutions to a problem similar to this but I did not find since it is not related to the values in cells but to the c...
<p>This approach will generate some intermediate columns which will be removed later on.</p> <p>First bring down those labels (A-1,...) from the header into a column</p> <pre><code>df = pd.melt(a, id_vars=['ID'], var_name='label') </code></pre> <p>Then split the label into character and number</p> <pre><code>df[['char'...
python|pandas|dataframe
2
374,571
70,845,169
Python numpy.corrcoef() got different result in different float number when two doesn't change vector
<pre class="lang-py prettyprint-override"><code>import numpy as np len = 999 a = np.array([1.0]*len) b = np.array([3.5]*len) print(np.corrcoef(a, b)) a = np.array([0.9]*len) b = np.array([3.4]*len) print(np.corrcoef(a, b)) </code></pre> <p>Got result:</p> <pre><code>[[nan nan] [nan nan]] [[ 1. -1.] [-1. 1.]] <...
<p>The correct answer should be na for all, because definition for correlation is (from wiki):</p> <p><a href="https://i.stack.imgur.com/kp0tZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kp0tZ.png" alt="enter image description here" /></a></p> <p>If all your observations are the same, the denomin...
numpy|statistics|data-analysis|numerical-methods
0
374,572
71,071,440
Pandas Drop Rows when a String is Matched to a Longer String in a Column in an Exact Match
<p>I'm trying to drop rows in a pandas DataFrame if a substring in a column exactly matches a string in a list. At the moment I can only get it working for partial matches.</p> <pre><code># list of strings to drop in an exact match drop_list = [&quot;sock&quot;, &quot;shirt&quot;] # initialize data of lists. data = {'...
<p>You can create a set from <code>drop_list</code> and use <code>set.isdisjoint</code> on the split words in each row to evaluate if the exact match appears.</p> <pre><code>drop_set = set(drop_list) msk = df['keyword'].apply(lambda x: drop_set.isdisjoint(x.split())) df = df[msk] </code></pre> <p>Output:</p> <pre><code...
python|pandas|dataframe
1
374,573
71,073,808
Advance year problem appear when plotting (pandas && matplotlib)
<p>My problem is when I plot the users joining by day the advance year appear, it should not have year 2023. I tried to search it into my csv file and there is no row holding the value of 2023.</p> <pre><code>data = pd.read_csv('users-current.csv') #transform datetime to date data['dateCreated'] = pd.to_datetime(data[...
<p>This is because the range of <code>x</code> is automatically generated. Instead, you can explicitly limit a range of <code>x</code> using <code>plt.xlim()</code>, as follows:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import datetime data = pd.read_csv('users-current.csv') #transform dateti...
python|pandas
0
374,574
70,885,170
efficiently vectorize scipy.stats.beta function
<p>I wanted to fit a curve (with <code>scipy.curve_fit</code>) that contains a <code>beta</code> distribution in the formula</p> <pre><code>def f(X,a,b): # X.shape == (2, 100) # X[0] is the column 0 of the matrix X, # the following line doesn't work because a must be a float not an array beta_cdf = be...
<p>finally turns out that <code>scipy.stats.beta.cdf</code> is able to receive a column vector with a list of parameters (thanks @Michael Szczesny for pointing that out).</p> <pre><code>def f(X:np.ndarray, a:float, b:float): beta_cdf = beta.cdf([0,0.5,1], a= a*X[0].reshape((-1, 1)), ...
python|numpy|scipy
0
374,575
71,015,610
Can I load two large csv files in pandas and perform Upsert ( Update / Insert )
<p>I have Two 5GB CSV files with 10 Columns, I need to perform update/Insert logic and generate a final CSV by comparing both CSV files.</p> <p>How to do it in Python Pandas?</p> <p>Ex:</p> <p><a href="https://i.stack.imgur.com/K57sh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K57sh.png" alt="ent...
<p>Try using the isin() method or the merge() method to compare the 2 csv files.</p> <pre><code>import pandas as pd csv1 = pd.read_csv(&quot;file1.csv&quot;) csv2 = pd.read_csv(&quot;file2.csv&quot;) #comparing the data using isin() result = csv1[csv1.apply(tuple,1).isin(csv2.apply(tuple,1))] print(result) #comparin...
python|python-3.x|pandas|dataframe|upsert
1
374,576
71,081,720
TypeError: incompatible index of inserted column with frame index when grouping 2 columns
<p>I have a dataset that looks like this (+ some other cols):</p> <pre><code>Value Theme Country -1.975767 Weather China -0.540979 Fruits China -2.359127 Fruits China -2.815604 Corona Brazil -0.929755 Weather UK -0.929755 Weather UK </code></pre> <p>I wan...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.expanding.html" rel="nofollow noreferrer"><code>DataFrame.expanding</code></a> with remove first level for new column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.droplevel.html" rel="nof...
python|pandas|dataframe|numpy|standard-deviation
2
374,577
70,861,551
Find Pandas column largest/smallest values where dates don't overlap
<p>I have a DataFrame like:</p> <pre><code>df = pd.DataFrame(index = [0,1,2,3,4,5]) df['XYZ'] = [2, 8, 6, 5, 9, 10] df['Date2'] = [&quot;2005-01-06&quot;, &quot;2005-01-07&quot;, &quot;2005-01-08&quot;, &quot;1994-06-08&quot;, &quot;1999-06-15&quot;, &quot;2005-01-09&quot;] df['Date1'] = [&quot;2005-01-02&quot;, &quot;...
<p>This is somewhat involved but hopefully will work for you. We introduce a <code>mask</code> indexed by every date between the min and the max date in your df, where we mark each date as 'used' if it appears in the range, and then use that to reject overlapping rows</p> <p>First we get the min and the max date (while...
python|python-3.x|pandas
1
374,578
70,890,680
How can I get the symbolic gradient [Tensorflow 2.x]
<p>I want to get the symbolic expression for gradient estimation. When I see the output it's quite difficult to understand what's going on.</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf @tf.function def f_k(input_dat): y = tf.matmul(tf.sin(input_dat[0]), input_dat[1]) grads = tf.gr...
<p>The symbolic representation you want will only work in <code>graph</code> mode. Outside of <code>graph</code> mode, eager execution is enabled by default. What you can do is create a new function to print the values and wrap it with the <code>@tf.function</code> decorator like you are already doing for <code>f_k</co...
python|tensorflow|tensorflow2.0|tensorflow2.x
1
374,579
70,825,977
Identify varying rows in pandas dataframe
<p>I have a dataframe:</p> <pre><code>ColA ColB ColC a 0 1 b 3 3 c 1 1 a 0 1 a 1 2 b 3 3 </code></pre> <p>I need to identify every row which has different values while filtering based on a value in a column. Example : when...
<p>If I understand correctly, you can <code>drop_duplicates</code> and then create the result column with <code>groupby</code> and <code>cumcount</code> to get an identifier per unique row per group.</p> <pre><code>print(df.drop_duplicates(subset=['ColA','ColB','ColC']) .assign(result=lambda x: x.groupby('ColA'...
python|pandas|dataframe|rows
0
374,580
70,949,823
Python pandas concatenate all tsv files from directory to new file
<p>I'm trying to do a concatenate a couple hundred files in one directory and write that into a new file in a separate directory. The underlying files each have a header row. The headers in each file are expected to have the same number, name, and position based upon how the data is generated. This is the code I'm usin...
<p>In your tsv files, in some row, the format is wrong. That row has 5 values, but expect 4 values, so the error message is shown.<br /> If you only want 4 values and ignore the exception value, you can use param <code>usecols</code> to set the cols you want.</p> <pre><code>combined_file = pd.concat([pd.read_csv(f) for...
python|python-3.x|pandas
0
374,581
70,923,153
Key error while plotting a bar graph using Matplotlib
<p>I have been facing one issue while I am trying to plot a bar graph using the matplotlib library.</p> <p>Please find the sample data below</p> <p><a href="https://i.stack.imgur.com/3De8U.png" rel="nofollow noreferrer">Sample Data Image</a></p> <pre><code>count_movies_year = n_db.groupby('release_year').agg({'title':'...
<p>When doing a <code>group_by</code>, the column &quot;release_year&quot; no longer exist in you Dataframe, since it's now the index.</p> <p>You have multiple solution :</p> <hr /> <p>using a <code>reset_index</code> as you did, but you should reattribute it to your variable</p> <pre><code>count_movies_year = count_mo...
python|pandas|matplotlib
0
374,582
51,685,660
fromstring() when converting Windows string to numpy under Linux
<p>A Pyro4 server running on 32bit Windows machine is serving numpy image data as a string using <code>img.tostring()</code>, the <code>dtype</code> reported before conversion is <code>int32</code>.</p> <p>The server code looks like:</p> <pre><code>def getLastPhase(self): print("Sending the data now: ") print...
<p>The key point is that in Python 2.x, the <code>str</code> type is (sometimes!) a series of bytes and so not interpreted any further unless you explicitly ask it to be so.</p> <p>In Python 3.x, the <code>str</code> type <em>is</em> interpreted, and as UTF-8 I believe as standard.</p> <p>Therefore you want, on Pytho...
python|linux|windows|numpy|tostring
2
374,583
51,926,303
how to insert flag for column match and non-match using read_sql
<p>I am trying to insert a flag (match/non-match) after the comparing columns for 2 different tables. I am able to compare the two mysql table columns <strong><em>but not getting how I can insert a flag column and get the status (match/non-match)</em></strong></p> <p>The below is an example, consider 2 mysql tables:</...
<p>Can be solved purely in SQL.</p> <pre><code>SELECT tab1.email CASE WHEN tab2.email IS NULL THEN 'non-match' ELSE 'valid' END FROM tab1 left join tab2 on tab1.email =tab2.email" </code></pre> <p>Case / When is how you assign a value conditionally in mysql</p>
python|mysql|pandas
1
374,584
51,987,651
Pandas Filtering Data Based on what appears at the start
<p>I have a dataframe that looks like this:</p> <pre><code>df4 = pd.DataFrame({'Q':['chair', 'desk', '-----monitor', 'chair'], 'R':['red', '-- use blue or dark blue', 'yellow', 'purple'], 'S': ['-- is english spoken?', 'german', 'spanish', 'english']}) Q R ...
<p>Using <code>applymap</code> with <code>in</code> and <code>any</code></p> <pre><code>df4[~df4.applymap(lambda x : '--' in x).any(1)] Out[287]: Q R S 3 chair purple english </code></pre> <p>Update only exclude the certain at the beginning.</p> <pre><code>df4[~df4.applymap(lambda x : str.sta...
python|python-3.x|pandas
6
374,585
51,816,647
For unsupervised learning, how to generate image set
<p>I've got unlabeled 500 pieces of RGB color image set(200x300pixel) for unsupervised learning(CNN, GAN, autoencoder). I want to import my image set to tensorflow, instead of MNIST example. Do I need to transform them in CSV file?</p> <pre><code>import tensorflow as tf import numpy as np import matplotlib.pyplot as p...
<p>This is part of my code that trains a GAN. The files are read like this. That is one way to do this.</p> <pre><code>filenames = tf.train.string_input_producer( tf.train.match_filenames_once("D:/TensorFlow/resizedimages/*.png")) </code></pre> <p>Code for reference is this.</p> <pre><code>def train(): filen...
tensorflow|image-processing
0
374,586
51,909,757
Insert rows based on values pandas dataframe
<p>I have this:</p> <p><a href="https://i.stack.imgur.com/nhogL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nhogL.png" alt="enter image description here"></a></p> <p>I would like to achieve this using pandas:</p> <p><a href="https://i.stack.imgur.com/uyacb.png" rel="nofollow noreferrer"><img s...
<p>I may be unsure about about what you want, but I believe you are trying to add rows of one data frame to another data frame:</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow noreferrer">Use pd.concat()</a></p>
python|pandas|insert|append|rows
0
374,587
51,939,022
Correct way to create Pytorch dataset that returns sequence of data for RNN?
<p>I am attempting to train an RNN on time series data, and while there are plenty of tutorials out there on how to build a RNN model I am having some trouble with building the dataloader object for this task. The data is all going to be the same length, so no need for padding as well. The approach I have taken so far ...
<p>If I understood correctly you have time series data and you want to crate batches of data with the same length by sampling from it? I think you can use <strong>Dataset</strong> for returning just one sample of data as it was initially intended by the PyTorch developers. You can stack them in the batch with your own ...
python|deep-learning|dataset|pytorch|rnn
3
374,588
51,643,755
Numpy reshape "reversal"
<p>I read a 4D array from a file which is given in a 2D form i, j, k, x, y, z. <a href="https://i.stack.imgur.com/Aft8s.png" rel="nofollow noreferrer">Input file header and shape</a> I use numpy.reshape to reshape the 2D array to it's 3-D form. After making changes to this, I wish to write the file exactly the same or...
<p>To "reverse" a reshape, you can just call <code>reshape</code> again on the array to reshape it into the original dimensions.</p> <p>If you have an array <code>x</code> with dimensions (<code>n</code>, <code>m</code>) then:</p> <pre><code>x.reshape(kmax, jmax, imax, 6).reshape(n, m) == x </code></pre>
python|numpy|multidimensional-array|reshape
5
374,589
51,608,346
Bitwise not True (including NaN) in pandas DataFrame
<p>I have a data frame which looks like:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({"id": range(5), "is_bar": [np.nan, np.nan, False, True, False], "is_foo": [True, False, True, True, False]}) </code></pre> <p>Now I want rows of <code>df</code> where are foo, but not bar or bar is missi...
<p>I think need <code>fillna</code>:</p> <pre><code>df = df.loc[df["is_foo"] &amp; ~df["is_bar"].fillna(False)] print (df) id is_bar is_foo 0 0 NaN True 2 2 False True </code></pre>
python|pandas
1
374,590
51,575,584
Can someone explain to me reduce sum in tensorFlow.js
<p>When I use the reduce sum of tensorFlow.js as : <a href="https://js.tensorflow.org/api/0.12.0/#sum" rel="nofollow noreferrer">https://js.tensorflow.org/api/0.12.0/#sum</a> , I was thinking that it would simply add all the element of an array to get a sum. But apparently it's something more complicated than that.</p...
<p>There were a problem with Ubuntu and tfjs 0.12.0</p>
tensorflow.js
0
374,591
51,827,536
How to set the ticks of log scale for x&y axis?
<p>I want to plot a log scale graph without scientific notation.</p> <pre><code> import matplotlib as mpl import matplotlib.pyplot as plt plt.plot(np.arange(0,10,0.1)) plt.xscale('log') plt.yscale('log') plt.xlim(0.1,100) plt.ylim(1,10) plt.gca().xaxis.set_major_formatter(mpl.ticker.S...
<p><strong>1. Get rid of Scientific notation.</strong></p> <p>The ticks are major and minor ticks, hence you would need to set the minor formatter as well:</p> <pre><code>plt.gca().yaxis.set_major_formatter(mpl.ticker.ScalarFormatter()) plt.gca().yaxis.set_minor_formatter(mpl.ticker.ScalarFormatter()) </code></pre> ...
python|python-3.x|numpy|matplotlib|plot
3
374,592
51,749,235
Pandas: filling placeholders in string column
<p>I am working with a pandas DataFrame looking as follows:</p> <pre><code>df = pd.DataFrame( [['There are # people', '3', np.nan], ['# out of # people are there', 'Five', 'eight'], ['Only # are here', '2', np.nan], ['The rest is at home', np.nan, np.nan]]) </code></pre> <p>resulting in:</p> <pre><code> ...
<p>Using string format </p> <pre><code>df=df.replace({'#':'%s',np.nan:'NaN'},regex=True) l=[] for x , y in df.iterrows(): if y[2]=='NaN' and y[1]=='NaN': l.append(y[0]) elif y[2]=='NaN': l.append(y[0] % (y[1])) else: l.append(y[0] % (y[1], y[2])) l Out[339]: ['There are 3 people...
python|pandas|string-formatting
2
374,593
51,651,476
tqdm progress bar with json string stuck
<p>I have a list of json strings, and I'm converting them to a list of dicts. </p> <p>I do that to combine them in one final json string, to be converted later to a Pandas Dataframe:</p> <pre><code>s1 = '{ "id": 11, "label": "REF", "claim": "Lorelai Gilmore", "ce": [[[1,2, "Gilmore", 3]]]}' s2 = '{ "id": 0, "label": ...
<p>Try this:</p> <pre><code>combine = [] for i in tqdm([json.loads(item) for item in s]): combine.append(i) </code></pre>
json|python-3.x|pandas|tqdm
1
374,594
51,730,651
Pandas: merging dataframes using a loop - MemoryError
<p>I have a few <strong>dataframes</strong> stored inside a <strong>dict</strong> called <strong>my_dict</strong>. The keys of the dict are stored inside a list called <strong>filter_list</strong>.</p> <pre><code>filter_list = ["A", "B", "C", ...] </code></pre> <p><strong>my_dict[A]</strong> gives me the following r...
<p>I think what you try to achieve can be done with <code>pd.concat</code>:</p> <pre><code>result = (pd.concat([my_dict[key].set_index('links') for key in filter_list], axis=1,sort=False) .fillna(0).reset_index()) result[result.columns[1:]] = result[result.columns[1:]].astype(int) </cod...
python|pandas
1
374,595
51,849,186
When using Pandas .groupby, why use .agg versus directly using the function eg .sum()
<p>In Python, to obtain summaries by group, I use <code>groupby().agg(fx())</code>; eg <code>groupby('variable').agg('sum')</code>. What is the difference between that and directly using the function, eg; <code>groupby('variable').sum()</code> ?</p>
<p><strong><em>Setup</em></strong></p> <pre><code>df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]}) </code></pre> <p>The primary benefit of using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.agg.html" rel="nofollow noreferrer"><code>agg</code></a> is stated in <a href="https://pandas...
python|pandas|pandas-groupby
6
374,596
51,593,871
calculating mean with a condition on python pandas Group by on two columns. And print only the mean for each category?
<p>Input </p> <pre><code>Fruit Count Price tag Apple 55 35 red Orange 60 40 orange Apple 60 36 red Apple 70 41 red </code></pre> <p>Output 1</p> <pre><code>Fruit Mean tag Apple 35.5 red Orange 40 orange </code></pre> <p>I need <strong>mean</strong> on condition price between 31 and 40 </p...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow noreferrer"><code>between</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> for filtering:</p> <...
python-3.x|pandas
1
374,597
51,689,035
Spyder: Check failed: PyBfloat16_Type.tp_base != nullptr error while starting kernel
<p>I am getting some weird error when starting Spyder 3.6. The error reads:</p> <pre><code>An error ocurred while starting the kernel 2018 15:37:39.970424: F T:\src\github\tensorflow\tensorflow\python\lib\core\bfloat16.cc:664] Check failed: PyBfloat16_Type.tp_base != nullptr </code></pre> <p>I Googled for a solutio...
<p>Run:</p> <pre><code>conda install tensorflow </code></pre> <p>This will solve the problem</p>
python|python-3.x|tensorflow|anaconda|spyder
0
374,598
51,890,425
Plot categorical data with matplotlib - transposed pandas dataframe
<p>I have data for two groups in a pandas dataframe, with for each group the mean of 3 different items of a scale:</p> <pre><code> item1 item2 item3 group 1 2.807692 3.115385 3.923077 2 2.909091 2.454545 3.909091 </code></pre> <p>I would like to...
<p>When I transpose the dataframe you provide the result looks like this</p> <pre><code> 1 2 item1 2.807692 2.909091 item2 3.115385 2.454545 item3 3.923077 3.909091 </code></pre> <p>therefore <code>data.index.values</code> returns <code>array(['item1', 'item2', 'item3'], dtype=object)</code>, a...
python|pandas|matplotlib|transpose
1
374,599
51,859,857
Search through a dataframe for a partial string match and put the rows into a new dataframe with only their IDs
<p>I have a dataframe of publications that have the following rows:</p> <p>publication_ID , title, author_name, date 12344, Design style, Jake Kreath, 20071208 12334, Power of Why, Samantha Finn, 20150704</p> <p>I ask the user for a string and use that string to search through the titles.</p> <p><strong>The go...
<p>Use a combination of <code>.str.contains</code> and <code>.loc</code></p> <pre><code>publications.loc[publications.title.str.contains(search_term), ['title', 'publication_ID']] </code></pre> <p>Just be careful, because if your title is <code>'nightlife'</code> and someone searches for <code>'night'</code> this wil...
python|string|python-3.x|pandas|dataframe
1