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
372,400
57,857,426
What is the correct way of reshaping a Data Frame in order to use it with .fit() function in ScikitLearn?
<p>The <code>coef_</code> &amp; <code>intercept_</code> function outputs arrays with unexpected values.</p> <p>My question is:</p> <p>Is there anything wrong with my Jupyter Notebook or I am coding things wrong? It will be a great help if someone please explain me the concept of reshaping because how hard I try I am ...
<p>First of all it's not recommended using <code>from pandas import DataFrame</code> You can try those two solutions:</p> <p>First Solution:</p> <pre><code>import pandas as pd from sklearn.linear_model import LinearRegression df = pd.read_csv("cost_revenue_clean.csv") X = df['production_budget_usd'] y = df['worldwid...
python|arrays|pandas|dataframe|scikit-learn
0
372,401
57,820,155
Pandas modify column in different way than loop
<p>I have a df:</p> <pre><code>DF name1 name2 finalName AB123 BB123 0 BB113 AB113 0 AB343 AB343 0 CC263 BB263 0 ED633 DD633 0 </code></pre> <p>I need to modify <code>finalName</code> in that way: <code>if name1 starts with AB and name2 starts with BB</code> - <code>finalName</code> should ...
<p>Here's one way using <a href="https://www.google.com/search?q=series+str+starts&amp;rlz=1C1GCEU_enIN822IN823&amp;oq=series+str+starts&amp;aqs=chrome..69i57j0l4.3452j1j7&amp;sourceid=chrome&amp;ie=UTF-8" rel="nofollow noreferrer"><code>series.str.startswith()</code></a>:</p> <pre><code>c1=df.name1.str.startswith('AB...
python|pandas|dataframe
1
372,402
57,753,237
Merging values of numpy array
<p>I have a multidementional numpy array representing four polygons by four x, y points (point1, point2, point3, point4):</p> <pre><code> [ [[248.37320795 107.04369371] [628.13542608 93.60279784] [631.17731304 179.54898405] [251.41509491 192.98987991]] [[594.74347239 199.82026651] ...
<p>Initial data:</p> <pre><code>p = np.array([ [[248.37320795, 107.04369371], [628.13542608, 93.60279784], [631.17731304, 179.54898405], [251.41509491, 192.98987991]], [[594.74347239, 199.82026651], [844.73138802, 197.36221057], [845.14434142, 239.36018039], [595.15642579, 241.81...
python|arrays|numpy|iteration
0
372,403
58,130,141
How to add some calculation in columns of the dataframe in python
<p><a href="https://i.stack.imgur.com/0BD9K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0BD9K.png" alt="Input excel sheet "></a></p> <p>I am having the excel sheet using the pandas.read_excel, I got the output in dataframe but I want to add the calculations in the after reading through pandas I ...
<p>I would first recommend to reshape your data into a long format, that way you can get rid of the empty cells naturally. Also most pandas functions work better that way, because then you can use things like group by operations on all x or y or wahtever dimenstion</p> <pre><code>from itertools import chain import pan...
python|pandas
0
372,404
57,965,148
How to create new column names and populate row values from lists in other columns
<p>I have a data set that contains a list of values in two columns. I need values from lists in column A to become new column names and values from lists in column B to become corresponding row values. </p> <p>My dataset looks like this:</p> <pre><code> A B -----------------------...
<p>If the pairs of lists are always the same length: <code>explode</code> (pandas 0.25+) + <code>pivot</code>. With different lengths, you can add a <code>cumcount</code> level after the explode (<code>groupby(level=0).cumcount()</code>) to the index so that they will align, though you'll need to make decisions about w...
python|pandas|list
4
372,405
57,988,620
How to better preprocess images for a better deep learning result?
<p>We are experimenting with applying a convolutional neural network to classify good surfaces and surfaces with defects.</p> <p>The good and bad images are mostly like the following:</p> <p>Good ones:</p> <p><a href="https://i.stack.imgur.com/50fkw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/...
<blockquote> <p>Is deep learning even an appropriate tool for defect detection like this in practice.</p> </blockquote> <p>Deep learning certainly is a possibility that promises to be universal. In general, it should rather be the last resort than the first approach. Downsides include:</p> <ul> <li>It is difficul...
python|tensorflow|machine-learning|deep-learning|data-science
0
372,406
57,932,548
Function that extracts data at specific indexes by passing indexes and numpy array as parameters, while being able to handle variations in dimensions
<p>I need to make a function that can pass in a numpy array (with no restrictions on shape/dimensions) and the indexes from where I want to extract data. </p> <p>Here is a simple example of some sample arrays, and what the function should return for a given input. </p> <pre><code> x = np.array( [ [2,3,1], [2, 1, 1], ...
<p>Numpy indexing allow you to do this:</p> <pre><code>x = np.array( [ [2,3,1], [2, 1, 1], ], [ [5, 3, 1], [6, 2, 4] ] ) y = np.array( [ [2,3,1], [2, 1, 1]] ) z = np.array( [2,3,1] ) #example: d=x[1,0,1]#returns 3 </code></pre> <p>like a normal list with 3 dimensions. so if all of the indexes you use match the arr...
python|arrays|numpy
0
372,407
57,817,565
Conversion of year column into respective years columns
<p><a href="https://github.com/Shristigithub/Population/blob/master/population.csv" rel="nofollow noreferrer">[[https://github.com/Shristigithub/Population/blob/master/population.csv]]</a><a href="https://github.com/Shristigithub/Population/blob/master/population.csv" rel="nofollow noreferrer">1</a> [<a href="https://i...
<p>Is this what you want:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'id':['a','a','b','c','c'], 'words':['asd','rtr','s','rrtttt','dsfd']}) print(df) zet = df.groupby('id')['words'].apply(','.join) print(zet) </code></pre> <p>Output:</p> <pre><code> id words 0 a asd 1 a rtr 2 b ...
python|pandas
0
372,408
57,798,848
Enumerate through 2D array in numpy and append to new array
<p>I'm trying to enumerate through a 2D numpy array of shape (512, 512), which holds the pixel values of an image. So basically it's an array representing width and height in pixel values for the image. I'm trying to enumerate through each element to output: [y_index, x_index, pixel_value]. I need these 3 output values...
<p>You could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.indices.html" rel="nofollow noreferrer"><code>numpy.indices</code></a> to do this. What you want ultimately is <code>image_data</code> with <code>y</code>, <code>x</code> indices and the corresponding pixels (<code>px</code>). There ar...
python|arrays|numpy|enumeration|numpy-ndarray
1
372,409
58,101,676
select specific word from first 2 lines, starting with specific word, regex
<p>data is pandas Series: i am using <code>df.B=df.A.str.extract(r'')</code> to create B column with extracted WHERE words df:</p> <pre><code>A HI my lines are so super WHERE1 my car car go anywhere next line like this HI my lines are so super WHERE2 my car one WHERE HI like me </code></pre> <p>Data above is test dat...
<p>You may use this regex with <code>MULTILINE</code> mode:</p> <pre><code>^HI\s.*(?:\n.*)?\b(WHERE1|WHERE2)\b </code></pre> <p><a href="https://regex101.com/r/y7jclc/1" rel="nofollow noreferrer">RegEx Demo</a></p> <p><strong>RegEx Details:</strong></p> <ul> <li><code>^HI\s</code>: Match a line starting with <code>...
python|regex|pandas
1
372,410
58,119,930
Keras fit_generator with images from directory and a constant tensor
<p>I have a simple CNN with input images of shape (5,5,3). As a first step I want to add a constant tensor to the input. According to the answer in my previous <a href="https://stackoverflow.com/q/58107942/3195597">SO question</a>, I have to define the constant tensor as an input layer (const_input), so that I can Add(...
<p>The problem lies with your <code>validation_data=</code> argument; your model expects <em>two</em> input arrays, whereas <code>validation_generator</code> supplies only <em>one</em>. You fixed this with <code>train_gen_with_const</code> - just extend it to val:</p> <pre class="lang-py prettyprint-override"><code>de...
tensorflow|keras
1
372,411
57,777,635
How to deal with NaN values in pandas (from csv file)?
<p>I have a fairly large csv file filled with data obtained from a machine for material testing (compression test). The headers of the data are Time, Force, Stroke and they are repeated 10 times because of the sample size, so the last set of headers is Time.10, Force.10, Stroke.10.</p> <p>Because of the nature of the e...
<p>Try <em>read_csv()</em> with <em>na_filter=False</em>. This should at least prevent from setting "empty" source cells to <em>NaN</em>.</p> <p>But note that:</p> <ul> <li>such "empty" cells can have an empty string as the content,</li> <li>the type of each column containing at least one such cell is <em>object</em>...
python|pandas|csv|nan
2
372,412
34,324,834
Disable/configure multithreading in default conda numpy
<p>Some versions/builds of numpy have multithreaded execution of certain operations. There are a number of questions on StackOverflow about how to enable this feature. In theory, it is great. However, I would like to disable it.</p> <p>The reason is that I am running some numpy code in the context of a script that use...
<p>Turns out that multithreading is controlled through the <code>OPENBLAS_NUM_THREADS</code> environment variable, so setting that to <code>1</code> will keep things in serial.</p>
multithreading|numpy|anaconda|blas|conda
6
372,413
34,357,617
Append 2D array to 3D array, extending third dimension
<p>I have an array <code>A</code> that has shape <code>(480, 640, 3)</code>, and an array <code>B</code> with shape <code>(480, 640)</code>.</p> <p>How can I append these two as one array with shape <code>(480, 640, 4)</code>? </p> <p>I tried <code>np.append(A,B)</code> but it doesn't keep the dimension, while the <c...
<p>Use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.dstack.html" rel="noreferrer"><code>dstack</code></a>:</p> <pre><code>&gt;&gt;&gt; np.dstack((A, B)).shape (480, 640, 4) </code></pre> <p>This handles the cases where the arrays have different numbers of dimensions and stacks the arrays ...
python|arrays|numpy|append
45
372,414
34,215,746
What is the difference between variable_scope and name_scope?
<p>What is the difference between <code>variable_scope</code> and <code>name_scope</code>? The <a href="https://www.tensorflow.org/programmers_guide/variable_scope#names_of_ops_in_tfvariable_scope" rel="nofollow noreferrer">variable scope tutorial</a> talks about <code>variable_scope</code> implicitly opening <code>nam...
<p>I had problems understanding the difference between <a href="https://www.tensorflow.org/api_docs/python/tf/variable_scope" rel="noreferrer">variable_scope</a> and <a href="https://www.tensorflow.org/api_docs/python/tf/name_scope" rel="noreferrer">name_scope</a> (they looked almost the same) before I tried to visuali...
python|scope|tensorflow
54
372,415
34,194,382
Sentiment Analysis using tensorflow
<p>I am exploring tensorflow and would like to do sentiment analysis using the options available. I had a look at the following tutorial <a href="http://www.tensorflow.org/tutorials/recurrent/index.html#language_modeling">http://www.tensorflow.org/tutorials/recurrent/index.html#language_modeling</a> </p> <p>I have wor...
<p>A commonly used approach would be using a Convolutional Neural Network (CNN) to do sentiment analysis. You can find a great explanation/tutorial in this <a href="http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/" rel="noreferrer">WildML blogpost</a>. The accompanying TensorFlow ...
sentiment-analysis|tensorflow
14
372,416
34,282,847
pandas: concat data frame with different column name
<p>Suppose I have this data frame</p> <pre><code>id x y 0 a hello 0 b test 1 c hi 2 a hi 3 d bar </code></pre> <p>I want to concat x and y into a single column like this keeping their ids</p> <pre><code>id x 0 a 0 b 1 c 2 a 3 d 0 hello 0 test 1 hi 2 hi 3 b...
<p>If ordering of rows is not important, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>:</p> <pre><code>print df id x y 0 0 a hello 1 0 b test 2 1 c hi 3 2 a hi 4 3 d bar s = df.set_ind...
python|pandas
1
372,417
34,376,896
Pandas DataFrames: how to wrap text with no whitespace
<p>I'm viewing a Pandas DataFrame in a Jupyter Notebook, and my DataFrame contains URL request strings that can be hundreds of characters long without any whitespace separating characters.</p> <p>Pandas seems to only wrap text in a cell when there's whitespace, as shown on the attached picture:</p> <p><a href="https:...
<p>You can set</p> <pre><code>import pandas as pd pd.set_option('display.max_colwidth', 0) </code></pre> <p>and then each column will be <strong>just as big as it needs to be</strong> in order to fully display it's content. It will <strong>not wrap the text</strong> content of the cells though (unless they contain sp...
python|pandas|ipython
29
372,418
34,026,780
Copying to a new DataFrame but failing on missing column
<p>I am doing the foll. in pandas:</p> <pre><code> all_df = pd.DataFrame() all_df[self.FAO_code] = per_df[self.FAO_code] all_df[self.ISO_code] = per_df[self.ISO_code] all_df[self.cft_id] = per_df[self.cft_id] all_df[self.cft_type] = per_df[self.cft_type] </code></pre> <p>In some cases, the column s...
<p>You could also do:</p> <pre><code>for col in [self.FAO_code, ..., self.cft_type]: if col in per_df.columns: all_df[col] = per_df.loc[:, col] </code></pre>
python|pandas
1
372,419
34,311,695
Split DF string column and add it as new column
<p>I want to take a DF column and build new column based on str splitting.<br> Column values looks like that: <em>abcd &lt;> 1234</em></p> <p>In order to split i'm using the following: </p> <pre><code>df['user_id'] = df['Customer User Id'].str.split('&lt;&gt;').str.get(1) </code></pre> <p>This action works but i'm...
<p>I am using this kind of data:</p> <pre><code>key1 key2 22 abcd &lt;&gt; 1234 34 abcd &lt;&gt; 1234 12 abcd &lt;&gt; 1234 55 abcd &lt;&gt; 1234 </code></pre> <p>And the code is:</p> <pre><code>my_df["key3"] = my_df['key2'].str.split('&lt;&gt;').str.get(1) </code></pre> <p>Output is :</p> <pr...
python|pandas
0
372,420
36,850,014
How to write two numpy arrays in text file in a proper format?
<p>I want to create input file that would have format like this(21 row and 20 columns)</p> <pre><code>0. 2900. 0. 2900. 0. 2900. 100. 2900. 100. 2900. 100. 2900. 200. 2900. 200. 2900. 200. 2900. 300. 3600. 300. 3600. 300. 3600. </code></pre> <p>Here is my code</p> <pre><code>import numpy as np import matplotli...
<p><code>numpy</code> has a great function <code>savetxt()</code> which saves an array to a file in exactly the format you're looking for. I'd suggest using this instead of <code>write</code>. </p> <p>Here's a quick example</p> <pre><code> sample_array = np.random.rand(3,2) myfile = open('foo.out', 'wb' ) np...
python|arrays|numpy
4
372,421
37,034,676
How to ensure that the behavior of pandas.to_csv() does not change
<p>The following code produces different results in python 2.7.5.final.0 with pandas 0.15.1 and numpy 1.9.1 and in python 2.7.11.final.0 with pandas 0.18.0 and numpy 1.10.4 (the anaconda package).</p> <p>The former version gives the result <code>18292498239.8</code>; the latter, <code>18292498239.824</code>.</p> <pr...
<p><strong>UPDATE2:</strong></p> <p>you can try to use <code>np.set_printoptions(precision=20)</code> function:</p> <pre><code>np.set_printoptions(precision=20) df.to_csv('d:/temp/a.csv', index=False) </code></pre> <p>gives me</p> <p>d:/temp/a.csv:</p> <pre><code>One 18292498239.824 123456789012345.12 </code></pre> <p>...
python|pandas|dataframe|anaconda
2
372,422
36,764,487
Pandas DateOffset, step back one day
<p>I try to understand why </p> <pre><code>print(pd.Timestamp("2015-01-01") - pd.DateOffset(day=1)) </code></pre> <p>does not result in</p> <pre><code>pd.Timestamp("2014-12-31") </code></pre> <p>I am using Pandas 0.18. I run within the CET timezone.</p>
<p>You can check <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.tseries.offsets.DateOffset.html" rel="noreferrer"><code>pandas.tseries.offsets.DateOffset</code></a>:</p> <blockquote> <p><code>*kwds</code> Temporal parameter that add to or replace the offset value.<br /> Parameters that add t...
date|pandas
25
372,423
36,694,313
pandas xlsxwriter, format table header - not sheet header
<p>I'm saving pandas DataFrame to_excel using xlsxwriter. I've managed to format all of my data (set column width, font size etc) except for changing header's font and I can't find the way to do it. Here's my example:</p> <pre><code>import pandas as pd data = pd.DataFrame({'test_data': [1,2,3,4,5]}) writer = pd.ExcelW...
<p>I think you need first reset default header style, then you can change it:</p> <pre><code>pd.core.format.header_style = None </code></pre> <p>All together:</p> <pre><code>import pandas as pd data = pd.DataFrame({'test_data': [1,2,3,4,5]}) writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter') pd.core.format.hea...
python|excel|pandas|format|xlsxwriter
50
372,424
36,816,466
Old numbers can't change in numpy.convolve and Python
<p>I am working with numpy.convolve. To be honest I am not sure if I am using the correct module for the project I am working.</p> <p>I want numpy convolve (or if there is any other module I can implement) not to change previous numbers. I don't want the old numbers changed I want them to be fixed. So when I get new d...
<p>You want to compute 3-neighborhood means. So you have a <code>mask=[1./3,1./3,1./3]</code> which size is <code>N</code>. </p> <p>See what happen on a simpler example , <code>numbers = [0,1,2,3,4]</code> , which size is <code>M&gt;=N</code> :</p> <pre><code>In [1]: numpy.convolve(numbers,mask) Out[1]: array([ 0....
python|numpy|fixed
1
372,425
37,038,733
Adding Column Headers to new pandas dataframe
<p>I am creating a new pandas dataframe from a previous dataframe using the <code>.groupby</code> and <code>.size</code> methods. </p> <pre><code>[in] results = df.groupby(["X", "Y", "Z", "F"]).size() [out] 9 27/02/2016 1 N 326 9 27/02/2016 1 S 332 9 27/02/2016 2 N 280 9 27/02/2...
<p>What you're seeing are your grouped columns as the index, if you call <code>reset_index</code> then it restores the column names</p> <p>so</p> <pre><code>results = df.groupby(["X", "Y", "Z", "F"]).size() results.reset_index() </code></pre> <p>should work</p> <pre><code>In [11]: df.groupby(["X","Y","Z","F"]).size...
python|pandas
6
372,426
36,772,082
Apply a comparison between two numpy.arrays to only one column but retrieve whole rows
<p>I have two numpy arrays with two columns each. </p> <pre><code>import numpy as np a = np.array([[1131, 1], [4131, 2], [421, 1], [41, 1]]) b = np.array([[5881, 2], [637, 2], [742, 2], [36, 2]]) </code></pre> <p>and I want ...
<p>Looks like a perfect case to <em>ab-use</em> <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> within <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a> -</p> <...
python|numpy
4
372,427
37,119,818
numpy.histogram fails after updating anaconda
<p>I have been using the matplotlib function <code>plt.hist</code> to generate histogram data from an array of values <code>mV</code>. This has worked fine in the past, but ever since I've updated my version of anaconda it throws back a <code>ValueError</code>:</p> <pre><code>------------------------------------------...
<p>Filter out any nan and inf from your data before plotting the histogram. See the bug report <a href="https://github.com/JosPolfliet/pandas-profiling/issues/6" rel="nofollow">here</a>.</p>
python|numpy|matplotlib|anaconda
0
372,428
36,704,397
Pandas read_csv multiple files
<p>What's the best way to loop through a bunch of files and create separate data frames for each file? I've looked through other questions, but it seems the point in each of those is to concatenate files into one data frame.</p> <p>For example, if I have mylist = ['a.csv','b.csv','c.csv'], and I want each of my data f...
<p>Use a dictionary comprehension:</p> <pre><code>dfs = {f.rsplit('.csv',1)[0]: pd.read_csv(file) for f in mylist} </code></pre>
python|pandas
4
372,429
36,756,907
Tensorflow on Docker: How to save the work on Jupyter notebook?
<p>Newbie to both Docker and Tensorflow and trying them out. Installation (on win10, using hyper-v driver) went fine and I can run </p> <pre><code>docker run -p 8888:8888 -it gcr.io/tensorflow/tensorflow </code></pre> <p>and get output like this:</p> <pre><code>[I 23:01:01.188 NotebookApp]←(B Serving notebooks from ...
<p>You can <a href="https://docs.docker.com/engine/reference/commandline/run/#mount-volume--v---read-only" rel="noreferrer">mount</a> current host folder to replace the default <code>/notebooks</code> folder in the container. Here is an example:</p> <pre><code>$ docker run -p 8888:8888 -v `pwd`:/notebooks -it gcr.io/t...
docker|tensorflow|jupyter-notebook
8
372,430
37,042,748
How to create a Rotation Matrix in Tensorflow
<p>I want to create a rotation matrix in tensorflow where all parts of it are tensors.</p> <p>What I have:</p> <pre><code>def rotate(tf, points, theta): rotation_matrix = [[tf.cos(theta), -tf.sin(theta)], [tf.sin(theta), tf.cos(theta)]] return tf.matmul(points, rotation_matrix) </code><...
<p>with two operations:</p> <pre><code>def rotate(tf, points, theta): rotation_matrix = tf.pack([tf.cos(theta), -tf.sin(theta), tf.sin(theta), tf.cos(theta)]) rotation_matrix = tf.reshape(rotation_matrix, (2,2)) r...
python|tensorflow
10
372,431
37,017,773
Pandas parse integers separated by commas and colons in a series
<p>Question is very similar to: <a href="https://stackoverflow.com/questions/32947781/pandas-sum-integers-separeted-by-commas-in-a-string-column">Pandas sum integers separeted by commas in a string column</a></p> <p>Solution: <code>df['B'].apply(lambda x: sum(map(int, x.split(','))))</code> </p> <p>Except the ser...
<h3>Setup</h3> <pre><code>from StringIO import StringIO import pandas as pd text = """ A B 0 1 0 1 2 3,1::4 2 3 1 ...
python|pandas
1
372,432
37,011,069
Why doesn't scikit-cuda subtract broadcast like numpy?
<p>skcuda.misc.subtract is not broadcasting as I expected. With this code:</p> <pre><code>import numpy as np import pycuda.gpuarray as gpuarray import skcuda.misc as gpumisc import pycuda.autoinit a = np.ones((3, 1)) b = np.ones((1, 3)) c = a - b assert np.allclose(c, np.zeros((3, 3))) a_gpu = gpuarray.to_gpu(a) b_g...
<p>If you're not bound to scikit-cuda, I'd suggest using TensorFlow for CUDA backend. It supports broadcasting natively on many of its operators. For your example:</p> <pre><code>import numpy as np import tensorflow as tf a = np.ones((3, 1)) b = np.ones((1, 3)) c = a - b assert np.allclose(c, np.zeros((3, 3))) with...
python|numpy|gpu
1
372,433
36,729,392
Pandas read_fwf: specify dtype
<p>I am reading in a huge fixed width text file in chunks and export the data as csv. Because <strong><em>pandas.read_fwf</em></strong> does not allow to specify the dtypes, I am wondering what other way there exists to force the columns to be strings. The reason is that pandas infers some columns as float even though ...
<p>The <code>converter</code> parameter can be used to preserve the data as strings since <code>pd.read_fwf</code> does not try to guess the dtype if a converter is specified:</p> <pre><code>import pandas as pd try: # for Python2 from cStringIO import StringIO except ImportError: # for Python3 from io...
python|pandas|dtype
7
372,434
37,073,954
getting unique date from python dataframe
<p>My dataframe has dates in format: dd-mm-yy hh:mm:ss</p> <p>E.g</p> <pre><code>15-14-2016 08:05:10 15-14-2016 08:15:30 15-14-2016 10:45:22 18-14-2016 06:23:10 18-14-2016 07:37:30 18-14-2016 12:48:22 </code></pre> <p>There are around 1000 rows and </p> <p>I used below code to get unique dates </p> <pre><code...
<p>I think 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> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unique.html" rel="noreferrer"><code>unique</code></a> if you need convert...
python|datetime|pandas|dataframe
5
372,435
36,972,414
Numpy, multiply 3x3 array by 3x10 array?
<p>I have a 3x10 matrix (in the form of a numpy array) and would like to multiply it by a 3x3 transformation matrix. I don't think np.dot is doing the full matrix multiplication. Is there a method for doing this multiplication with arrays?</p> <pre><code>transf = np.array([ [0.1, -0.4, 0],[0.9, 0.75, -0.1],[0.5, 0.7...
<p>You're missing commas in the last two entries of <code>transf</code>. Fix them and you'll get matrix multiplication as you'd expect:</p> <pre><code># Missing commas between 0.75 and -0.1, 0.75 and -0.9. transf = np.array([ [0.1, -0.4, 0],[0.9, 0.75 -0.1],[0.5, 0.75 -0.9] ]) # Fix with commas transf = np.array([ [0...
python|arrays|numpy|matrix
2
372,436
37,113,173
Compare 2 excel files using Python
<p>I have two <code>xlsx</code> files as follows:</p> <pre><code>value1 value2 value3 0.456 3.456 0.4325436 6.24654 0.235435 6.376546 4.26545 4.264543 7.2564523 </code></pre> <p>and </p> <pre><code>value1 value2 value3 0.456 3.456 0.4325436 6.24654 0.23546 6.376546 4.26545 4.264543 7.2564523 </code...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="noreferrer"><code>pandas</code></a> and you can do it as simple as this:</p> <pre><code>import pandas as pd df1 = pd.read_excel('excel1.xlsx') df2 = pd.read_excel('excel2.xlsx') difference = df1[df1!=df2] print difference </code></pre> <p>...
python|excel|pandas|compare|xlrd
26
372,437
37,010,837
How to write multidimensional NumPy array to disk the same as struct.pack?
<p>I have a routine that iteratively appends a 41x55 numpy array to an output file like the following:</p> <pre><code>fmt = 'ihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh' for x in range(0, 41): vmdata_file.write(struct.pack(fmt, *building_vms[x,:])) </code></pre> <p>I'm trying to replace this with a ca...
<p>One way is to first build the array in memory exactly how you like to have it on disk: </p> <pre><code>import numpy as np firstcol = building_vms[:,0].astype('i').view('h').reshape(len(building_vms), -1) tmp = np.hstack((firstcol , building_vms[:,1:].astype('h'))) tmp.tofile(vmdata_file) </code></pre> <p>Maybe sl...
python|arrays|numpy
0
372,438
37,058,236
Load checkpoint and evaluate single image with tensorflow DNN
<p>For research at university I am examining the oxford 17 flowers alexnet example. The example uses the API tflearn based on tensorflow. Training is working very well on my GPU, reaching an accuracy of ~ 97% after a while.</p> <p>Unfortunately evaluating single images isn't working yet in tflearn, I would have to use...
<p>for save: model.save('name.tflearn')</p> <p>for load: model.load('name.tflearn')</p> <p>and for testing in loop just load the model and follow following code</p> <pre><code>files_path = '/your/test/images/directory/path' img_files_path = os.path.join(files_path, '*.jpg') img_files = sorted(glob(img_files_...
python|tensorflow|conv-neural-network
0
372,439
36,730,939
Appending to List after Pandas if else statement
<p>I'm trying to append the <code>time</code> value to <code>plotList</code> wherever the <code>dup</code> column value is <code>False</code>.</p> <p>The DF = </p> <pre><code> lat time trip_id diff shifted Segment dup -7.12040 2015-12-24 02:03:10 18060.0 0.00003 0.00000 1 Fals...
<p>i guess you can do it this way:</p> <pre><code>plotList = df.loc[df['dup'] == False, 'time'].values </code></pre> <p>you're passing the whole DF as a parameter to your function, but are treating it as one row...</p> <p>depending on what do you want to get - array or list:</p> <pre><code>In [167]: df.loc[df['dup'...
python|python-2.7|pandas|dataframe
2
372,440
36,930,755
How do you apply a function incorporating random numbers to rows of a numpy array in python?
<p>So I have a 3D array with shape <code>(28, 28, 60000)</code>, corresponding to 60000 28x28 images. I want to get random 24x24 chunks of each image by using the following function:</p> <pre><code>def crop(X): x = random.randint(0,3) y = random.randint(0,3) return X[x:24+x, y:24+y,] </code></pre> <p>If I...
<p>Here is my attempt at it.</p> <p>Basically the idea is you will have to somehow split the matrix away from the last dimension (numpy doesn't let you apply over things which aren't a 1d array). You can do this using <code>dsplit</code>, and put it back together using <code>dstack</code>. </p> <p>Then you would appl...
python|arrays|numpy
1
372,441
36,816,284
Find closest number in a circular array
<p>I have a numpy array:</p> <pre><code>np.arange(1, 366) </code></pre> <p>I have 2 values: <code>355</code> and <code>129</code>. I want to find which one of them is closest value to a number within that array, say <code>36</code>.</p> <p>In this case, the answer will be <code>355</code> since I want the array to r...
<p>I utilized Polar coordinates mathematics to solve this:</p> <p><a href="https://i.stack.imgur.com/mJ1sL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mJ1sL.png" alt="enter image description here"></a></p> <pre><code>import numpy as np array = [355,129] target = 36 def distance(list_of_points...
python|numpy
2
372,442
37,015,278
reduce perimeter of polygon by eliminating points
<p>I don't know exactly how to state this question, so consider the following picture.<a href="https://i.stack.imgur.com/iIF10.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iIF10.png" alt="enter image description here"></a></p> <p>The polygons were generated by detecting contours of a rasterized m...
<p>You could try an alpha shape. Alpha shape is defined as edges in a delaunay triangulation not exceeding alpha.</p>
python|numpy|geometry|polygon|contour
0
372,443
37,000,316
pandas: pd.grouper trouble grouping by end of year date
<p>I have the following data frame:</p> <pre><code>url='https://raw.githubusercontent.com/108michael/ms_thesis/master/pacs.can.cl.abbridged' df=pd.read_csv('https://raw.githubusercontent.com/108michael/ms_thesis/master/pacs.can.cl.abbridged') df= df.set_index(pd.to_datetime(df['date']), inplace=False) df.head(3) ...
<pre><code>import pandas as pd import datetime as dt import numpy as np index= pd.date_range(start=dt.date(2014,02,04), periods=200, freq='1M') data = np.random.random(200) df = pd.DataFrame(data, index=index, columns=["col1"]) group = pd.TimeGrouper('A') grouped = df.groupby(group) for key, g in grouped: prin...
python|pandas|group-by
1
372,444
36,849,586
Trying to create a 2D array from python dictionary
<p>I am trying to create a 2D array from dictionary in python.</p> <pre><code>mydictionary={ 'a':['review','read','study'], 'b':['read'], 'c':['review','dictate']} </code></pre> <p>I want to have a 2D array that shows the number of items matching.(i.e compare the keys and their values and store the matching values in...
<p>A sweet way to obtain result is to use <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a>, the numpy big brother :</p> <pre><code>In [6]: md=mydictionary In [7]: df=pd.DataFrame([[len(set(md[i])&amp;set(md[j])) for j in md] for i in md],md,md) In [8]: df Out[8]: c a b c 2 1 0 a 1 3 1 b 0 1 ...
python|arrays|numpy
1
372,445
36,800,605
Read or construct an array from a binary file containing both integers and doubles in Python/NumPy
<p>I have a binary file that contains both integers and doubles. I want to access that data either in one call (something like: <code>x = np.fromfile(f, dtype=np.int)</code>) or sequentially (value by value). However, NumPy doesn't seem to allow to read from a binary file without specifying a type. Should I convert eve...
<pre><code>NumPy doesn't seem to allow to read from a binary file without specifying a type </code></pre> <p>No programming language I know of pretends to be able to guess the type of raw binary data; and for good reasons. What exactly is the higher level problem you are trying to solve?</p>
python|arrays|numpy|binaryfiles
0
372,446
54,864,100
Is there a way to impose a constraint in tensor flow, could I enforce some rule along the way?
<p>Is there some way to a constraint on the data generated by tensor flow, for example if my model produced two outputs can you impose some sort of constraint on these, like if a and b where the outputs could you pre-enforce something like (a+b)/2&lt;10? So the model wouldn't break this rule?</p> <p>Thanks in advance...
<p>If by "generated by TensorFlow" you mean generated by a neural network, I don't think it is possible to do that in general. You can't really guarantee that the output of a neural network never violates such hard constraints in general, especially at test time.</p> <p>Here's what you could do:</p> <ul> <li>Add a lo...
python-3.x|tensorflow|constraints
1
372,447
54,743,789
How to loop over multiple DataFrames and produce multiple list?
<p>I have some difficulties to create multiple lists using pandas from a list of multiple dataframes:</p> <pre><code>df1 = pd.read_csv('df1.csv') df2 = pd.read_csv('df2.csv') ... dfN = pd.read_csv('df1.csv') dfs = [df1, df2, ..., dfN] </code></pre> <p>So far, I am able to convert each dataframe into a list by <c...
<p>Use list comprehensions:</p> <pre><code>dfs = [i.values.tolist() for i in dfs] </code></pre>
python|pandas
2
372,448
54,968,094
Filter out duplicated data in pandas dataframe
<p>I have a dataframe with 3 columns ['id', 'city', 'time']: </p> <pre><code> city id time 0 CA 1 2019-01-01 05:34:21 1 CA 1 2019-01-01 08:10:21 2 CA 1 2019-02-01 06:10:21 3 NY 1 2019-02-01 16:10:21 4 NY 1 2019-02-01 18:10:21 5 CA 1 2019-02-01 22:10:21 6 CA 1 2019-02-...
<p>You can use:</p> <pre><code>df_new=df.groupby([df.city.ne(df.city.shift()).cumsum(),'city'],as_index=False).min() print(df_new) city id time 0 CA 1 2019-01-01 05:34:21 1 NY 1 2019-02-01 16:10:21 2 CA 1 2019-02-01 22:10:21 </code></pre>
python|pandas|dataframe
1
372,449
54,875,606
How to export numbers from python then reuse them
<p>I've got a function that integrates a pair of differential equations. Right now my code outputs a list for $c$ and a list for $\tau$. I'm plotting these the normal way. Now I want to do long calculations over a large time but the code takes a while so I would like to export some data that can later be called upon to...
<p>There are many ways to "export numbers from Python". You could write them to a <code>.txt</code> file, a <code>.json</code> file, or <code>.csv</code> file to name a few. I believe that since you mention <code>np.save()</code> that your data is currently in a <code>np.array()</code> format. If that is the case, then...
python|numpy|export
0
372,450
54,897,612
RuntimeError when changing the values of specific parts of a `torch.Tensor`
<p>Say I have a 3 dimentional tensor <code>x</code> initialized with zeros:</p> <pre><code>x = torch.zeros((2, 2, 2)) </code></pre> <p>and an other 3 dimentional tensor <code>y</code></p> <pre><code>y = torch.ones((2, 1, 2)) </code></pre> <p>I am trying to change the values of the first line of <code>x[0]</code> an...
<p>Is this what you want?</p> <pre><code>x = torch.arange(0, 8).reshape((2,2,2)) y = torch.ones((2,2)) x2 = x.permute(1,0,2) x2[0] = y x_target = x2.permute(1,0,2) </code></pre> <p>The value of first rows of <code>x</code> are changed by <code>y</code> .</p>
python|pytorch|tensor
1
372,451
54,936,655
Modifying Values of row values while iterating over dataframe
<p>I have this dataframe test_data:</p> <pre><code> Deal Year Month Billing Running_total payment over_payment 2 A 2018 December 21167.99 21167.99 1270.08 0.00 3 A 2018 December -3184.59 17983.40 -1270.08 0.00 4 A 2019 January 1855.10 198...
<p>Here's a method that gets your desired answer in a single try:</p> <pre class="lang-py prettyprint-override"><code>for deal in test_data.Deal.unique(): over_payment = 0 # reset for each deal for idx, row in test_data[test_data.Deal == deal].iterrows(): if row.over_payment &lt; 0: over_p...
python|pandas|iterator
0
372,452
54,960,933
Cumulative sum based on mutiple condition in dataframe
<p>I'm stuck on a problem which I think is not complicated but I can't see an easy way ...</p> <p>I have a dataframe (stats_match) like this with 11 000 rows:</p> <pre><code>domicile exterieur season home away FC Metz Stade Rennais FC 1999 0.0 0.0 Paris Saint-Germ...
<p>You can do this natively in <code>pandas</code>.</p> <p>First, if I understand you correctly, you only want the teams in <code>stade</code>:</p> <pre><code>filtered_stats_match = stats_match[stats_match[['domicile', 'exterieur']].isin(stade['equipe']).any(axis=1)] </code></pre> <p>After this, you can simply perfo...
python|pandas|dataframe|cumulative-sum
0
372,453
55,082,483
Why can I not import Tensorflow.contrib I get an error of No module named 'tensorflow.python.saved
<p>Hi I just installed <code>Tensorflow</code> on my Mac and I want to use <code>tf.contrib.slim</code> but when I use it I get this </p> <pre><code>import tensorflow as tf slim = tf.contrib.slim </code></pre> <p>Error:</p> <blockquote> <p>File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/si...
<p>For anyone who is trying some old codes from <strong><em>github</em></strong> with <code>Tensorflow 1.x.x</code> versions while having <code>Tensorflow 2.0.x</code> please note that <code>tf.contrib</code> no longer exist in <code>Tensorflow 2.0.x</code> and it's modules were moved.<br> Please google the name of the...
python|tensorflow
72
372,454
55,091,324
Keras doesn't seem to correctly load a trained model
<p>Following along with a tutorial to learn keras i've hit a bit of a snag. i have some code to solve the lunar lander problem, which seems to train the agent up and get pretty good scores after many iterations of training (eg for the Lunar lander problem hes getting scores between 200 - 400 usually), but when i load...
<p>The question is quite old but maybe it can help someone else. I was having the same issue and actually realized it has nothing to do with loading the model.</p> <p>The issue is this line:</p> <pre><code>def __init__(self, state_size, action_size): ... self.epsilon = 1.0 # exploration rate </code></pre> <p>When ...
python|tensorflow|keras
1
372,455
54,735,106
Accumulate gradients in Estimator with distribution strategy
<p>In order to reduce the number of synchronization in distributed training, I want to do local accumulation of gradients first. it is just like you can have multiple GPUs, but in serial not in parallel.</p> <p>I want to use it in the estimator.train loop with distribute strategy, such as mirrored and collective allre...
<p>I think you can achieve this via passing train_ops to the estimator. Calling tensorflow ops alone inside an estimator model_fn has absolutely NO effect. Because by design the model_fn is called only once per training session, hence every op you put in it will also be executed only once. In addition to that, all tf.c...
tensorflow|distributed|tensorflow-estimator
4
372,456
54,708,010
How to fix Docker dependencies installation?
<p>I have a movie recommender system and I am trying to create a docker image for it.</p> <p>requirements.txt </p> <pre><code>pandas==0.22.0 requests==2.18.4 Django==2.0.6 Scrapy==1.5.1 numpy==1.14.0 scipy==1.0.0 pymongo==3.7.2 </code></pre> <p>Dockerfile:</p> <pre><code>FROM python:3 MAINTAINER SPARSH KEDIA ENV P...
<p>Looks like a problem related to <code>numpy</code>, probably due to libraries <code>setuptools</code> and <code>wheel</code> build.</p> <p>Add to requirements:</p> <pre><code>pip==19.0.2 setuptools==40.6.3 wheel==0.32.0 </code></pre> <p>This link below was developed for use with AWS SageMaker, but maybe can help ...
python|macos|numpy|docker|pip
0
372,457
55,031,427
Deepcopy pandas DataFrame containing python objects (such as lists)
<p>Need help understanding variable assignment, pointers, ...</p> <p>The following is reproducible.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ 'listData': [ ['c', 'f', 'd', 'a', 'e', 'b'], [5, 2, 1, 4, 3] ]}) df['listDataSort'] = df['listData...
<p>When you run </p> <pre><code>df['listDataSort'] = df['listData'] </code></pre> <p>All you do is copy the <em>references</em> of the lists to new columns. This means only a shallow copy is performed and both columns reference the same lists. So any change to one column will likely affect another.</p> <p>You can us...
python|python-3.x|pandas|memory-management
5
372,458
54,786,539
Creating a pandas dataframe from a dictionnary and with different types of values
<p>I am really not used to pandas, thus the question on how to resolve this problem:</p> <p>I have a dictionary called <code>table</code> which is similar to:</p> <pre><code>table = dict() table[(1, 1)] = [1000, (1.05, 1.02), [Class1(1.05), Class1(1.02)]] table[(2, 3)] = [3400, (1.8, 2.9), [Class1(1.8), Class1(2.9)]]...
<p>Try it:</p> <pre><code>df = pd.DataFrame.from_dict(table, orient='index').reset_index().iloc[:,:3] df.columns =['Key','Integer', 'Replacement key'] # swap the column integer and replacement key df = df[['Key','Replacement key','Integer']] print(df) # export .csv df.to_csv('test.csv') Key Replacement key...
python|pandas|dataframe|dictionary
1
372,459
54,927,437
Count occurrences of a character in a column of dataframe in pandas
<p>I have a dataframe with the following structure</p> <pre><code>Debtor_ID | Loan_ID | Pattern_of_payments Uncle Sam Loan1 11111AAA11555 Uncle Sam Loan2 11222A339999 Uncle Joe Loan3 1111111111111 Uncle Joe Loan4 111222222233333 Aunt Annie Loan5 1 Aunt C...
<p>First step is create <code>DataFrame</code> by <code>Counter</code> in list comprehension, then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> for add missing categories and change order of columns, <code>rename</co...
python|pandas|dataframe
3
372,460
54,770,249
Why aren't torch.nn.Parameter listed when net is printed?
<p>I recently had to construct a module that required a tensor to be included. While back propagation worked perfectly using <code>torch.nn.Parameter</code>, it did not show up when printing the net object. Why isn't this <code>parameter</code> included in contrast to other modules like <code>layer</code>? (Shouldn't i...
<p>When you call <code>print(net)</code>, the <code>__repr__</code> method is called. <a href="https://docs.python.org/3/reference/datamodel.html#object.__repr__" rel="noreferrer"><code>__repr__</code></a> gives the “official” string representation of an object. </p> <p>In PyTorch's <a href="https://pytorch.org/docs/s...
python|pytorch
10
372,461
54,959,861
plot grouped information from survey
<p>I have a dataframe with a variable of interest (categorical, here <code>Yes</code>, <code>No</code>, etc.) and a grouping variable (see below):</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ 'ID': range(100), 'group': np.random.choice(['A', 'B', 'C'], 100), 'Response':np.rand...
<p>You should do <code>unstack</code> without select the <code>columns</code> , the <code>groupby</code> output is <code>Series</code>, and notice you are using <code>Series</code> <code>groupby</code> not <code>pd.DataFrame.groupby</code></p> <pre><code>df['Response'].groupby(df['group']).value_counts().unstack(fill_...
python|pandas|matplotlib
3
372,462
54,826,766
Automate the process of comparing multiple columns of a dataframe and storing data into a new column
<p>I have an excel file which I imported as a dataframe. The dataset looks like this:</p> <pre><code>rule_id reqid1 reqid2 reqid3 reqid4 53139 0 0 1 0 51181 1 1 1 0 50412 0 1 1 0 50356 0 0 1 0 50239 0 1 0 1 5023...
<p>First compare <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html" rel="nofollow noreferrer"><code>shift</code></a>ed DataFrame with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>DataFrame.eq</code></a>,...
python|pandas|dataframe
3
372,463
54,820,821
Output score , class, id and BOXES Extraction using TensorFlow object detection
<p>According to this <a href="https://stackoverflow.com/questions/51213290/output-score-class-and-id-extraction-using-tensorflow-object-detection">question</a>. Mine is; Let us assume that there is one picture that contains 3 cats ,2 dogs and 1 bird. After detection of whole object how could we get the xmin ymin xmax ...
<p>After these lines</p> <pre><code> (boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) </code></pre> <p>you can retrieve the information you need looking into</p> <pre><code> boxes, scores, classes, nu...
tensorflow|object-detection|object-detection-api
0
372,464
54,701,578
Can I choose to manually update weights in my neural network to allow an essentially infinite batch size?
<p>I am feeding large images into my CNN, and for some reason, converting the images to grayscale or making my network much smaller has no impact whatsoever on my maximum batch size. If I do anything more than 4, I run out of memory on my 16GB cpu. I am loading in each batch at a time, but I still run into memory issue...
<p>You need to use a batch generator. With Keras see <a href="https://keras.io/models/model/#fit_generator" rel="nofollow noreferrer"><code>model.fit_generator</code></a>. </p> <p>Define your generator similarly to (taken from the docs):</p> <pre><code>def generate_arrays_from_file(path): while True: with...
python|tensorflow|neural-network
1
372,465
55,074,539
Passing Column Names from a tuple to Pandas
<p>My Scenario looks like this, where i have identified the columns having NaN values using,</p> <pre><code>nan_cols=tuple(train.columns[train.isnull().sum()&gt;0]) </code></pre> <p>Now, I need to find the correlation between these columns and target variable. So I tried something like,</p> <p><code>train[[nan_cols,...
<p>By this line</p> <pre><code>train[[nan_cols,'SalePrice']].corr() </code></pre> <p>you trying to access <strong>rows</strong>. Also <code>[nan_cols,'SalePrice']</code> gives a <strong>list</strong> of a <strong>tuple</strong> and an <strong>object</strong>: <code>[(tuple),object]</code></p> <p>A good practice is t...
python|pandas|indexing|data-science|namedtuple
0
372,466
54,792,336
Filtering a DataFrame index by another index or a value
<p>I have a multi-indexed dataframe that looks like this:</p> <pre><code> status value id country 1234 US Complete 54 2345 US Ongoing 3 UK Complete 343 ...
<p>You 2nd question No <code>Ongoing</code></p> <pre><code>sliceidx=~df.index.get_level_values(0).isin(df.loc[df.status=='Ongoing'].index.get_level_values(0)) df[sliceidx] Out[474]: status value id country 1234 US Complete 54 </code></pre> <p>Your 1st question no <code>U...
python|pandas
2
372,467
55,004,985
convert pandas dataframe to json with columns as key
<p>I have a data frame like this:</p> <pre><code>df: Col1 col2 col3 col4 A 1 2 3 A 4 5 6 A 7 8 9 B 3 2 1 B 4 4 4 </code></pre> <p>I want to create a nested json file for each col1 values, the inside it there w...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code...
python|json|pandas|dataframe
2
372,468
54,936,913
Fastest way to perform comparisons between every column using Pandas
<p>I have an excel file with 100 columns each with 1000 entries. Each of those entries can only take 3 particular values of (0.8, 0.0 and 0.37) I want to count the number of mismatches between every combination of two column's entry.</p> <p>For example, the excel sheet below shows the mismatches between the columns:</...
<p>This is what I will handle this problem </p> <pre><code>from itertools import combinations L = df.columns.tolist() pd.concat([df[x[0]]!=df[x[1]] for x in list( combinations(L, 2))],axis=1).sum(1) 0 3 1 2 dtype: int64 </code></pre>
python|pandas
3
372,469
55,078,202
How to show frequency of elements in pandas DataFrame?
<p>I have a pandas DataFrame containing the following columns (with an existing numeric index):</p> <pre><code> points | variety ---------------- 1 97 | Chardonnay 17 67 | Cabernet Sauvignon 12 70 | Cabernet Sauvignon 8 97 | Chardonnay </code></pre> <p>I would like to transform this into ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>Pandas.crosstab</code></a> for this:</p> <pre><code>pd.crosstab(index=df.points, columns=df.variety) </code></pre> <p>[out]</p> <pre><code>variety Cabernet Sauvignon Chardonnay p...
python|pandas|dataframe|pandas-groupby
2
372,470
55,049,479
Tensorflow for Poets label_image issue
<p>I am trying to do the Tensorflow for Poets tutorial and I am on step 6 which is using the retrained model. I am trying to run this command:</p> <pre><code>python -m scripts.label_image --graph=tf_files/retrained_graph.pb -- image=tf_files/flower_photos/daisy/21652746_cc379e0eea_m.jpg </code></pre> <p>and this erro...
<p>Well apparently the layer is wrong, looked at the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/label_image/label_image.py" rel="nofollow noreferrer">official github</a> and there they use the name 'input', maybe that works. If that does not work, you need to load in your model an...
python|python-3.x|tensorflow|input
0
372,471
54,887,616
AttributeError: module 'dateutil.parser' has no attribute 'parse' pandas on python 3.7
<p>I tried install pandas via command <code>pip install pandas</code> and got error:</p> <pre><code>import pandas ../python3.7/site-packages/pandas/compat/__init__.py", line 440, in &lt;module&gt; parse_date = _date_parser.parse AttributeError: module 'dateutil.parser' has no attribute 'parse' </code></pre>
<p>pip install python-dateutil==2.5.* and then install pandas. It solves that problem.</p>
python|pandas|python-3.7
3
372,472
54,857,554
OpenAI Gym Atari games, TD Policy application
<p>Can I apply TD policy to such environments? Or only methods like DQN and why?</p> <p>I try to apply TD policy evaluation to Gym's Atari games' simulations in Python and I am a little new to it. I have this Value class:</p> <pre><code>class V_Class(): """ Class to store the state Value function V(s) = expecte...
<p>You are trying to search in a dictionary(<code>f</code>) with a numpy array (<code>obs</code>) as the key like in this example:</p> <pre><code>import numpy as np array = np.ndarray([1,2,3]) dict = {} if array not in dict: print("Its not") else: print("Its in") </code></pre> <p>that returns the same error:<...
python|dictionary|reinforcement-learning|numpy-ndarray|openai-gym
0
372,473
54,728,905
Docker Tensorflow-Serving Predictions too large
<p>I'm trying to serve my model using Docker + tensorflow-serving. However, due to restrictions with serving a model with an iterator (using<br> <code>make_initializable_iterator()</code> ), I had to split up my model. </p> <p>I'm using grpc to interface with my model on docker. The problem is that my predicted ten...
<p>Default message length is 4MB in gRPC, but we can extend size in your gRPC client and server request in python as something given below. You will be able to send and receive large messages without streaming</p> <pre><code>request = grpc.insecure_channel('localhost:6060', options=[('grpc.max_send_message_length', ...
docker|grpc|tensorflow-serving
7
372,474
54,988,878
Change a column of all duplicated row to same value
<p>Here I have a df with multiple ID belonging to the same email. I want to change all duplicated Email's ID to the same for each unique Email and not dropping any rows.</p> <p>Sample DF:</p> <pre><code> ID Email 1 a@gmail.com 2 a@gmail.com 3 b@gmail.com 4 c@gmail.com 5 c@gmail.com </code></p...
<p>IIUC</p> <pre><code>df['ID']=df.groupby('Email').ID.transform('first') df Out[195]: ID Email 0 1 a@gmail.com 1 1 a@gmail.com 2 3 b@gmail.com 3 4 c@gmail.com 4 4 c@gmail.com </code></pre>
python|pandas|numpy
2
372,475
54,908,466
Merge several data frame, keep only one set of colnames
<p>I'm using a package which for each element in a list, print in a file the following lines:</p> <pre><code>Entry Entry name Status Protein names Gene names Organism A0A20CSC4 A0A20CSC4_1PHYC unreviewed Uncharacterized protein OlL7_200 Ostreococcus lucimarinus virus 7 Entry Entry name Status Protein...
<p>So one way to get that type of output is if you drop NaN values.</p> <p>So you could do, <code>blast.dropna(inplace=True)</code></p> <p><code>blast.drop(blast[blast['Entry'] == 'Entry'].index, inplace=True)</code></p> <p>This should work.</p>
python|pandas
1
372,476
54,785,894
Indexing a DataFrame
<p>I am new to Python and I am trying to use indexing to obtain the last name along each row.</p> <pre><code>import numpy as np import pandas as pd def manager(vec): for i,val in enumerate(vec): if val == np.NaN: break return vec[i - 1] df = pd.DataFrame({'ID':[23,15,20], 'L1_name': [...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>filter</code></a> with forward filling per rows of missing values with seelct last column by positions:</p> <pre><code>s = df.filter(like='Name').ffill(axis=1).iloc[:,-1] print (s) 0 J...
python|pandas|dataframe|indexing
1
372,477
54,851,623
Python=>Pandas=> DataFrame==> While performing drop_duplicates(),
<p>Is there any way to keep some columns from first occurance and some columns from last occurance..?</p> <p>Let's consider the following example.</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-html lang-html pre...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.agg</code></a> with first and last aggregate function, but all another columns are lost:</p> <pre><code>#if need convert to datetimes and sorting c = ['s...
python-3.x|pandas
0
372,478
54,778,544
Boolean comparison of each value across two data frames
<p>I have two dataframes (read from csvs) with identical columns but likely different rows. I'm trying to produce a third data frame that has the index on the left and a TRUE or FALSE value for each column where there is a match for a given index record. Here is a simplistic example</p> <pre><code>df1 = pd.DataFrame(n...
<p>In that case you may need to use <code>eq</code>:</p> <pre><code>df1.eq(df2) Col1 Col2 Col3 ID 100 True True True 101 True True True 102 False False False 105 False False False </code></pre>
python-3.x|pandas
2
372,479
54,835,968
loop through a list and convert a column to datatime
<p>I have a list that contains dataframes. I want to loop though each dataframe in the list and for each dataframe select column 'Time' and convert it to a datetime object. This is the code that I wrote but it gives the error "list indices must be integers or slices, not DataFrame"</p> <pre><code>for i in list_of_data...
<p>Your problem is immediately at the front:</p> <pre><code>for i in list_of_dataframes: list_of_dataframes[i] ... </code></pre> <p><code>i</code> is a data frame, just as you asked. Why are you trying to use it as an index into the list of data frames? Try this, instead:</p> <pre><code>for df in list_of_datafra...
python|pandas|loops|datetime
0
372,480
54,805,307
ValueError: Cannot feed value of shape (637, 1162) for Tensor u'Placeholder:0', which has shape '(?, 637, 1162)'
<p>i m getting the mentioned error. i want to load single image as input and train it across given masked image for image binary classification. </p> <pre><code>import tensorflow as tf import os import cv2 import matplotlib.pyplot as plt import numpy as np images = [] file_names = [os.path.join('../', f) ...
<p>Sounds like you are missing the batch size dimension, try <code>np.expand_dims(image, dim=0)</code></p>
python|tensorflow|machine-learning|deep-learning
0
372,481
54,963,381
Pandas: Create a new column in a data frame with values calculated from an already existing column, i. calculate maximum
<p>I want to create a new column with a max values calculation on the first column, as follows: </p> <pre><code> High Highest2P Highest3P 0 101.0 102.0 103.0 1 102.0 103.0 109.0 2 103.0 109.0 109.0 3 109.0 109.0 4 100.0 </code></pre> <p></p> <pre><code>from pandas import * ...
<p>You can use <code>Rolling.max</code> with <code>assign</code>:</p> <pre><code>df.assign(**{ f'Highest{i}P': pd.Series(df.High.rolling(i).max().dropna().values) for i in range(2, 4)} ) High Highest2P Highest3P 0 101.0 102.0 103.0 1 102.0 103.0 109.0 2 103.0 109.0 109....
python|pandas|dataframe
1
372,482
54,941,243
How to split colour channels in openCV without returning a gray scale image? I have tried the following it returns a gray scale image
<p>How to split colour channels in openCV without returning a gray scale image? I have tried the following it returns a gray scale image?</p> <pre><code>import cv2 import numpy as np img = cv2.imread("1.jpeg") (channel_b, channel_g, channel_r) = (img[:,:,0], img[:,:,1], img[:,:,2]) cv2.imshow('red',channel_b) cv2.wa...
<p>The thing is, that the seperate channels do not really have a color assigned to them.</p> <p>If you use <code>imshow</code> to display an image of dimensions <code>(m, n, 3)</code> the method assumes that the 3 channels are representing R, G and B. However if it gets an image of dimensions <code>(m, n, 1)</code> or...
python-3.x|image|numpy|computer-vision|opencv3.0
0
372,483
54,937,706
TensorFlow GPU doesn't work, How to install it?
<p>I started learning about the tensorflow recently and decided to switch to the GPU version, because it is much faster, but I can not import it, it always gives the same error.</p> <p>I already tried:</p> <blockquote> <ul> <li>Installing it by pip, in python 3.6.8, cuda 10 and the most recent cuDNN for cuda 10 ...
<p>just have a look here: <a href="https://www.tensorflow.org/install/gpu" rel="nofollow noreferrer">https://www.tensorflow.org/install/gpu</a></p> <p>Tensorflow supports CUDA 9.0, you will need to downgrade your CUDA or use one of the tensorflow's docker images: <a href="https://www.tensorflow.org/install/docker" re...
python|tensorflow|importerror
1
372,484
54,943,294
use pd.read_csv on an opened file
<p>My program is writing on an .csv file : </p> <pre><code>try : out1 = open(chemin1, 'w') Logger.info('file opened') except IOError : Logger.warning('IOError') </code></pre> <p>then I'm trying to use pd.read_csv on the same file : </p> <pre><code>df=pd.read_csv(chemin1, sep=';', decimal=',') </code...
<p><code>out1 = open(chemin1, 'w')</code>, operation system will <strong>lock</strong> chemin1 in disk and prevent other to read or write something until you complish writing and <strong>close</strong> file. Otherwise, there will be conflicting. Just imagining that, two ones without knowing each other exsit write somet...
python|pandas|file
0
372,485
54,902,641
Can I implement kaldi-pytorch on windows?
<p>kaldi can only be used on windows via VM configuration (fedora 29 for example) , which massively consumes ressources of computations and late working flow . is there any other suitable way to configure and implement kaldi-pytorch on windows10 ? thanks </p>
<p>It is hopeless to do modern speech research on Windows, nobody uses it. Use Linux, everything will be smooth.</p>
pytorch|named-entity-recognition|kaldi
0
372,486
55,065,007
How to perform inner join in multiple columns in pandas
<p>I have 2 dataframe namely accidents_data which has 15 columns and bad_air_quality_data dataframe whch has 5 columns.</p> <p>Now i'd like to inner join both data frames on column ['District Name', 'Weekday', 'Hour', 'Month'] and finally keep only the data from accidents_data after joining. </p> <p>accidents_data:</...
<p>I think i figured out the solution. While merging the data the datatype of same columns were different. After making that correction, the merge worked.</p>
python|pandas
1
372,487
54,953,289
Convert a Python DataFrame into a list of dictionaries
<p>I have a dataframe and want to convert it to a list of dictionaries. I use <code>read_csv()</code> to create this dataframe. The dataframe looks like the following: </p> <pre><code> AccountName AccountType StockName Allocation 0 MN001 #1 ABC 0.4 1 MN001 ...
<pre><code>import pandas as pd import numpy as np d = np.array([['MN001','#1','ABC', 0.4], ['MN001','#1','ABD', 0.6], ['MN002', '#2', 'EFG', 0.5], ['MN002', '#2', 'HIJ', 0.4], ['MN002', '#2', 'LMN', 0.1]]) df = pd.DataFrame(data=d, columns = ['Account...
python|pandas|dataframe|dictionary
4
372,488
54,990,007
Python 3.7+Numpy+pandas Arrays Selecting data between a range
<p>Ok I'm going to try to explain my problem, I have a csv file with data, the data is wavelength and amplitude, the image is include here.</p> <p><a href="https://i.stack.imgur.com/5fm1Y.png" rel="nofollow noreferrer">CSV data</a></p> <p>So, I want to select only data between 500nm and 800nm (wave),</p> <pre><code>...
<p>Like @ALollz pointed out, you shouldn't split the DataFrame up. Instead just filter the whole dataframe on wavelength. See the docs for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a></p> <pre><code>import pandas...
python|pandas|numpy|python-3.7
0
372,489
55,029,551
Median of string column Pandas data frame
<p>I need median of pandas data frame column which is having string values. but I don't know I am getting this error.Instead it is expected to give me the most repeated value. Why median function is trying to convert expected value into float</p> <pre><code>df_train["Electrical"] 0 SBrkr 1 SBrkr 2 SB...
<p>The median formula is {(n + 1) ÷ 2} where “n” is the number of items in the set.</p> <p>But you are trying with string, which is not numeric</p> <p>If you want most common values try this</p> <pre><code>df_train[&quot;Electrical&quot;].value_counts().idxmax() </code></pre>
python|pandas
4
372,490
54,819,017
Identifying the most frequently occurring value (string) in a column
<p>I have a very large dataset (10 GB) in csv format with various columns and rows. One of the columns is IDs (represented as strings) of some class of individuals. The IDs are all scrambled in the data, and each individual ID may occur more than once. I'd like to find the ID of the individual that occurs most frequent...
<p>You can use value_counts of pandas.</p> <blockquote> <p><strong>value_counts</strong>: Returns object containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element. Excludes NA values by default.</p> </blockquote> <pre><cod...
python|pandas|group-by|pandas-groupby|data-science
3
372,491
54,887,445
Tensorflow tf.hessian returns only zeros
<p>I have a trained keras model of which I need to compute both the gradients and hessian of the output respect to the input. The input <code>X</code> is a 5000x3 numpy array and the output <code>y</code> is 5000x1.</p> <p>The gradient computation works fine both using keras' gradients and tensorflow's gradients funct...
<p>What do you mean by "using the calculated gradient as an input for another <code>get_derivative</code> call"? Are you referring to <code>get_derivatives_NN</code>?</p>
python|tensorflow|keras|hessian
0
372,492
55,085,959
How to check if a string contains substring when both are stored in lists in python?
<p>My main string is in dataframe and substrings are stored in lists. My desired output is to find the matched substring. Here is the code I am using.</p> <pre><code>sentence2 = "Previous study: 03/03/2018 (other hospital) Findings: Lung parenchyma: The study reveals evidence of apicoposterior segmentectomy of LUL ...
<p>I don't really use TextBlob, but I have two methods that might help you get to your goal. Essentially, I'm splitting the sentence by a whitespace and iterating through that to see if there are any matches. One method returns a list and the other a dictionary of index values and the word.</p> <pre><code>### If you...
python|string|pandas|textblob
1
372,493
55,109,138
pandas - remove specific sequence from column
<p>I want to remove specific sequences from my column, because they appear a lot and don't give me a lot of extra information. The database consists of edges between nodes. In this case, there will be an edge between node 1 and node 1, node 1 and node 2, node 2 and node 3.....</p> <p>However, the edge 1-5 happens arou...
<p>Here is one way:</p> <pre><code>import numpy as np import pandas as pd def find_drops(seq, df): if seq: m = np.logical_and.reduce([df.num.shift(-i).eq(seq[i]) for i in range(len(seq))]) if len(seq) == 1: return pd.Series(m, index=df.index) else: return pd.Series(...
python|pandas|graph|sequence|networkx
1
372,494
55,065,496
Calculation on list of numpy array
<p>I'm trying to do some calculation (mean, sum, etc.) on a list containing numpy arrays. For example:</p> <blockquote> <p>list = [array([2, 3, 4]),array([4, 4, 4]),array([6, 5, 4])]</p> </blockquote> <p>How can retrieve the mean (for example) ? In a list like <code>[4,4,4]</code> or a numpy array like <code>array(...
<p>If <code>L</code> were a list of scalars then calculating the mean could be done using the straight forward expression:</p> <pre><code>sum(L) / len(L) </code></pre> <p>Luckily, this works unchanged on lists of arrays:</p> <pre><code>L = [np.array([2, 3, 4]), np.array([4, 4, 4]), np.array([6, 5, 4])] sum(L) / len(...
python|list|numpy
0
372,495
54,734,957
Difference between transpose() and .T in Pandas
<p>I have a sample of data:</p> <pre><code>d = {'name': ['Alice', 'Bob'], 'score': [9.5, 8], 'kids': [1, 2]} </code></pre> <p>I want to display simple statistics of the dataset in pandas using <code>describe()</code> method.</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(data=d) print(df.describe...
<p>There is no difference. As mentioned in the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.T.html" rel="noreferrer"><code>T</code></a> attribute documentation, <code>T</code> is simply an accessor for the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas...
python|pandas
8
372,496
54,742,406
categorizing different texts for Python
<p>I have a dataset where each row is a specific compliance violation. The first column is the name of the violation (df['Violations'] Fire Exit, Aisle, Ergonomic Seats..up to 130 violations), the second column represents the gravity of the violation (df['Category'] Minor, Medium, Major, Critical), the 3rd the descript...
<blockquote> <p>it would take me quite a bit to identify keywords for each violation category</p> </blockquote> <p>This is called Topic Modeling task and you can achieve this using Latent Dirichlet Allocation (LDA) which will automatically form text clusters for you. LDA considers each document as a collection of to...
python|pandas|text|categorization
1
372,497
54,731,936
How to merge rows with combination of values in a DataFrame
<p>I have a DataFrame (df1) as given below</p> <pre><code> Hair Feathers Legs Type Count R1 1 NaN 0 1 1 R2 1 0 Nan 1 32 R3 1 0 2 1 4 R4 1 Nan 4 1 27 </code></pre> <p>I want to merge rows based by different combinations of the...
<p>A possible way to do it is by replicating each of the rows containing <code>NaN</code> and fill them with values for the column.</p> <p>First, we need to get the possible not-null unique values per column:</p> <pre><code>unique_values = df.iloc[:, :-1].apply( lambda x: x.dropna().unique().tolist(), axis=0)....
python|pandas|dataframe|combinations
1
372,498
54,749,793
Appending rows from one CSV to another in Python
<p>I have looked at many solutions for this but cannot find one that works for what I want to do.</p> <p>Basically I have 2 CSV files:</p> <blockquote> <p>all.csv</p> </blockquote> <pre><code>1 Wed Oct 03 41.51093923 41.51093923 41.51093923 41.51093923 2 Wed Oct 04 3 Wed O...
<p>You don't need to use <code>pandas</code>. Simply append one csv to another:</p> <pre><code>with open('original.csv', 'r') as f1: original = f1.read() with open('all.csv', 'a') as f2: f2.write('\n') f2.write(original) </code></pre> <p>Output:</p> <pre><code>1 Wed Oct 03 41.51093923 41.51093923 41....
python|pandas|csv|merge|dataset
6
372,499
55,135,556
removing non English words from df.columns
<p>I am appending multiple datasets together, unfortunately in the data collection some data collectors added the translation to the English question.</p> <p>df['What is your name'] is reported in other datasets as df['What is your name Como te llamas']</p> <p>Ideally, I would only want df['What is your name']</p> <...
<p>I think you need loop by columns names for pass scalar <code>string</code> to <code>wordpunct_tokenize</code> function:</p> <pre><code>df_t = pd.DataFrame(columns=['What is your name Como te llamas']) words = ['what','is','your','name'] df_t.columns = [" ".join(w for w in nltk.wordpunct_tokenize(x) ...
python|pandas|nltk
0