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
359,300
22,813,160
filling numpy array by index
<p>I have a function which gives me the index for a given value. Eg,</p> <pre><code>def F(value): index = do_something(value) return index </code></pre> <p>I want to use this index to fill a huge numpy array by 1s. Lets call array <code>features</code></p> <pre><code>l = [1,4,2,3,7,5,3,6,.....] </code></pre> ...
<p>If you can vectorize <code>F(value)</code> you could write something like</p> <pre><code>indices = np.arange(features.shape[0]) feature_indices = F(l) features.flat[indices, feature_indices] = 1 </code></pre>
python|arrays|numpy
1
359,301
22,793,601
Using numba.autojit on a lambdify'd sympy expression
<p>I've used numpy in the past and am fairly comfortable with it, but sometimes when I've wanted a little extra speed, I've been able to use the numba.autojit decorator. Easy. The problem now is I'm currently working on a chain of sympy expressions and numba (jit OR autojit) isn't sure what to make of the function out ...
<p>To answer your second question, the way lambdify works is that it creates a string form of the expression as a lambda, and <code>eval</code>s it in a namespace with the numerical functions. </p> <p>For instance, for <code>lambdify(x, sin(x), 'numpy')</code>, <code>sin(x)</code> is converted to <code>'sin(x)'</code>...
python|numpy|sympy|numba
4
359,302
22,597,353
Build diagonal matrix without using for loop
<p>I am trying to build the following matrix in Python without using a <code>for</code> loop:</p> <pre><code>A [[ 0.1 0.2 0. 0. 0. ] [ 1. 2. 3. 0. 0. ] [ 0. 1. 2. 3. 0. ] [ 0. 0. 1. 2. 3. ] [ 0. 0. 0. 4. 5. ]] </code></pre> <p>I tried the <code>fill_diagonal</code> method i...
<p>There are functions for this in <code>scipy.sparse</code>, e.g.:</p> <pre><code>from scipy.sparse import diags C = diags([1,2,3], [-1,0,1], shape=(5,5), dtype=float) C = C.toarray() C[0, 0] = 0.1 C[0, 1] = 0.2 C[-1, -2] = 4 C[-1, -1] = 5 </code></pre> <p>Diagonal matrices are generally very sparse, so you could...
python|numpy|scipy|diagonal
4
359,303
22,740,666
Python : Separating a .txt file into columns and finding the most frequent data item in one of the columns
<p>I read from a file and stored into artists_tag with column names . Now this file has multiple columns and I need to generate a new data structure which has 2 columns from the artists_tag as it is and the most frequent value from the 'Tag' column as the 3rd column value. Here is what I have written as of now: </...
<p>I'm sure there is a more succint way of doing it, but this should get you started:</p> <pre><code># returns a df grouped by ArtistID and Tag tag_counts = artists_tags.groupby(['ArtistID', 'Tag']) # sum up tag counts and sort in descending order tag_counts = tag_counts.sum().sort('Count', ascending=False).reset_inde...
python|data-structures|syntax|pandas
0
359,304
22,691,010
How to print a groupby object
<p>I want to print the result of grouping with Pandas.</p> <p>I have a dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A': ['one', 'one', 'two', 'three', 'three', 'one'], 'B': range(6)}) print(df) A B 0 one 0 1 one 1 2 two 2 3 three 3 4 three 4 5 one 5 </code></pre> <p>...
<p>Simply do:</p> <pre><code>grouped_df = df.groupby('A') for key, item in grouped_df: print(grouped_df.get_group(key), &quot;\n\n&quot;) </code></pre> <hr /> <blockquote> <p><strong>Deprecation Notice</strong>: <code>ix</code> was <a href="https://pandas.pydata.org/docs/whatsnew/v0.20.0.html#deprecate-ix" rel="no...
python|pandas
137
359,305
15,073,504
Dense random matrix to (un)directed graph as sparse matrix?
<p>I want to work on some "maximum flow" problems to understand the algorithms, but my notion of what would be a simple set-up to test them is proving difficult to implement.</p> <p>Take a look at this Project Euler problem: <a href="http://projecteuler.net/problem=83" rel="nofollow">http://projecteuler.net/problem=83...
<p>Here is the ipython notebook code to calculate the edges of Project Euler problem 83. Instead of 2D coordinates, I use index for every elements in the matrix.</p> <pre><code>In [1]: #load the data import numpy as np from StringIO import StringIO data = StringIO("""131 673 234 103 18 201 96 342 965 150 630 803 74...
python|numpy
-1
359,306
15,435,551
Calculate euclidean distance with numpy
<p>I have a point set which I have stored its coordinates in three different arrays (xa, ya, za). Now, I want to calculate the euclidean distance between each point of this point set (xa[0], ya[0], za[0] and so on) with all the points of an another point set (xb, yb, zb) and every time store the minimum distance in a ...
<p>A different solution would be to use the spatial module from scipy, the KDTree in particular.</p> <p>This class learn from a set of data and can be interrogated given a new dataset:</p> <pre><code>from scipy.spatial import KDTree # create some fake data x = arange(20) y = rand(20) z = x**2 # put them togheter, sho...
python|numpy
8
359,307
15,206,206
Concatenate numpy arrays inside a function and return it?
<p>How to concatenate two numpy arrays inside a function and return it considering the following program</p> <pre><code>#!/usr/bin/env python import numpy as np def myfunction(myarray = np.zeros(0)): print "myfunction : before = ", myarray # This line should not be modified data = np.loadtxt("test.txt", un...
<p>You should return the value </p> <p>Modify the function like that:</p> <pre><code>def myfunction(myarray = np.zeros(0)): print "myfunction : before = ", myarray # This line should not be modified data = np.loadtxt("test.txt", unpack=True) # This line should not be modified concatenated = np.concaten...
python|arrays|numpy|pass-by-reference
2
359,308
14,992,244
image feature detection with large structuring element
<p>I am trying to extract some features from an image but each of the extracted features are really small. The easiest way to extract larger features seems to be to use a larger structuring element but the following code fails when <code>ITER &gt; 1</code>.</p> <pre><code>from scipy import ndimage,misc lena=misc.lena(...
<p>The parameter <code>structure</code> for the <code>ndimage.label</code> function is used to determine the connectivity of the input. When you represent the input as a rectangular matrix, this connectivity commonly regards either the 4 or the 8 neighbors around a point <code>p</code>. Scipy follows this convention an...
python|image-processing|numpy|python-3.x|scipy
3
359,309
15,341,714
Is there a fast way to compare one element in a numpy array to the rest of the elements in that array?
<p>I have an array, and I want to see if any element in that array is greater than or equal to any other element in that array. I could do two for loops, but my array has a length of 10,000 or greater, and so that created a very slow program. Anyway I can do this faster?</p> <p>[EDIT] I only need it to see if it's gre...
<p>The first value that is greater than a later value necessarily corresponds to the minimum among local minima:</p> <pre><code>k = np.array([0,1,2,3,4,5,6,5,4,10]) lm_i = np.where(np.diff(np.sign(np.diff(k))) &gt; 0)[0] + 1 mlm = np.min(k[lm_i]) mlm_i = lm_i[np.argmin(k[lm_i])] </code></pre> <p>The index of the firs...
python|arrays|numpy
5
359,310
14,974,459
Pandas Column Construction with np.where()
<p>I'm working through an assignment with Pandas and am using np.where() to create add a column to a Pandas DataFrame with three possible values:</p> <pre><code>fips_df['geog_type'] = np.where(fips_df.fips.str[-3:] != '000', 'county', np.where(fips_df.fips.str[:] == '00000', 'country', 'state')) </code></pre> <p>The ...
<p>Just in case, you can create a new column with much less effort. E.g.:</p> <pre><code>In [1]: import pandas as pd In [2]: import numpy as np In [3]: df = pd.DataFrame(np.random.uniform(size=10)) In [4]: df Out[4]: 0 0 0.366489 1 0.697744 2 0.570066 3 0.756647 4 0.036149 5 0.817588 6 0.884244 7 ...
pandas
4
359,311
15,420,672
IPython Notebook: What is the default encoding?
<p>I have created a package using the encoding utf-8. </p> <p>When calling a function, it returns a <code>DataFrame</code>, with a column coded in utf-8.</p> <p>When using IPython at the command line, I don't have any problems showing the content of this table. When using the Notebook, it crashes with the error <code...
<p>I had the same problem recently, and indeed setting the default encoding to UTF-8 did the trick:</p> <pre><code>import sys reload(sys) sys.setdefaultencoding("utf-8") </code></pre> <p>Running <code>sys.getdefaultencoding()</code> yielded <code>'ascii'</code> on my environment (Python 2.7.3), so I guess that's the ...
pandas|ipython|ipython-notebook
21
359,312
13,595,945
python genfromtxt problems
<p>I am new to Python...here is my problem. For an optimizing subroutine I am testing in Python, I need to parse a csv file with numbers. </p> <p>The format of the csv file is thus:</p> <pre><code>Support load summary for anchor at node 5, Load combination,FX (N),FY (N),FZ (N),MX (Nm),MY (Nm),MZ (Nm),, Sustained,-...
<p>I reduced your problem to the following code. It checks for nans and empty input strings.</p> <pre><code>from StringIO import StringIO import numpy as np def getnumbers(s): try: res = np.genfromtxt(s, delimiter=",") return res[np.where(np.isnan(res), False, True)] except IOError as ioe: ...
python|numpy|genfromtxt
1
359,313
29,563,788
How to draw N elements of random indices from numpy array without repetition?
<p>Say, I have a numpy array defined as:</p> <pre><code>X = numpy.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) </code></pre> <p>Now I want to draw 3 elements from this array, but with random indices and without repetition, so I'll get, say:</p> <pre><code>X_random_draw = numpy.array([5, 0, 9] </code></pre> <p>How can I ac...
<p>With NumPy 1.7 or newer, use <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html"><code>np.random.choice</code></a>, with <code>replace=False</code>:</p> <pre><code>In [85]: X = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [86]: np.random.choice(X, 3, replace=False) Out[86]: ar...
python|arrays|numpy
8
359,314
29,544,728
Using a lookup table with openCV and NumPy
<p>I'm trying to use NumPy and CV2 by doing pixel math on an array of pixels then using a lookup table and replacing that pixel with the lookup table's value.</p> <p>This works but it is too slow,</p> <pre><code>image = cv2.imread('C:\\Users\\Event38\\Desktop\\IMG_2231.JPG') height, width, depth = image.shape image =...
<p>You can try OpenCV's Look Up Table to apply a LUT in one shot. Here is the <a href="http://docs.opencv.org/modules/core/doc/operations_on_arrays.html?highlight=lut#lut" rel="nofollow">documentation</a> </p> <p><strong>C++</strong> </p> <pre><code>void LUT(InputArray src, InputArray lut, OutputArray dst, int inter...
python|opencv|numpy|pixel
2
359,315
29,500,650
Python How to find average of columns using dataframes apply method
<p>This is a question on Udacity Data Science Nanodegree and I can't figure it out. The instructions are:</p> <p>Using the dataframe's apply method, create a new Series called <code>avg_medal_count</code> that indicates the average number of gold, silver, and bronze medals earned amongst countries who earned at least ...
<p>I would first modify how you import the data to:</p> <pre><code>df = DataFrame(olympic_medal_counts).set_index('country_name') </code></pre> <p>I would then calculate a new column containing the sum of the rows for the toal number of medals per country.</p> <pre><code>df['medal total'] = df.sum(axis=1) </code></p...
python|numpy|pandas
3
359,316
29,585,260
Plotting pandas time and category
<p>I really can't get out of this. Here is my table:</p> <p>where grade can be A,B,C</p> <pre><code>doc_id, grade, timestamp 1, A, 27/01/15 2, A, 27/01/15 3, B, 27/01/15 ... </code></pre> <p>My aim is to show a graph with three lines, showing how many A, B and C I got through time.</p> <p>I can only think of this:<...
<p>try this:</p> <pre><code>df2 = df.groupby(['timestamp', 'grade']).grade.size().unstack().cumsum().ffill().fillna(0) </code></pre> <p>It basically pivots by date and grade, rolling forward the cumulative sum.</p> <pre><code>&gt;&gt;&gt; df2 grade A B C timestamp 4/1/15 0 1 0 4/11/15 ...
python|pandas|matplotlib
1
359,317
29,782,898
Combine Pandas data frame column values into new column
<p>I'm working with Pandas and I have a data frame where we can have one of three values populated:</p> <pre><code>ID_1 ID_2 ID_3 abc NaN NaN NaN def NaN NaN NaN ghi NaN NaN jkl NaN mno NaN pqr NaN NaN </code></pre> <p>And my goal is to combine these three columns...
<p>You can use the property that summing will concatenate the string values, so you could call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html#pandas.DataFrame.fillna"><code>fillna</code></a> and pass an empty str and the call <a href="http://pandas.pydata.org/pandas-docs/sta...
python|pandas|dataframe
13
359,318
29,768,087
Np.where function
<p>I've got a little problem understanding the where function in numpy. The ‘<strong>times</strong>’ array contains the discrete epochs at which GPS measurements exist (rounded to the nearest second). The ‘<strong>locations</strong>’ array contains the discrete values of the latitude, longitude and altitude of the sat...
<p>I think the problem is your dual slices. Further, having an array of arrays could lead to weird problems (I assume you mean an object array of 2D arrays). </p> <p>So I think you need to <code>dstack</code> <code>tracking</code> into a 3D array, then do <code>where</code> on that. If the array is already 3D, then...
numpy|gps|location|where
0
359,319
29,634,091
IOError [Errno 13] when using numpy.loadtext?
<p>I have a function that polls a folder for new files, then loads them using numpy.loadtext when it shows up. The function is called from a while loop that runs for 30 seconds. The function works properly most of the time, but for some files, seemingly at random, I get the error IOError: [Errno 13] Permission denied: ...
<p>Have you tried opening the file as read only, may be a conflict if the file is accessed by another application (or is still currently being created). </p> <pre><code># New File if added: with open(mydir + added[0], 'r') as f: raw = numpy.loadtxt(f) </code></pre> <p>You could also try some form of IOErr...
python|numpy
0
359,320
62,198,773
How to edit the values in one column when a certain value is realised in another in pandas DataFrame?
<p>I have the following DataFrame with several columns beyond the ones included here:</p> <pre><code> Col2 Col3 Col4 0 3682 US91892 US 1 7568 US91234 US 2 3546 UKIPD GB 3 7892 UKI43 GB 4 1243 US92345 US </code></pre> <p>For this if col4 = US I want to get on...
<p>Another way is to use boolean indexing:</p> <pre><code>df.loc[df.Col4=='US', 'Col3'] = df.Col3.str[-5:] </code></pre> <p>Output:</p> <pre><code> Col2 Col3 Col4 0 3682 91892 US 1 7568 91234 US 2 3546 UKIPD GB 3 7892 UKI43 GB 4 1243 92345 US </code></pre>
python|pandas|multiple-columns
2
359,321
62,146,156
GCC compilation error while building tensorflow using docker on mac(host) running ubuntu
<p><strong>System information</strong></p> <ul> <li>OS Platform: host: mac 14.10 </li> <li>docker image: tensorflow/tensorflow:latest-devel </li> <li>TensorFlow version: 2.2</li> <li>Python version: 3.6.9</li> <li>building tensorflow from source using docker on mac with ubuntu in docker image</li> <li>Bazel version (...
<p>The message <code>./third_party/eigen3/unsupported/Eigen/CXX11/src/FixedPoint/PacketMathAVX2.h:37:41: warning: ignoring attributes on template argument '__m128i {aka __vector(2) long long int}' [-Wignored-attributes] typedef eigen_packet_wrapper&lt;__m128i, 28&gt; Packet4q32i;</code></p> <p>is not a serious error ...
python|docker|gcc|tensorflow2.0
0
359,322
62,311,972
issue with fitting data with TensorFlow Keras
<p>I am attempting to create a model for deciphering hand written text. The issue I am encountering right now is feeding my data to the model.</p> <p>I start out with a list of file names with each file as a picture. I also have a list of labels for each.</p> <p>I then iterate through the file names and load those im...
<p>Conv2D expects input:</p> <blockquote> <p>Input shape: 4D tensor with shape: (batch_size, channels, rows, cols) if data_format='channels_first' or 4D tensor with shape: (batch_size, rows, cols, channels) if data_format='channels_last'.</p> </blockquote> <p><a href="https://www.tensorflow.org/api_docs/python/...
tensorflow|keras|neural-network
0
359,323
62,255,474
TypeError: 'DataFrame' object is not callable for DBscan
<p>Data set is below</p> <pre><code>storeid,revenue,profit,country 101,11434,2345,IN 101,12132,3445,US 102,21343,4545,CH 103,34423,3432,CH 103,43435,3234,JP 103,34345,3335,IN </code></pre> <p>Code is below</p> <pre><code>import pandas as pd from sklearn.cluster import DBSCAN import matplotlib.pyplot as plt import nu...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <code>[]</code> for filter by mask:</p> <pre><code>print(outliers_df[model.labels_==-1]) revenue profit country_CH country_IN country_JP 0 1...
python|pandas|machine-learning|dbscan
1
359,324
62,153,185
Python - Compare TS in 2 col and 2 rows
<p>I've a Df with multiple engine, a start and end Dt, and an info code. (exemple here)</p> <pre><code> engine start end duration info energy 20 a 2020-04-16 09:40:00 2020-04-17 00:00:00 860 1 1982 21 a 2020-04-17 00:01:00 2020-04-18 00:00:00 1439 1 3...
<p>You can do this using <code>groupby</code> as follows:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({"engine": ["a"]*10, "start": pd.to_datetime(pd.Series(["2020-04-16 09:40:00", "2020-04-17 00:01:00", "2020-04-18 ...
python|pandas|dataframe
1
359,325
62,346,577
Cumsum with restarts
<p>I want to bin the data every time the threshold 10000 is exceeded.</p> <p>I have tried this with no luck:</p> <pre><code># data which is an array of floats diff = np.diff(np.cumsum(data)//10000, prepend=0) indices = (np.argwhere(diff &gt; 0)).flatten() </code></pre> <p>The problem is that all the bins does not ...
<p>Not sure how this could be vectorized, if it even can be, since by taking the cumulative sum you'll be propagating the remainders each time the threshold is surpassed. So probably this is a good case for <code>numba</code>, which will compile the code down to C level, allowing for a loopy but performant approach:</p...
python|numpy
4
359,326
62,461,015
pandas fill only group meeting criteria?
<p>How do you fill only groups inside a dataframe which are not fully nulls?</p> <p>In the dataframe below, only groups with <code>df.A=b</code> and <code>df.A=c</code> should get filled.</p> <pre><code>df A B 0 a NaN 1 a NaN 2 a NaN 3 a NaN 4 b 4.0 5 b NaN 6 b 6.0 7 ...
<p>We can do <code>groupby</code> </p> <pre><code>df.B=df.groupby('A').B.apply(lambda x : x.ffill().bfill()) </code></pre>
python|pandas|data-science|data-cleaning
1
359,327
62,048,251
Find (space separated) compound words in a DataFrame
<p>I have two dataframes:</p> <p>the first is called Roster:</p> <pre><code>| u_id | Skills | |------|------------------------------------------------| | 1 | ai, deep learning, machine learning, nlp | | 2 | computer vision, statistics, python, css | | 3 | d...
<p>I created cleaner dataframes for <strong>Roster</strong> and <strong>Taxonomy</strong>, so that they can be easily run. Then, I created a list object column called <strong>all_skills</strong>. From there, start your loop with <code>zip()</code>, so that you can iterate through multiple columns simultaneously, so th...
python|pandas|nlp
1
359,328
62,102,397
numpy not-equally distant range of numbers
<p>Using np.linspace(0,3,100) would give a range of numbers that are equally distant between 0 and 3. what's the best way to get a range of numbers between 0 and 3 but more densely close to 3 and less dense in the beginning, perhaps in a logarithmic way.</p> <p>----------edit</p> <p>(np.log10(1), np.log10(4), 100)-1 ...
<p>Try <a href="https://numpy.org/doc/stable/reference/generated/numpy.logspace.html" rel="nofollow noreferrer"><code>np.logspace()</code></a>. You will need to use <code>np.log10()</code> for arguments.</p>
python|numpy
1
359,329
62,316,736
TensorFlow1.15, the inner logic of Estimator's input_fn? Or the inner logic of MirroredStrategy?
<p>I am pretraining BERT in 1 machine with 4 GPU, not 1 GPU.</p> <p>For each training step, I am wondering whether the <code>input_fn</code> give 1 GPU 1 batch or give 4 GPU 1 batch.</p> <p>The mirrow strategy code:</p> <pre><code> distribution = tf.contrib.distribute.MirroredStrategy( devices=["device:GP...
<p>According to <a href="https://github.com/guotong1988/BERT-GPU/blob/master/run_pretraining_gpu_v2.py" rel="nofollow noreferrer">BERT-GPU</a>.</p> <p><code>input_fn</code> return 1 batch for 1 GPU.</p> <p>The <code>batch_size</code> is for 1 GPU.</p>
tensorflow|deep-learning|tensorflow-datasets|tensorflow-estimator|bert-language-model
0
359,330
62,312,639
Why am I getting a 'hashable' error when combining two dataframes?
<p>I have two DataFrames and I'm attempting to combine them as follows:</p> <pre><code>df3 = df1.combine(df2, np.mean) </code></pre> <p>However, I'm getting the following error:</p> <p><code>TypeError: 'Series' objects are mutable, thus they cannot be hashed</code>.</p> <p>I'm not sure I understand why I'm getting ...
<p><code>np.mean</code> takes one positional argument as the input array. So you cannot and should not do</p> <pre><code> np.mean(series1, series2) </code></pre> <p>Since the command above will interpret <code>series2</code> as the second argument for <code>np.mean</code>, which is <code>axis</code>. But this argumen...
python|pandas|dataframe
1
359,331
62,127,261
python, struggling to plot CSV file
<p>as the title explains I'm trying to read in a CSV file and plot it, the file is in the following format:</p> <pre><code>Dishwasher,60,1,1,1,0,0,1 Washing Machine,200,0,0,0,0,1,1 </code></pre> <p>where I just want to plot the 6 digits at the end.</p> <p>Here is my code so far:</p> <pre><code>import matplotlib.py...
<p>in those 2 lines:</p> <pre><code>y1=int((rows[0])-2) y2=int((rows[1])-2) </code></pre> <p>you are taking the first and second elements of the list subtracting 2 and transforming on an int the assigning it to the variables <code>y1</code> and <code>y2</code> that means you cant subtract an int from a list</p> <p...
python|numpy|matplotlib
4
359,332
62,110,302
How to sort a pandas dataframe on two (or more) different columns, in a particular order
<h1>Note</h1> <p><code>df2</code> is the <strong>only</strong> thing that can be used here - using <code>df</code> or <code>df1</code> would be to use data that isn't possible. The data is received as <code>df2</code>, it wants to be manipulated to the form of <code>df1</code>. Neither <code>df1</code> or <code>df</co...
<p>Let us try <code>pd.Categorical</code></p> <pre><code>df2.one=pd.Categorical(df2.one,categories=df1.one.unique()) df2.two=pd.Categorical(df2.two,categories=df1.two.unique()) df2=df2.sort_values(['one','two']) df2 one two 5 dog orange 4 dog apple 1 dog grape 7 ant orange 6 ant apple 8 ant grap...
python|pandas|dataframe|data-manipulation
2
359,333
62,146,252
Calculate perc of each element in a list for each value in column in pandas dataframe
<p>The df I am working on looks like this</p> <pre><code>co1 col2 A ['1','2','er'] A [] B ['1','3','4','abc'] B ['5'] C [] </code></pre> <p>I want to calculate the % of each element in the list in col2 for each value in col1. i.e calculate % of 1 for A, calculate % of 2 for A, calculate % of ab...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferrer"><code>DataF...
python|python-3.x|pandas|dataframe|pandas-groupby
2
359,334
62,246,762
Look Up Dictionary Tensorflow for a List inside array
<p>i have a Tensor where i want to lookup and output a int for every word. </p> <p>How can i scroll over this and put out a value for every word? </p> <pre><code>table =tf.lookup.StaticHashTable(tf.lookup.TextFileInitializer(vocab_filename, tf.string, 0, tf.int64, 1, delimiter="!"),7) out=table.lookup(data[0]) print...
<p>You can use the <code>StaticVocabularyTable</code> to achieve the same. Below is an example.</p> <pre><code>vocab = ["&lt;1H OCEAN", "INLAND", "NEAR OCEAN", "NEAR BAY", "ISLAND"] indices = tf.range(len(vocab), dtype=tf.int64) table_init = tf.lookup.KeyValueTensorInitializer(vocab, indices) num_oov_buckets = 20 tabl...
python|tensorflow|dictionary
1
359,335
62,435,475
How to count the number of unique elements in a column in a Pandas dataframe
<p>Say I have a data frame that records a customer (denoted by a letter) and the date that they arrived in a store.</p> <pre><code> customer date A 2010-01-01 B 2010-01-01 A 2010-01-02 C 2010-01-02 D 2010-01-03 D 2010-01-03 </...
<p>try this, <code>drop_duplicates</code> along with <code>groupby</code></p> <pre><code>&gt;&gt;&gt; df.drop_duplicates(["customer"]).groupby("date")['customer'].nunique().cumsum() date 2010-01-01 2 2010-01-02 3 2010-01-03 4 Name: customer, dtype: int64 </code></pre>
python|pandas|dataframe|unique
3
359,336
62,335,665
Best practice working with AI models from inside docker containers
<p>I’m using TensorFlow docker images for the first time. Before I get going with big time investments, I want to make sure I understand where files should be. Should I store, run, create, save all files inside the container and remove what I want to later? Should any files remain on the host?</p>
<p>Edit the files always outside the container. I recommend you Docker Compose to setup your Docker environment. Here's an example:</p> <pre><code># Use version 2.3 of Docker Compose to access the GPU with NVIDIA-Docker # (it's the only version that supports GPUs version: '2.3' services: ai_container: image: ...
docker|tensorflow2.0
1
359,337
62,402,795
Most efficient way to process list of list of arrays of varying lengths in python
<p>I have a dictionary that contains lists of values of varying lengths. I need to be able to process all the values at a particular index (column) in each list together. The only way I have found to is to convert it to a pandas dataframe. However, this is very slow for the actual dataset which can include 1000+ events...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.from_dict.html" rel="nofollow noreferrer"><code>DataFrame.from_dict</code></a> and parameter <code>orient='index'</code>:</p> <pre><code>s = pd.DataFrame.from_dict(event_dict, orient='index').mean() print (s) 0 1.000000 1 ...
python|pandas|dataframe
4
359,338
62,143,572
Python Pandas: TypeError: first argument must be string or compiled pattern in user defined function
<p>I have defined a function which looks like below:</p> <pre><code>def incident_rate(substation,year,events): age = conductor_yearly_df.loc[conductor_yearly_df['SUBSTATION']==substation,conductor_yearly_df.columns.str.contains(year)].reset_index(drop=True).values[0][0] length = conductor_yearly_df.loc[conduc...
<p>Change year to string with <code>str(year)</code>, since <code>str.contains</code> accept type of string </p> <pre><code>age = conductor_yearly_df.loc[conductor_yearly_df['SUBSTATION']==substation,conductor_yearly_df.columns.str.contains(str(year))].reset_index(drop=True).values[0][0] </code></pre>
python|python-3.x|pandas
1
359,339
62,109,957
Why does the BERT NSP head linear layer have two outputs?
<p>Here's the code in question. </p> <p><a href="https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_bert.py#L491" rel="nofollow noreferrer">https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_bert.py#L491</a></p> <pre><code>class BertOnlyNSPHead(nn.Module):...
<p>The two scores are meant to represent unnormalized probabilities (<code>logits</code>) from the model. If we softmax them, we get our predictions, where index 0 indicates next sentence, and index 1 indicates random.</p> <p>This is just a stylistic choice on the HuggingFace author's behalf, probably to keep the loss...
nlp|pytorch|transformer-model|huggingface-transformers|bert-language-model
3
359,340
62,076,514
Try/Except for ...AttributeError: Can only use .str accessor with string values
<p>I am running a function that grabs some data from a website and writes it into a pandas database. I am using selenium and geckodriver.</p> <pre><code>...code... first_names = driver.find_elements_by_class_name('first-name') first_names = [name.text for name in first_names] last_names = driver.find_elements_by_cla...
<p>Does the below code where I add <code>.astype('str')</code> to the middle for each column solve? You probably have column with mixed data type of strings and objects.</p> <pre><code>athlete['commit_school'] = athlete['commit'].astype('str').str.replace('\d+', '').str.replace('/', '').str.replace('VERBAL', '').str.r...
python|pandas|selenium|web-scraping
1
359,341
62,364,160
How to stack year-as-row, month-as-column data into a series
<p>There are lots of unstack examples, and not many on stack. I am trying to process a dataset in this format</p> <pre><code> 1 2 3 4 5 6 7 8 9 10 11 12 1870 -1.00 -1.20 -0.83 -0.81 -1.27 -1.08 -1.04 -0.88 -0.53 -0.92 -0.79 -0.79 1871 -0.25 -0.58 -0.43 -0.50 -0.70 -0.53...
<p>You can use <code>melt</code> for this, first make sure to <code>reset_index()</code> on your dataframe to make Year a column, and then do this:</p> <pre><code>df1 = pd.melt(df, id_vars=['Year'], var_name=['Month']) df1['Date'] = pd.to_datetime(df1['Year'].astype(str) + '-' + df1['Month'].astype(str)) df1 = df1.sor...
python|pandas
1
359,342
62,375,303
How do I multiply each element in a list with nested lists and get the sum?
<p>I have a project that goes like this:</p> <pre><code>data = [[0, 1], [1, 1], [1, 0], [0, 1]] res = [4, 2] </code></pre> <p>The objective is to multiply <code>res</code> with each element in <code>data</code> and get the sum. For example:</p> <pre><code>sum_prod = [[4*(0) + 2*(1)], [4*(1) + 2*(1)], [4*(1) + 2*(0)]...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.multiply.html" rel="nofollow noreferrer"><code>np.multiply</code></a>, which accepts an <a href="https://numpy.org/doc/stable/user/basics.creation.html" rel="nofollow noreferrer">array_like</a> as input (and hence lists too) followed by <cod...
python|arrays|list|numpy
3
359,343
62,054,502
NLTK FreqDist to a table using pandas
<p>I have this frequency distribution that i got using NLTK:</p> <pre><code>[(('ingeniería', 'informática'), 30), (('tecnologías', 'información'), 26), (('sistemas', 'información'), 19), (('big', 'data'), 16), (('ingeniería', 'software'), 14), (('ingeniero', 'técnico'), 11), (('bases', 'datos'), 10), (('información', ...
<pre><code>fdist = nltk.FreqDist( ... ) df_fdist = pd.DataFrame.from_dict(fdist, orient='index') df_fdist.columns = ['Frequency'] df_fdist.index.name = 'Term' print(df_fdist) df_fdist.to_csv(...) </code></pre> <p>Or:</p> <pre><code>def cond_freq_dist(data): """ Takes a list of tuples and returns a conditional...
python|pandas|nltk
1
359,344
62,416,754
how to not plot the graph and make a Cut diagram
<p>I have computed a thing and the result has some "NaN" values which if I want to replace them with zero by <code>np.nan_to_num</code> the graph becomes wrong. How can I plot not the whole of list? I mean how can I plot the value within the list and not plot "NaN" like the image that I have attached in this post. The ...
<p>Your <code>x</code> and <code>y</code> are lists. You have to convert them to numpy arrays before you can do efficient filtering:</p> <pre><code>x = np.array(x) y = np.array(y) good_mask = np.isfinite(y) plt.plot(x[good_mask], y[good_mask]) </code></pre>
python|numpy|matplotlib
2
359,345
62,073,691
My Python set-up is too complicated, and I don't understand it. Currently my Python is unusable. Advice would be welcome
<p>Here is a sequence of my commands, and my system's response. This shows that I do not know how to access numpy with my current (very confusing) Python setup. It was recently working, but then I changed something, but can't remember what.</p> <p>I run MacOs 10.14.6 on a Macbook Pro.</p> <pre class="lang-none pretty...
<p>Actually, you kind of screwed your pip setup. Start with the beginning : </p> <pre><code>$ python -m pip list </code></pre> <p>What is returned by this command ? </p> <p>I would suggest you start using virtual environment (venv). It is much easier to handle module dependency issues in the future. </p> <pre><code...
python-3.x|numpy|pip
3
359,346
62,295,325
Converting strings to datetime in dataframe of one row
<p>I have a CSV file that serves as an input to my calculations. The file contains a table that is read as a dataframe in my script. Two columns are datetime objects. When I am reading the file to a dataframe I am converting those values from default string type to datatime applying to_datetime function with UTC argume...
<p>I've found that with older versions of pandas this can happen with when date fields are present in the data frame (specifically datetime64 variants). So, instead of <code>iloc</code> try this...</p> <pre><code>df_in[['Start Time','End Time']] = df_in[['Start Time','End Time']].apply(pd.to_datetime, utc = True) </co...
python|pandas|dataframe
0
359,347
62,066,367
How to get date from year and semeter format ('YYYY-SX') using pandas
<p>I have a pandas column called time and it contains the year and semester. For instance in format ('YYYYSX') 2018S1. I want to convert the time format in YYYYSX into date</p> <p>Input </p> <pre><code> time 1 2019S2 2 2019S2 3 2020S1 </code></pre> <p>output </p> <pre><code> time 1 2019-09-30 2 2019-10-3...
<pre><code>def convert(time): year = time[:4] semester = time[4:] conversions = {'S1': '-01-31' , 'S2': '-06-03', 'S3': '-09-30'} return pd.to_datetime(year + conversions[semester]) df['time'] = df.time.apply(convert) </code></pre> <p>returns :</p> <pre><code> time 0 2019-06-03 1 2019-06-03 2 ...
python|pandas|dataframe|datetime|period
1
359,348
62,352,416
Group by + New column + oldest date when type repated
<p>I have this dataset:</p> <pre><code>df=pd.DataFrame({'user':[1,1,2,2,2,3,3,3,3,3,4,4], 'date':['1995-09-01','1995-09-02','1995-10-03','1995-10-04','1995-10-05','1995-11-07','1995-11-08','1995-11-09','1995-11-10','1995-11-15','1995-12-18','1995-12-20'], 'type':['a','b','a','x','b'...
<p>You can try with <code>merge</code> </p> <pre><code>df=df.merge(df.loc[df.type.eq('a'), ['user','date']], on = 'user', how = 'left') </code></pre>
python|pandas|date|group-by|conditional-statements
2
359,349
62,055,018
Set ALL pixels to black if values at position is 0
<p>I have images with the same shape defined as:</p> <pre><code> img = cv2.imread(file, 0) # values are 0 - 255 mask = cv2.imread(file2, 0) # values are only 0's and 255's </code></pre> <p>From the given images, I want to check if at mask[x,y] = 0, then set the img[x,y] = 0.</p> <p>I can do this by doing a loop. ...
<p>You just need to create a mask (not the same as your existing variable) and apply it to the <code>img</code> array to specifically target indexes where you want to put a 0. Then it's as simple as:</p> <pre><code>mask2 = (mask == 0) img[mask2] = 0 </code></pre> <p>Alternatively, </p> <pre><code>img[mask.astype(boo...
python|numpy
1
359,350
62,197,905
Error importing csv file data into pandas dataframe
<p>I've hit a brick wall trying to cleanse an imported CSV and I was hoping someone could help please?</p> <p>I've got this importing a 30000 row x68 column csv file:</p> <pre><code>df = pd.read_csv("training_dataCSV",low_memory=False) </code></pre> <p>Here's what the data looks like:</p> <pre><code>ID PP1.1 PP2...
<p>You may specify the desired data types to the read_csv function using a dict which maps each column name contained in your ".csv" file to the desired type. For instance, if you'd like the ID to be an integer, try this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.read_csv("trainin...
python-3.x|pandas
0
359,351
62,108,661
How do I find the source code for a method in Pandas?
<p>The following is the GitHub link for Python's Pandas package.</p> <p><a href="https://github.com/pandas-dev/pandas" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas</a></p> <p>I would like to find the source code for a specific method (for instance, iterrows). What would be the file path for this?</p...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html" rel="nofollow noreferrer">This site</a> and <a href="https://pandas.pydata.org/pandas-docs/version/0.25.0/reference/api/pandas.DataFrame.iterrows.html" rel="nofollow noreferrer">this one</a> have a button with a link ...
python|pandas
3
359,352
62,255,856
How to perform Multi output regression using RoBERTa?
<p>I have a problem statement where I want to predict multiple continuous outputs using a text input. I tried using 'robertaforsequenceclassification' from HuggingFace library. But the documentation states that when the number of outputs in the final layer is more than 1, a cross entropy loss is used automatically as m...
<p><code>BertForSequenceClassification</code> is a small wrapper that wraps the <code>BERTModel</code>.</p> <p>It calls the models, takes the pooled output (the second member of the output tuple), and applies a classifier over it. The code is here <a href="https://github.com/huggingface/transformers/blob/master/src/tr...
pytorch|regression|huggingface-transformers|bert-language-model
2
359,353
62,144,788
Sort a Pandas DataFrame using both Date and Time
<p>I'm Trying to sort my dataframe using "sort_value" Im not getting the desired output</p> <pre><code>df1 = pd.read_csv('raw data/120_FT DDMG.csv') df2 = pd.read_csv('raw data/120_FT MG.csv') df3 = pd.read_csv('raw data/120_FT DD.csv') dconcat = pd.concat([df1,df2,df3]) dconcat['date'] = pd.to_datetime(dconcat['Act...
<p><code>sort_values</code> returns a data frame which is sorted if <code>inplace=False</code>.<br> so <code>dconcat=dconcat.sort_values(by='date')</code></p> <p>or you can do <code>dconcat.sort_values(by='date', inplace=True)</code></p> <p>you can try this;</p> <pre><code>dconcat = pd.concat([df1,df2,df3]) dconcat...
python|pandas|dataframe|sorting
1
359,354
62,103,241
Transform Numpy Arrays to specific 2 dimensional Form
<p>Currently I work with numpy and have to transform large data sets. Starting point are some one-dimensional arrays. These should be combined to a large 2 dimensional array. I attach a small example how it should look like.</p> <pre class="lang-py prettyprint-override"><code># Returns 16 arrays with four numbers in e...
<p>You can use np.pad, with mode='wrap':</p> <pre><code>final_width = 8 final_height = 8 a = np.arange(4).reshape(2,2) np.pad(a, ((0, final_height-a.shape[0]),(0, final_width-a.shape[1])), mode='wrap') a out: array([[0, 1, 0, 1, 0, 1, 0, 1], [2, 3, 2, 3, 2, 3, 2, 3], [0, 1, 0, 1, 0, 1, 0, 1], [2...
python|arrays|numpy|numpy-ndarray
1
359,355
62,168,750
HOW to use a column Dataframe Python to find a value in another column of the same Dataframe
<pre><code>Borrower=[1,1,1,2,2] Property_type=[Residential, Other, Other, Land, Hotel] OMV = [100, 50, 30, 102,45] </code></pre> <p>I have calculated the max OMV per Borrower&amp;Property_Type</p> <pre><code>OMV_max= [100,100,100,102,102] </code></pre> <p>Now I would obtain</p> <pre><code>Property_Type_Borrower = [...
<p>I think you should use a dictionary <code>OMV_to_Property = OMV_to_Property = {100: 'Residential', 50: 'Other', 30: 'Other', 102: 'Land', 45: 'Hotel'}</code>. Then you can just use a list comprehension like <code>Property_Type_Borrower = [OMV_to_Property[x] for x in OMV_max]</code>.</p>
python|pandas|dataframe
0
359,356
62,228,230
Pandas to_datetime show format dont match
<p>i think i have entered the format correctly.Shows value error</p> <p><a href="https://i.stack.imgur.com/2tkQa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2tkQa.png" alt="enter image description here"></a></p>
<p>please check the following code:</p> <pre><code>df['Order Date'] = pd.to_datetime(df['Order Date'], format='%Y%m%d').dt.strftime('%Y-%m-%d') </code></pre> <p>And if you want to format it to other date and time formats change the stftime() and please go look through the link for the other formats <a href="https://...
python|pandas|python-datetime
0
359,357
62,270,742
product of large numbers
<p>I have two sets of numbers:</p> <ol> <li>one is a "list" (tuple works too) of powers of 2 (1, 2, 4, etc), which I'll call Mult_array. I can successfully define this to have a length of 1485, for example, and I can examine the values, so that code is working. I have tried to work with them in various format. I can s...
<p>I suspect that your BigCourseDF row (the one with the ones and zeros) is of data type np.float64. If you do a matrix multiply with a python int (unlimited digits) array, the ints will be converted into 64-bit float, which will give a problem around 2**1024:</p> <pre><code>import numpy as np bignums = [1&lt;&lt;10, ...
python|pandas|largenumber
1
359,358
62,128,721
Pandas .equals method returns different results between windows and linux
<p>I am trying to deploy the same code on <strong>windows10</strong> using <strong>conda</strong>, and the unit tests that work on <strong>linux</strong> does not function on <strong>windows</strong>.</p> <p><strong>On Ubuntu:</strong></p> <p><strong>df_1</strong></p> <pre class="lang-py prettyprint-override"><code>...
<p>I can replace the <strong>.equals</strong> method by a <strong>to_dict==</strong></p> <p>Before:</p> <pre class="lang-py prettyprint-override"><code>df_1.equals(df_2) False </code></pre> <p>After:</p> <pre class="lang-py prettyprint-override"><code>df_1.to_dict() == df_2.to_dict() True </code></pre> <p>Thank yo...
python|python-3.x|pandas|windows
0
359,359
62,061,703
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation?
<p>I am using <code>pytorch-1.5</code> to do some <code>gan</code> test. My code is very simple gan code which just fit the sin(x) function:</p> <pre><code>import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt # Hyper Parameters BATCH_SIZE = 64 LR_G = 0.0001 LR_D = 0.0001 N_IDEAS = 5...
<p>This happens because the opt_D.step() modifies the parameters of your discriminator inplace. But these parameters are required to compute the gradient for the generator. You can fix this by changing your code to:</p> <pre><code>for step in range(10000): artist_paintings = artist_works() # real painting from ar...
python|deep-learning|computer-vision|pytorch|generative-adversarial-network
10
359,360
62,140,759
How to eliminate elements with certain characters or phrases from a list in python?
<p>I have a list of plant names from an excel spreadsheet that I have extracted with pandas. After removing duplicates and making the entire list lower-case, I wanted to remove characters like parenthesis, apostrophes, dashes, and phrases like "A" and "The" to further eliminate any possible duplicates so that in a list...
<p>This should do it:</p> <pre><code>import re new = [] test_list = ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin") for s in test_list: for n in s.split(): if n == re.sub(r'[^\w\s]','',n) and n.lower() != 'a' and n.lower() != 'the': # Adds w...
python|python-3.x|pandas|string|list
1
359,361
62,361,150
Extract specific value in pandas dataframe based on column condition
<p>I am faced with a small problem, the solution of which is certainly very simple, but I cannot find how to do it. Let's say I have the following pandas dataframe <code>df</code>:</p> <pre><code>import pandas as pd X = [0.78, 0.82, 1.03, 1.06, 1.21] Y = [0.0, 0.2521, 0.4905, 0.5003, 1.0] df = pd.DataFrame({'X':X, 'Y'...
<p>We can check with <code>idxmax</code>, notice it will need have one value less than 0.5 </p> <pre><code>df.loc[df.Y.gt(0.5).idxmax(),'Z']=1 df.Z.fillna(0,inplace=True) df X Y Z 0 0.78 0.0000 0.0 1 0.82 0.2521 0.0 2 1.03 0.4905 0.0 3 1.06 0.5003 1.0 4 1.21 1.0000 0.0 </code></pre> <p>I...
python-3.x|pandas
0
359,362
62,315,562
Create a dataframe for stock analysis using a datetimeindex timeseries data source
<p>I have a datasource which gives me the following dataframe, <code>pricehistory</code>:</p> <pre><code>+---------------------+------------+------------+------------+------------+----------+------+ | time | close | high | low | open | volume | red | +---------------------+----...
<p>Given you didn't provide data I create some dummy one. By SO policy you should make different question per problem. For now I'm answering the first one.</p> <h1>Generate data</h1> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np times = pd.date_range(start="2020-06-01", end="...
python|pandas|finance|stock
0
359,363
62,295,463
CUDA Runtime Error: Which Cuda version is compatible to run NER task using BERT-NER
<p>I have setup all the requirement packages installed on my VM and i found no nvidia GPU driver installed, In the requirements doesn't have nvidia GPU driver installation instructions, I want to know which cuda version and it compatible nvidia driver which needs too resolve the below error.</p> <p>Github link: <a hr...
<p>I had the same issue for some time ago. The following commands fixed for me!</p> <p>It is a problem if you have multiple installation and likely you have now since you tried many things. Remove basically everything</p> <pre><code>sudo apt-get purge nvidia-* sudo apt-get remove nvidia-cuda-toolkit sudo apt autoremove...
pytorch|named-entity-recognition|huggingface-transformers|bert-language-model
0
359,364
51,345,144
Docker toolbox (HomeBrew / Tensorflow)
<p><em>Installing TansorFlow on MacBook. As a part of the installation, I have to install "Docker-Toolbox" for a "Docker"...</em></p> <p><a href="https://i.stack.imgur.com/6IQJ6.jpg" rel="nofollow noreferrer">Comand line screenshot</a></p> <p><strong>Why do I get the error</strong> (<em>check the attached screenshot<...
<p>As mentioned in <a href="https://github.com/docker/toolbox/issues/153" rel="nofollow noreferrer">docker/toolbox issue 153</a>:</p> <blockquote> <h2>Common problems:</h2> <ul> <li>VirtualBox in an erroneous state. Restarting and/or re-installing VBox may fix this.</li> <li>Check your <code>~/.bashrc</code...
docker|tensorflow|homebrew|docker-toolbox
1
359,365
51,355,561
if a column has duplicates and next column has a value how to add these to duplicate values
<p>Their is a dataframes with the columns, below is input ,if the username has duplicates and the owner region should be added to the duplicates also</p> <pre><code>Queue Owner Region username xxy aan xyz india aan yyx aandiapp xox UK aa...
<p>I think need replace empty values to <code>NaN</code>s first and then per groups repalce them by forward and back filling:</p> <pre><code>df['Owner Region'] = df['Owner Region'].replace('', np.nan) df['Owner Region'] = df.groupby('username')['Owner Region'].transform(lambda x: x.ffill().bfill()) </code></pre>
python-3.x|pandas
1
359,366
51,542,897
Getting predicted value Y to a certain number of X values in tensorflow.js
<p>I'm a beginner with machine learning and since i love to work with javascript, i recently started working with tensorflow.js Library. And i worked with both <em>Fitting the curve to the synthetic data</em> which is a <strong>regression</strong> problem and <em>MNIST digit recognition</em> with Convolutional layers w...
<p>Your input array are of dimension 1 and of size 6. One can define the following model using a stochastic gradient descent optimizer. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-overri...
machine-learning|tensorflow.js
0
359,367
51,207,964
Pandas rowwise data to table form
<p>I have information from a csv file that is presented rowwise:</p> <pre><code>Color Shape Value red triangle 10 red circle 11 blue triangle 12 blue circle 13 </code></pre> <p>I need to convert this to a new dataFrame in a matrix form, where the columns are colors and the...
<p>You can use <code>pivot_table()</code>:</p> <p>For the data: import pandas as pd</p> <pre><code>df = pd.DataFrame({'Color': ['red', 'red', 'blue', 'blue'], 'Shape': ['triangle', 'circle', 'triangle', 'circle'], 'Value': [10, 11, 12, 13]}) df.pivot_table(index = 'Color', colu...
python|pandas|dataframe
3
359,368
51,513,259
merge information from duplicate records in python
<p>Giving this Data sample, I would like to deduplicate rows by mergin info by one column and not by deleting rows. In this case would be the field CODE.</p> <pre><code>df = pd.DataFrame({'CODE':['000', '111','111','222','222', '333'],'NAME':['help','foo','bar', 'bla','booo','nyaa'] ,'ALT_NAME':['zzz','foo 1','bar', ...
<p>I think this works for you, <code>agg</code> is alias of <code>aggregate</code> which is applied to each column of the group:</p> <pre><code> df.groupby(['CODE']).agg(lambda x:list(x)) </code></pre> <p>BTW, does anyone know why it failed when I run <code>df.groupby(['CODE']).agg(list)</code>?</p>
python|pandas|duplicates
2
359,369
51,552,859
Extract indexes of Columns where dtype is 'object' in Pandas
<p>From all the columns in a Pandas Dataframe, how to extract indexes of all the columns of specific <code>dtype</code>?</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="noreferrer"><code>select_dtypes</code></a> and if positions necessary <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_indexer.html" rel="noreferrer"><code>get_indexer</code></a...
python|pandas|numpy
8
359,370
51,329,666
Python Panda DF - how to check if specific character exist in whole DF and globally replace it
<p>I want to check if there is character '|' in a whole Panda DF.</p> <p>After that step - want to globrally replace all '|' with some other character.</p> <p>I know to check if specific cell contains character:</p> <pre><code>df['a'].str.contains('|') </code></pre> <p>But how to check that globally and also replac...
<p>You can using </p> <pre><code>df = df.apply(lambda x : x.str.replace('-','something')) </code></pre> <p>Or </p> <pre><code>df = df.replace({'-':'something'},regex=True) </code></pre>
python|pandas|csv|dataframe
1
359,371
51,334,836
Converting DataFrame columns that contain tuples into rows
<p>I have a DataFrame similar to the following:</p> <pre><code> A B C D E F 0 1 (10, 11) (a, b) abc () () 1 2 (10, 11) (a, b) def (2, 19) (j, k) 2 3 () () abc (73,) (u,) </code></pre> <p>where some columns contain tuples. How could I...
<p>using <a href="https://docs.python.org/3/library/itertools.html#itertools.zip_longest" rel="nofollow noreferrer">zip_longest from itertools</a>. All single-values are wrapped in lists so that they can be zipped with the other lists (or tuples)</p> <pre><code>expanded = df.apply( lambda x: pd.DataFrame.from_reco...
python|pandas|dataframe
3
359,372
51,479,503
How to sum the values of a list's elements which elements' values come from anthor dataframe in pandas?
<p>I have two pandas DataFrame, which called <code>df1</code> and <code>df2</code>. I want to sum the list values in <code>df2</code> which the list's values come from <code>df1</code>.</p> <p>For example:</p> <p>df1:</p> <pre><code>df1 = pd.DataFrame([['a',11],['b',13],['c',45],['d',88]],columns=['name1','data1']) ...
<p>First create dictionary by <code>df1</code> and then list comprehension with <code>get</code> for map value of <code>dict</code>, if values not matched is added <code>0</code> to <code>sum</code>:</p> <pre><code>d = df1.set_index('name1')['data1'].to_dict() df2['data2'] = [sum(d.get(y, 0) for y in x) for x in df2['...
python|pandas
3
359,373
51,231,419
Perform calculations on a list present in a column of a dataframe pandas
<p>I have the below dataframe:</p> <pre><code> Position A B 0 29644164 71.0 [31, 38, 1, 1] 1 45861974 45.0 [17, 26, 1, 1] 2 58142396 69.0 [37, 31, 0, 1] 3 41223046 75.0 [21, 53, 0, 1] </code></pre> <p>I'd like to do calculations on column B....
<p>Use list comprehension:</p> <pre><code>df['calc'] = [sum(x[-2:]) / sum(x) for x in df.B] print (df) Position A B calc 0 29644164 71.0 [31, 38, 1, 1] 0.028169 1 45861974 45.0 [17, 26, 1, 1] 0.044444 2 58142396 69.0 [37, 31, 0, 1] 0.014493 3 41223046 75.0 [21, 53, 0, 1] 0.013...
python|python-3.x|pandas
2
359,374
51,271,087
How to improve the subplots part with a for loop?
<pre><code># dataframe with 8 columns using pandas dictionary method: df = DataFrame({'x1':[10.,8,13,9,11,14,6,4,12,7,5], 'y1':[8.04,6.95,7.58,8.81,8.33,9.96,7.24,4.26,10.84,4.82,5.68], 'x2':[10.,8,13,9,11,14,6,4,12,7,5], 'y2':[9.14,8.14,8.74,8.77,9.26,8.1,6.13,3.1,9.13,7.26,4.74], ...
<p>You could use pd.wide_to_long to reshape your dataframe and use subplot parameter in pandas plot.</p> <pre><code>df1 = df.reset_index() df_out = pd.wide_to_long(df1,['x','y'],'index','values',sep='',suffix='.')\ .set_index(['x'],append=True)\ .unstack(1)\ .reset_index('index',drop=True) df_out.plot(subplots=...
python|pandas|matplotlib
2
359,375
51,515,253
Optimizing a function involving tf.keras's "model.predict()" using TensorFlow optimizers?
<p>I used tf.keras to build a fully-connected ANN, "my_model". Then, I'm trying to minimize a function <code>f(x) = my_model.predict(x) - 0.5 + g(x)</code> using Adam optimizer from TensorFlow. I tried the below code:</p> <pre><code>x = tf.get_variable('x', initializer = np.array([1.5, 2.6])) f = my_model.predict(x) -...
<p>I found the answer! </p> <p>Basically, I was trying to optimize a function involving a trained ANN w.r.t the input variables to the ANN. So, all I wanted was to know how to call <code>my_model</code> and put it in <code>f(x)</code>. Digging a bit into the Keras documentation here: <a href="https://keras.io/getting-...
python|tensorflow|optimization
2
359,376
51,354,086
How to connect the output tensor of a restored graph to the input of the default graph in tensorflow?
<p>I am new to tensorflow, and I have been stuck at this for several days. Now I have the following pretrained model (4 files):</p> <pre><code>Classification.inception.model-27.data-0000-pf=00001 Classification.inception.model-27.index Classification.inception.model-27.meta checkpoint </code></pre> <p>And I can succ...
<p>Your issue is that <a href="http://devdocs.io/tensorflow~python/tf/graph" rel="nofollow noreferrer"><code>with tf.Graph().as_default():</code></a> overrides your old graph:</p> <blockquote> <p>Another typical usage involves the tf.Graph.as_default context manager, which overrides the current default graph for the...
python|tensorflow|machine-learning|training-data|pre-trained-model
1
359,377
51,359,716
how to nested value_counts in pandas
<p>hello friends i'm very confused with nested value_counts in pandas</p> <p>i have example dataframes:</p> <pre><code>SenderID Status long john 1 2 john 0 1 eddie 1 1 eddie 1 2 eddie 1 2...
<p>I think need <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.GroupBy.size.html" rel="nofollow noreferrer"><code>size</code></a> for ...
python|pandas|dataframe
1
359,378
51,278,514
turning categorical variables into quantitative variables in python
<p>I am trying to change a categorical variable into quantitative variables. I am using the <code>get_dummies</code> function which should return the quantitative variable.</p> <p>My idea is to make new columns in my dataframe and add the returned quantitative variables to those new columns, but when I print it out, t...
<p>I think need assign to subset of new columns names:</p> <pre><code>df[['0_to_35', '35_to_55', 'greater then 55']] = pd.get_dummies(df['age_band']) </code></pre> <p>Or assign to new DataFrame and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow noreferrer"><co...
python|pandas
1
359,379
51,372,741
Pandas add n number of new date rows to DataFrame
<p>I want to add a number of months to the end of my dataframe.</p> <p>What is the best way to append another six (or 12) months to such a dataframe using dates?</p> <pre><code>0 2013-07-31 1 2013-08-31 2 2013-09-30 3 2013-10-31 4 2013-11-30 </code></pre> <p>Thanks</p>
<p>Edit: I think you might want <code>pd.date_range</code></p> <pre><code>df = pd.DataFrame({'date':['2010-01-31', '2010-02-28'], 'x':[1,2]}) df['date'] = pd.to_datetime(df.date) date x 0 2010-01-31 1 1 2010-02-28 2 </code></pre> <p>Then</p> <pre><code>df.append(pd.DataFrame({'date': pd.date_range(s...
python|pandas
4
359,380
51,422,606
Adding lines to scatter plot from multiple columns of two Pandas DataFrames
<p>I am creating a scatter plot from multiple columns of two pandas DataFrames, and would like to join the markers with lines. Below is some example code.</p> <p>Creating two DataFrames:</p> <pre><code>inYs= pd.DataFrame(np.random.uniform(low=0.3, high=0.450, size=(100))) inYs[1]= np.random.uniform(low=0.1, high=0.2,...
<p>The problem is, that your (x, y)-pairs you plot are single points. Connections between markers are plotted if you plot lists of y against lists of x values. Which markers should be connected to which others? These should be packed into the mentioned lists.</p> <p>Just to give an example, how y-list against x-list l...
python|pandas|scatter-plot
0
359,381
51,543,875
Error: tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[3,7] = -1 is not in [0, 20000)
<p>I am training a lstm on a ecommerce data. During training I am getting following error:</p> <blockquote> <p>tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[3,7] = -1 is not in [0, 20000) [[Node: embedding_1/GatherV2 = GatherV2[Taxis=DT_INT32, Tindices=DT_INT32, Tparams=DT_FLOAT, _cla...
<p>I made following changes in the code and it worked:</p> <p>I used python.cat.codes for this</p> <pre><code>for i in range(len(columns)): df[columns[i]] = df[columns[i]].astype('category') df[columns[i]+"_cat"] = df[columns[i]].cat.codes </code></pre> <p>the astype converts the data columns to category typ...
python|tensorflow|keras|lstm
0
359,382
51,552,199
tf.Variable with dynamic shape from input placeholder
<p>I am trying to build a network, where my requirement is hidden unit shape should be according to input shape, so that user can give any length of input. What I am trying to do is :</p> <pre><code>import tensorflow as tf n_hidden_1=100 input_ = tf.placeholder(name='input_data',shape=[None,None],dtype=tf.float32) va...
<p>A <code>tf.Variable</code> cannot really have a dynamic shape, because it does not make sense for their purpose. In tensorflow, a variable is meant to be a model parameter that is optimized, typically by SGD. During optimization you typically assume that your cost function and the space it is defined on does not var...
python|python-3.x|tensorflow
3
359,383
51,267,029
Why we are using shape=((None,)+image_shape) below what does that mean?
<p>what does <code>shape=((None,)+image_shape)</code> mean below?</p> <pre><code>tf.placeholder(tf.float32,shape=((None,)+image_shape),name="x") </code></pre>
<p>The <code>(None, ) + image_shape</code> is tuple addition. <code>(None, )</code> is a tuple of one element, and the addition will produce something like <code>(None, 1920, 1080)</code></p> <p>The <code>None</code> in numpy arrays is a special value, which means that you want to add a new dimension. So, the original...
python|tensorflow|neural-network
2
359,384
51,450,366
Python pandas read_csv issue with bad data when dtype is specified
<p>I am reading a .csv file from amazon s3 bucket by using pandas 'read_csv'. Below is the statement which I issued:</p> <pre><code>xyz = pd.read_csv(io.BytesIO(obj['Body'].read()), dtype={'col1': str ,'col2':int,'col3':int ,'col4':int} ,encoding='latin-1') </code></pre> <p>Now herein lies my problem; col2 contains ...
<p>Firstly, you should be aware that pandas allows you to read directly from S3 with something like</p> <pre><code>xyz = pd.read_csv('s3://bucket/file.csv, dtype={..}, encoding='latin-1') </code></pre> <p>however, this does not solve your bad-data problem. Using the python parser engine of regex delimiters <em>might<...
python|pandas|amazon-s3
0
359,385
51,546,075
Two parallel conv2d layers (keras)
<p>I want two build a neural network that takes two separate matrices with same dimensions (for example grey-scale images) as input, and outputs a value between -1 and 1 (probably tanh).</p> <p>I would like to build the network so that there are two seperate convolutional layers as inputs. Each one takes one matrix(or...
<p>You can do that in Keras and is makes sense, if the inputs are different. To do so in keras first you need a multiple input model and you have to concatenate the outputs of the convolutional layer together.</p> <pre><code>input_1= Input(shape=(x,y), name='input_1') input_2= Input(shape=(x,y), name='input_1') c1 = C...
tensorflow|keras|conv-neural-network
4
359,386
51,471,781
import pandas error in Spyder
<p>I got this error message in Spyder,</p> <pre><code>import pandas as pd </code></pre> <blockquote> <p>Traceback (most recent call last):</p> <p>File "", line 1, in import pandas as pd</p> <p>File "C:\ProgramData\Anaconda3\lib\site-packages\pandas__init__.py", line 42, in from pandas.co...
<p>Check in your Anaconda Prompt if you've installed pandas within an Anaconda environment. In that case, you need to launch the spyder after activating that particular environment. Let's say, the pandas is installed within an environment named 'myenv', then type the following two commands in your Anaconda prompt:</p> ...
python|pandas
0
359,387
51,424,336
Python - to_dict() creates unwanted nested dictionary
<p>Edit: the duplicate suggested was not able to resolve my issue as the indexed column is different from turning a normal df into a dict. Would appreciate it if the downvoter takes away the vote.</p> <p>Very simple, I want to create a dictionary from a df, with the df indexes as keys, and a column called 'signal' as ...
<p>This is the intended behavior of <code>to_dict</code> (check <a href="https://stackoverflow.com/questions/26716616/convert-a-pandas-dataframe-to-a-dictionary">this very good answer</a> with inputs/outputs of the different possible args, followed with explanations on them).</p> <p>In your case, just get all <code>si...
python|pandas|dictionary
2
359,388
51,151,889
change the specific cell value having common index in pandas
<p>I am trying to change the value of particular cell of pandas Dataframe. using <code>loc</code> i am finding all the column having the given index and then trying to change the given row and column value, but it is not reflecting in the original dataframe.</p> <pre><code>df.loc[df.index == 'Lactose intolerance ', '...
<p>Try with: </p> <pre><code>df.iloc[row_index, col_index] = "no" </code></pre> <p>or</p> <pre><code>df.loc[row_index, 'Lactose intolerance] = "no" </code></pre>
python|pandas
1
359,389
51,306,333
How the error of tensorflow will be fix?
<p>I am trying the code of CNN fault detection but it is getting error. I tried pip install tensorflow but that is also not working.<br> No module named as tf,<br> How this error will be removed?</p> <p><img src="https://i.stack.imgur.com/CR8UK.png" alt="Screenshot"></p>
<p>U are using Anaconda enviroment, u must install tensorflow by following this steps:</p> <ul> <li><code>C:&gt; conda create -n tensorflow pip python=3.5</code> </li> <li><code>C:&gt; activate tensorflow</code></li> <li><code>(tensorflow)C:&gt; pip install --ignore-installed --upgrade tensorflow</code> </li> </ul> <...
python|tensorflow
0
359,390
51,175,012
Pandas not one hot encoding data
<p>This code :</p> <pre><code>df = pd.DataFrame({ 'id_val' : [1.0 , 2.0, 3.0] , 'c1': [1.0 , 2.0, 3.0], 'c2': [1.0 , 2.0, 3.0], 'c3': [1.0 , 2.0, 3.0] }) df </code></pre> <p>generates the dataframe :</p> <p><a href="https://i.stack.imgur.com/XJxdV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XJxdV...
<p>Convert values to <code>string</code>s:</p> <pre><code>print (pd.get_dummies(df.astype(str))) id_val_1.0 id_val_2.0 id_val_3.0 c1_1.0 c1_2.0 c1_3.0 c2_1.0 c2_2.0 \ 0 1 0 0 1 0 0 1 0 1 0 1 0 0 1 ...
python|pandas
1
359,391
51,292,900
How do I merge two dataframes that don't share one common index?
<p>Here is the first DataFrame:</p> <pre><code>In: df.head() Out: avg_lmp avg_load read_year read_month trading_block 2017 3 0 24.606666 0.018033 1 32.090800 0.023771 4 0 ...
<p>You seem to have common indexes. Set them, then join:</p> <pre><code>df = df.reset_index().set_index(['read_month', 'trading_block']).join(df2) </code></pre> <p>and if you wish:</p> <pre><code>df.reset_index().set_index(['read year', 'read_month', 'trading_block']) </code></pre> <p>Not sure if that is what you'r...
python|python-2.7|pandas
1
359,392
51,174,114
How to extract segments of dataframe contains at least two records
<p>Given a dataframe df </p> <pre><code>Trip_id Latitude Longitude Acceleration date_time Transportation_Mode 1 39.98528333 116.3073667 186.6302183 5/26/2007 10:21 Walk 1 39.98521667 116.30955 20.69027793 5/26/2007 10:22 Walk 1 39.98513333 116.3097667 12.41329907...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.agg</code></a> by custom functions, only necessary at least 2 values per groups for get top2 of <code>acceleration</code>:</p> <pre><code>#conve...
python-3.x|pandas
1
359,393
51,537,834
Pandas - check to see if all elements in a list are in a column
<p>I have a data frame with 3 columns - 'sport' 'age' 'name'</p> <p>I have a list with different sports in, declared like this:</p> <pre><code>sports = ['tennis','cricket','swimming'] </code></pre> <p>I want to check to see if all 3 of the sports are in the sport column. Currently, i have this:</p> <pre><code>if (d...
<p>Try using <code>isin(sports).all()</code></p> <p><strong>Ex:</strong></p> <pre><code>import pandas as pd sports = ['tennis','cricket','swimming'] df = pd.DataFrame({'sport': ['tennis','cricket','swimming']}) print(df["sport"].isin(sports).all()) </code></pre>
python|pandas
3
359,394
51,396,671
Convert TFLite to Lite
<p>I have a working app with TFlite using tensorflow for poets. It works with a labels.txt and graph.lite pair files. I have downloaded another model in .tflite file format and wanted to use in my application. I wanted to ask what are the differences between .lite and .tflite files and are there any ways to convert tfl...
<p>There is no difference in ".lite" and ".tflite" format (as long as they can be correctly consumed by Tensonflow Lite). And there is no need to convert them.</p>
python|tensorflow
3
359,395
51,483,044
Image Prediction fails on Chrome Mobile using tfjs but works on Chrome Desktop
<p>There is a simple classification <em>keras</em> model that i have converted to <em>tfjs</em> model, it works completely fine on Desktop Chrome predicts images as it should but on Chrome Mobile I receive the following error on calling the <strong>predict</strong> function:</p> <pre><code>Uncaught Error: Requested te...
<p>I ran into this same problem. Models would work fine on desktop but would crash when trying to use model.predict on mobile. For my issue, I was able to track this down to being due to the size of my convolutional kernels. I found that I am able to use convolutional kernels up to size (6,6) without running into probl...
tensorflow|keras|tensorflow.js|mobile-chrome
0
359,396
51,401,953
Transpose column value as unique column header more like matrix
<p>As newbie to python trying to understand how i can achieve below transformation:</p> <pre><code>Date Name Value 20180101 Dto 801 20180102 Dto 80 20180101 Rnc 501 20180102 Rnc 50 </code></pre> <p>to</p> <pre><code> Dto Rnc 20180101 801 501 20180102 501 50 </...
<p>Your input and desired output are inconsistent, I assuming that's a typo.</p> <p>Assuming you are using Pandas, you can use <a href="https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pd.pivot_table</code></a> to transform your data:</p> <pre><code...
python|python-3.x|pandas|dataframe
0
359,397
51,187,462
Join Dataframes by Time Period
<p>I'm trying to join two dataframes that have time stamped rows. Frame A is made up of events with a start time A1 and an end time A2. The events in Frame B each have just the one time.</p> <pre><code>import pandas as pd import datetime as dt # Data df_A = pd.DataFrame({'A1': [dt.datetime(2017,1,5,9,8), dt.datet...
<p>Thanks Scott, this answer works:</p> <pre><code># Define the time interval df_A["A1X"] = df_A["A1"] + dt.timedelta(days=-2) df_A["A2X"] = df_A["A2"] + dt.timedelta(days= 2) Bv = df_B .B.values A1 = df_A .A1X.values A2 = df_A .A2X.values i, j = np.where((Bv[:, None] &gt;= A1) &amp; (Bv[:, None] &lt;= A2)) df_C = ...
pandas|datetime|dataframe|join|typeerror
0
359,398
51,483,375
Python | Read from multiple csv files and add to a nested list
<p>I have csv files (present in the same directory) like these:</p> <p>File1:</p> <pre><code>Id,Param1,Param2 1,10,12 2,16,18 3,24,28 4,22,26 </code></pre> <p>File2:</p> <pre><code>Id,Param1,Param2 1,13,19 2,15,23 3,21,25 </code></pre> <p>I want to read the files and create nested lists like this:</p> <pre><code>...
<p>Modified the sample input a bit.</p> <pre><code>cat file1 1|10|12 2|16|18 3|24|28 4|22|26 cat file2 1|13|19 2|15|23 3|21|25 </code></pre> <p>Sample code</p> <pre><code>def process(filename): first_list = [] second_list = [] with open(filename, 'r') as fh: for line in fh: line = li...
python|list|pandas|csv|nested-lists
1
359,399
51,274,891
How to build some packet in tensorflow with debug mode\
<p>I encountered the problem that I wanted to have a debug, then I wanted to build a debug version of tensorflow, using the following command: bazel build --compilation_mode=dbg -s //tensorflow/tools/pip_package:build_pip_package</p> <p>but it will trigger the longtime link in protobuf for almost oneday, and still not...
<p>To understand the issue better, try running the neverending action manually:</p> <ol> <li>start the debug build, wait for it to get stuck in the protobuf linking action</li> <li>interrupt the build (Ctrl+C)</li> <li>run the build again with the <code>-s</code> flag, so Bazel shows the command line it executes (you ...
debugging|tensorflow|bazel
0