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
366,700
13,732,025
Get array elements from index to end
<p>Suppose we have the following array:</p> <pre><code>import numpy as np a = np.arange(1, 10) a = a.reshape(len(a), 1) array([[1], [2], [3], [4], [5], [6], [7], [8], [9]]) </code></pre> <p>Now, i want to access the elements from index 4 to the end:</p> <pre><c...
<p>The <code>[:-1]</code> removes the last element. Instead of</p> <pre><code>a[3:-1] </code></pre> <p>write</p> <pre><code>a[3:] </code></pre> <p>You can read up on Python slicing notation here: <a href="https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation">Explain Python&#39;s slice no...
python|vector|numpy|indexing
63
366,701
13,659,881
Count by unique pair of columns in pandas
<p>I'm trying to figure out how to count by number of rows per unique pair of columns (ip, useragent), e.g.</p> <pre><code>d = pd.DataFrame({'ip': ['192.168.0.1', '192.168.0.1', '192.168.0.1', '192.168.0.2'], 'useragent': ['a', 'a', 'b', 'b']}) ip useragent 0 192.168.0.1 a 1 192.168.0.1 ...
<p>If you use groupby, you will get what you want. </p> <pre><code>d.groupby(['ip', 'useragent']).size() </code></pre> <p>produces:</p> <pre><code>ip useragent 192.168.0.1 a 2 b 1 192.168.0.2 b 1 </code></pre>
python|pandas
61
366,702
29,773,480
Unstack a MultiIndex pandas DataFrame counter-clockwise instead of clockwise
<p>I have a multiindex pandas DataFrame that looks like this: </p> <pre><code> Number of Vulnerabilities Name Severity moderate 2167 Person 1 high 1421 critical 2464 moderate 5841 Person 2 high 3687 critical 10267 </code></p...
<p>You could reorder your columns.</p> <pre><code>df = df.unstack('Severity') # This is your current dataframe df = df['Number of Vulnerabilities'][['moderate', 'high', 'critical']] # reoder df.plot(kind='barh', stacked=True) #plot </code></pre>
python|pandas|matplotlib
1
366,703
29,727,468
Grouping date index in pandas
<p>I have a dataframe looks like this:</p> <pre><code> In [101]: import pandas as pd df = pd.DataFrame( {'date':['2014-06-30','2014-06-30','2014-06-29','2014-06-29','2014-06-29'], 'value':[1,2,5,5,4]}) df.set_index('date') Out[101]: value date 2014-06-30 1 2014-06-30 2 2014-06-29 5 2014-06-29 5 201...
<p><code>df.set_index('date')</code> needs to assigned to <code>df</code> and you coule use <code>.loc</code></p> <pre><code>df = pd.DataFrame( {'date':['2014-06-30','2014-06-30','2014-06-29','2014-06-29','2014-06-29'], 'value':[1,2,5,5,4]}) df = df.set_index('date') df value date 2014-06-30 1 2014-0...
python|pandas
0
366,704
29,644,721
PyOpenNI Depth Generator refresh
<p>I am capturing depth images from the Asus Xtion Live Pro using <a href="https://github.com/jmendeth/PyOpenNI" rel="nofollow">PyOpenNI</a>. Here's a short example of code:</p> <pre><code>from openni import * import numpy as np import cv2 import time context = Context() context.init() depth = DepthGenerator() depth...
<p>I found the solution! You have to call:</p> <pre><code>context.wait_any_update_all() context.wait_and_update_all() context.wait_one_update_all(Generator) </code></pre>
python|numpy|openni
0
366,705
29,519,050
Composite Index updates for Numpy Matrices
<p>I am trying to update a set of particular rows and columns of a numpy matrix . Here is an example:</p> <pre><code>import numpy as np A=np.zeros((8,8)) rows=[0, 1, 5] columns=[2, 3] #(What I am trying to achieve) The following does not update A A[rows][:,columns]+=1 #while this just does for i in rows: A[i][colu...
<p><code>rows</code> needs to be a 'column' vector, e.g.</p> <pre><code>rows=[[0],[1],[5]] cols=[2,3] A[rows,cols]+=1 </code></pre> <p>Sometimes a 2 stage indexing works, <code>A[rows][:,cols]</code>, but not always. In particular it doesn't in this case where <code>rows</code> is not a slice. <code>A[rows]</code> ...
python|numpy|matrix
4
366,706
29,516,616
formatting inconsistent date data with pandas
<p>I'm wondering how I might approach the problem of inconsistent data formats with pandas. Initially I used regular expression to extract a date from a large data set of urls. That worked great however there is an inconsistent date format among the extracted dates:</p> <pre><code>dates 20140609 20140624 20140404 3/18...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html#pandas.to_datetime" rel="nofollow"><code>to_datetime</code></a> it seems man/woman enough to handle your inconsistent formatting:</p> <pre><code>In [77]: df['dates'] = pd.to_datetime(df['dates']) df.info() &lt;class 'pandas....
python|datetime|pandas
2
366,707
29,504,938
Get (row,col) indices of max value in dataframe
<p>I have a data frame that looks something like this.</p> <pre><code>import pandas as pd data = [[5, 7, 10], [7, 20, 4,], [8, 1, 6,]] cities = ['Boston', 'Phoenix', 'New York'] df = pd.DataFrame(data, columns=cities, index=cities) </code></pre> <p>Output:</p> <pre><code> Boston Phoenix New York Boston ...
<p>Use unstack() and extract the top MultiIndex as a tuple using idxmax()</p> <pre><code>import pandas as pd data = [[5, 7, 10], [7, 20, 4,], [8, 1, 6,]] cities = ['Boston', 'Phoenix', 'New York'] df = pd.DataFrame(data, columns=cities, index=cities) print df.unstack().idxmax() </code></pre> <p>returns:</p> <pre><c...
python|numpy|indexing|max|dataframe
2
366,708
29,548,179
Time Series Plot Python
<p>I am using pandas and I want to make a time series plot. I have this dataframe, and I want to plot the date on the x-axis with the number of units on the y-axis. I am assuming I need to convert my date object to a datetime before I can make this plot. </p> <pre><code>df1_99.dtypes date object store_nb...
<p>As your dates are strings you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html#pandas.to_datetime" rel="nofollow noreferrer"><code>to_datetime</code></a> to convert to datetime objects:</p> <pre><code>In [4]: df['date'] = pd.to_datetime(df['date']) df.info() &lt;class ...
python|pandas|plot|time-series
0
366,709
29,434,533
Edge detection for image stored in matrix
<p>I represent images in the form of 2-D arrays. I have this picture:</p> <p><img src="https://i.stack.imgur.com/jBD9j.png" alt="original"></p> <p>How can I get the pixels that are directly on the boundaries of the gray region and colorize them?</p> <p><img src="https://i.stack.imgur.com/UdWJO.png" alt="colorized">...
<p>The following should hopefully be okay for your needs (or at least help). The idea is to split into the various regions using logical checks based on threshold values. The edge between these regions can then be detected using numpy roll to shift pixels in x and y and comparing to see if we are at an edge,</p> <pre>...
python|algorithm|numpy|edge-detection
9
366,710
29,638,692
delete string in a pandas dataframe
<p>I have a </p> <pre><code>df = pandasdataframe with data. </code></pre> <p>I have a second pandas-dataframe (called df_outlier) with only some keys (that obviously also exist in df) and I want to remove them from df.</p> <pre><code>df_outlier </code></pre> <p>I was looking for something like the following functi...
<p>To filter a df using multiple values from another df we can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html#pandas.Series.isin" rel="nofollow"><code>isin</code></a>, this will return a boolean mask for the rows where the values exist in the passed in list/Series. In order t...
python|pandas
1
366,711
29,629,254
numpy structured array no shape information?
<p>Why is the shape of a single row numpy structured array not defined ( '()') and whats the common "workaround"?</p> <pre><code>import io fileWrapper = io.StringIO("-0.09469 0.032987 0.061009 0.0588") a =np.loadtxt(fileWrapper,dtype=np.dtype([('min', (float,2) ), ('max',(float,2) )]), delimiter= " ", comments="#");...
<p><em>Short answer</em>: Add the argument <code>ndmin=1</code> to the <code>loadtxt</code> call.</p> <p><em>Long answer</em>:</p> <p>The shape is <code>()</code> for the same reason that reading a single floating point value with <code>loadtxt</code> returns an array with shape <code>()</code>:</p> <pre><code>In [4...
python-3.x|numpy
3
366,712
29,696,644
Find the second closest index to value
<p>I am using</p> <pre><code>index = (np.abs(array - value)).argmin() </code></pre> <p>to find the index in an array with the smallest absolute difference to a value.</p> <p>However, is there a nice clean way such as this for finding the <em>second</em> closest index to the value?</p>
<p>I think this works</p> <pre><code>a = np.linspace(0,10,30) array([ 0. , 0.34482759, 0.68965517, 1.03448276, 1.37931034, 1.72413793, 2.06896552, 2.4137931 , 2.75862069, 3.10344828, 3.44827586, 3.79310345, 4.13793103, 4.48275862, 4.82758621, 5.17241379, ...
python|numpy
14
366,713
29,459,186
building class that inherits pandas DataFrame
<p>I am trying to write a class that inherits pandas' <code>DataFrame</code> class for some custom data that I am working on. </p> <pre><code>class EquityDataFrame(DataFrame): def __init__(self, *args, **kwargs): DataFrame.__init__(self, *args, **kwargs) def myfunc1(self,...) ... # does someth...
<p>After looking for 6 years, pylint gave me the answer :<br /> <code>[W0223(abstract-method), CustomDataFrame] Method '_constructor_expanddim' is abstract in class 'DataFrame' but is not overridden</code></p> <p>And indeed implementing</p> <pre><code>@property def _constructor_expanddim(self) -&gt; Type[&quot;CustomDa...
python-3.x|pandas
2
366,714
29,724,553
Add raster image to HDF5 file using h5py
<p>I apologize if this is sort of a newbie question, but I am fairly new to Python and HDF5. I am using h5py, numpy, and Python 2.7. I have data from various files that need to be imported into one HDF5 file. The data from each file is to be stored in a different group. Each of these groups needs to contain 1) the ...
<p>There is nothing special about images in HDF5. The <a href="http://support.hdfgroup.org/HDF5/Tutor/h5image.html" rel="nofollow noreferrer">link</a> you provided is for the high level library bindings. You can just as easily use the <a href="http://support.hdfgroup.org/HDF5/doc/ADGuide/ImageSpec.html" rel="nofollow n...
python|numpy|hdf5|raster|h5py
8
366,715
62,150,347
How do I select rows where I x% of the columns have NaN values in pandas?
<p>I have a pandas df with floats and NaNs.<br> How do I select rows where >1000 columns have Nan? </p> <p>I have tried </p> <pre><code>df[(df == NaN).sum(axis=1)&gt;1000]) </code></pre> <p>but get:</p> <pre><code>NameError: name 'NaN' is not defined </code></pre> <p>Thanks</p>
<p>Please Try</p> <pre><code> df[(df.isna()).sum(axis=1)&gt;1000] </code></pre>
pandas
1
366,716
62,242,328
geopandas rasterize shpefile
<p>I am looking for the very simplest way to rasterise a shpfile in geopandas - the equivalent to arcpy PolygonToRaster_conversion() which does things in one line.</p> <p>I have found some relatively involved methods eg <a href="https://snorfalorpagus.net/blog/2014/11/09/masking-rasterio-layers-with-vector-features/"...
<p>Are you trying to rasterize a set of polygons with unique values in one step? If so, you want to <a href="https://rasterio.readthedocs.io/en/latest/topics/features.html" rel="nofollow noreferrer">rasterize</a> using that unique value for each polygon, but beware that the last polygon rasterized to a given pixel wil...
geopandas|rasterizing|rasterio
1
366,717
62,359,875
Keep same color for each label in different pie charts
<p>I'm having trouble keeping the same color for every label from one pie chart to another. As you can see in the image below, Matplotlib inverts the colors in the 2nd pie chart.I would like to keep red for the 'Frogs' label and green for the 'Hogs' label. I also tried to add the <code>label</code> parameter but then ...
<p>You can define a color dictionary and then use this mapping to assign the <code>colors</code> while plotting. This will keep the color scheme consistent across all the subplots.</p> <pre><code>colors={'Frogs':'red', 'Hogs':'green'} df1['a'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[0...
python|pandas|matplotlib
9
366,718
62,381,426
How to Upload a File Using Pandas in Python
<p>I'm having a problem uploading a file ( the file is called "kickstarter1.csv" it is in the image that I attached) using Pandas in python. In the bottom of the picture I attached, it is saying that the file does not exist. I found out a way to view the full path of my file which is located at the bottom of the finde...
<p>provide the complete path of your CSV file while reading it through pandas as</p> <p><code>name_you_want = pd.read_csv('path/file_name.csv') </code></p> <p>or go to the specific folder using cd command on notebook and then read the CSV file.</p>
python|pandas|csv|import
1
366,719
62,072,806
Python:Group By Multiple Column Pandas
<p>I'm trying to group by a flattened data such as 2 columns group as list &amp; the third one should be the sum of rows of that column .</p> <p>Suppose data frame looks like </p> <pre><code>ColA ColB ColC ColD A Hi Hello 2 A There You 4 B Okay Tap 4 B...
<p>IIUC, try <code>groupby</code> with <code>agg</code> and a dictionary defining how to aggregate the columns:</p> <pre><code>df.groupby('ColA').agg({'ColB':list, 'ColC':list, 'ColD':'sum'}) </code></pre> <p>Output:</p> <pre><code> ColB ColC ColD ColA A [Hi...
python|pandas|dataframe|pandas-groupby
1
366,720
62,090,716
Pandas: use groupby to sum while aggregating certain values
<p>I have the following pandas dataframe:</p> <pre class="lang-py prettyprint-override"><code> Pasture Surface Farm 01 Sown 1 2 01 Sown 2 3 01 Natural 3 01 Hay 5 02 Sown 7 </code></pre> <p>I'd like to group over the farm, in a way that...
<p>I would do:</p> <pre><code>sown_or_not = np.where(df.Pasture.str.contains('Sown'), 'Sown', 'Not Sown') df.groupby(['Farm', sown_or_not]).Surface.sum() </code></pre> <p>Output:</p> <pre><code>Farm 1 Not Sown 8 Sown 5 2 Sown 7 Name: Surface, dtype: int64 </code></pre>
python|pandas|pandas-groupby
0
366,721
62,371,861
-= works different in numpy?
<p>When I use:</p> <pre><code>f = f - df </code></pre> <p>everything works. Hence:</p> <pre><code>f-=df </code></pre> <p>results in this error:</p> <pre><code>UFuncTypeError: Cannot cast ufunc 'subtract' output from dtype('float64') to dtype('int64') with casting rule 'same_kind' </code></pre> <p>Does the -= oper...
<p>I assume this is what is happening here:</p> <p>-= is an inplace operation for the mutable object <code>f</code>. The inplace operation does not work in this case, because it would change the datatype of <code>f</code>.</p>
python|numpy
1
366,722
62,379,476
Numpy drop duplicate rows without considering the place of row elements
<p>I have come across many questions on removing duplicate rows but couldn't find an answer to my specific case. I have a 2D numpy array. I want to remove <em>duplicate</em> rows irrespective of the placement of elements in the row. And I want to keep the first duplicate too. Here's a simple reproducible example.</p> ...
<p>This might help : sort the array, and pull out the unique rows</p> <pre><code>np.unique(np.sort(arr),axis=0) </code></pre>
python|arrays|numpy
2
366,723
62,159,812
TensorFlow: Converting SavedModel.pb file to .tflite using Tensorflow 2.2.0
<hr /> <p>OS: Windows 10</p> <p>Tensorflow Version: 2.2.0</p> <p>Model Type: SavedModel (.pb)</p> <p>Desired Model Type: Tensorflow Lite (.tflite)</p> <hr /> <p>I have been going in endless circles trying to find a python script or a command line function to convert a .pb file to .tflite. I have tried using the tflite_...
<p>You can try something like below with <code>TF2.2</code>.</p> <pre><code>import tensorflow as tf graph_def_file = "./saved_model.pb" tflite_file = 'mytflite.tflite' input_arrays = ["input"]. # you need to change it based on your model output_arrays = ["output"] # you need to change it based on your model print("{...
python|tensorflow|tensorflow-lite
1
366,724
62,324,821
Dropping ID of multiindex dataframe if a specific column only includes NaAs for that ID
<p>I have a mulitindex dataframe looking somethin like that (but with over 20k rows and around 100 columns):</p> <pre><code> x1 x2 x3 Time ID 1 1 1 2 NaN 2 1 1 2 3 1 2 1 2 NaN 2 2 1 2 NaN </code></pre> <p>I'd like to drop all IDs whos' columns x3 only contain NaNs but kee...
<p>You want <code>any</code> on <code>groupby</code>:</p> <pre><code>df[df.x3.notnull().groupby('ID').transform('any')] </code></pre> <p>Output:</p> <pre><code> x1 x2 x3 Time ID 1 1 1 2 NaN 2 1 1 2 3.0 </code></pre>
python|pandas|dataframe|nan|multi-index
1
366,725
62,336,669
Combining Pandas Data Frame Rows and Preserving Data in Separate Columns
<p>I am attempting to extract data from a Google Spreadsheet that is formatted to look like a calendar in order to reformat the data to be batch-uploaded to an information management system we use at work. The final CSV has to have very specific formatting, and I am one step away from a final product.</p> <p>My curren...
<p>Try:</p> <pre><code>df.groupby((df['description'] != df['description'].shift()).cumsum()).first() </code></pre> <p>Output:</p> <pre><code> description event_type start_date end_date description 1 ...
python|python-3.x|pandas|dataframe
0
366,726
62,169,725
Building CNN + LSTM in Keras for a regression problem. What are proper shapes?
<p>I am working on a regression problem where I feed a set of spectograms to CNN + LSTM - architecture in keras. My data is shaped as <code>(n_samples, width, height, n_channels)</code>. The question I have how to properly connect the CNN to the LSTM layer. The data needs to be reshaped in some way when the convolution...
<p>One possible solution is setting the LSTM input to be of shape <code>(num_pixels, cnn_features)</code>. In your particular case, having a cnn with 32 filters, the LSTM would receive <code>(256*256, 32)</code></p> <pre><code>cnn_features = 32 inp = tf.keras.layers.Input(shape=(256, 256, 3)) x = tf.keras.layers.Conv...
python|tensorflow|keras|deep-learning|lstm
1
366,727
62,329,948
Plotly Dash: How to display a calculated value from a data frame created from a file upload?
<p>I have the following data in a <code>Pandas</code> data frame:</p> <pre><code> df = pd.DataFrame({'Make':['Mercedes', 'BMW', 'Mercedes', 'Mercedes', 'Chrysler', 'Chrysler', 'Chrysler', 'Chrysler', 'BMW', 'Chrysler', 'BMW', 'Mercedes', 'BMW', 'Mercedes'], 'Dimension':['Styling', 'Stylin...
<p>You can create a new component (such as an <code>html.Div()</code>, an <code>html.H1()</code>, an <code>html.P()</code> etc.) and then include in the <code>children</code> property both the text and the numeric value converted to string, such as</p> <pre><code>html.Div(children=['The average Styling score is: ' + s...
python|pandas|plotly|plotly-dash
2
366,728
62,244,493
Parse list and create DataFrame
<p>I have been given a list called data which has the following content</p> <pre><code>data=[b'Name,Age,Occupation,Salary\r\nRam,37,Plumber,1769\r\nMohan,49,Elecrician,3974\r\nRahim,39,Teacher,4559\r\n'] </code></pre> <p>I wanted to have a pandas dataframe which looks like the link <a href="https://i.stack.imgur.com/...
<p>You can try this:</p> <pre><code>data=[b'Name,Age,Occupation,Salary\r\nRam,37,Plumber,1769\r\nMohan,49,Elecrician,3974\r\nRahim,39,Teacher,4559\r\n'] processed_data = [x.split(',') for x in data[0].decode().replace('\r', '').strip().split('\n')] df = pd.DataFrame(columns=processed_data[0], data=processed_data[1:])...
pandas|dataframe
1
366,729
62,172,177
Create a new dataframe that list of keywords with sum of their respective value
<p>So here is the issue : I have a dataframe that contains a list of keywords. I have a bigger dataframe with commentaries that contain those keywords and values.</p> <p>My goal is to look into the bigger dataframe with the keywords of the first dataframe and sum the respective value in each line creating a new datafr...
<p>Here you go:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd #Creating dataframe d = {'col1':['1d1 a','b xa2','mx1 b','b x12','c xas','d 123','xas c','a vx3','z mp','c xg'] , 'col2': [1,2,3,4,5,6,7,8,9,10]} df = pd.DataFrame(data=d) keywords = {'col1':['a','b','c']} letters = keywords['col...
python|pandas|dataframe
1
366,730
62,261,148
keep multiplying all integers in a list in itself till reach one integer
<p>I am trying to multiply all elements in a list in itself till i get one integer.</p> <p>x = 1234 to be 1x2x3x4=24, then 2x4=8</p> <p>i tried numpy.prod but for some reason it works only once.</p> <p>here is my code:</p> <pre><code>import numpy as np def persistence(p): numbers = list(map(int, list(p))) ...
<p>That is a wonderful problem to introduce someone in the world of recursion. Here is how the recursive solution would look like:</p> <pre><code>def rec_prod(n): s = str(n) while len(s) != 1: n = 1 for i in s: n *= int(i) return rec_prod(n) return n res = rec_prod(1234) print(res) # -&gt; 8...
python|numpy
1
366,731
62,288,066
Python Pandas: how do I fill none empty rows with its corresponding column names?
<p>Here's the original df:</p> <pre><code>A B C 32 4 2 2 9 2 2 6 </code></pre> <p>I want to fill in cells that have data with the column names.The output will look like this:</p> <pre><code>A B C A C B A A C A B </code></pre> <p>Thanks RJ</p>
<p>Another way is <code>np.where</code> and would be very fast as well:</p> <pre><code>out = df.copy() out[:] = np.where(df.notna(),df.columns,np.nan) </code></pre> <hr> <pre><code>print(out) A B C 0 A NaN C 1 NaN B NaN 2 A NaN NaN 3 A NaN C 4 A B NaN </code></pre>
python|pandas
3
366,732
62,207,457
pandas use resample.sum I need to convert the result to the format I want?
<p>data</p> <pre><code> [{"content": "11", "title": "刘德华", "info": "2020-01-13", "time": 1578877014}, {"content": "22", "title": "刘德", "info": "2020-01-24", "time": 1579877014}, {"content": "33", "title": "apple", "info": "2020-02-28", "time": 1582877014}, {"conten...
<pre><code>cdata = pd.to_numeric(self.s.str.get(field), errors='coerce').resample('1y').sum() cdata = cdata.to_json(orient records) </code></pre> <p>maybe.. i guess</p> <p>or maybe </p> <pre><code> cdata.to_dict(orient="rows") </code></pre>
python|python-3.x|pandas
1
366,733
62,252,368
Drop rows in pandas where all values are the same
<p>I want to drop rows where all values are the same. But, I want solution that can apply to 1,2,3,4...n columns.</p> <pre><code>df = pd.DataFrame({"Col1":[1,4,2,5,1,4], "Col2":[4,5,2,2,3,4], "Col3":[5,1,2,5,1,4], "Col4":[3,1,2,4,2,4]}) print(df) Col1 Col2 C...
<h3><code>nunique</code></h3> <pre><code>df[df.nunique(axis=1) &gt; 1] Col1 Col2 Col3 Col4 0 1 4 5 3 1 4 5 1 1 3 5 2 5 4 4 1 3 1 2 </code></pre> <hr> <p><code>nunique(axis=1)</code> tells you the number of unique values in a row:</p> <pre><code>...
python|pandas
3
366,734
62,306,438
Low-latecy response with Ray on large(isch) dataset
<h2>TL;DR</h2> <p>What's the fasted way to get near-zero loading time for a pandas dataset I have in memory, using ray?</p> <h2>Background</h2> <p>I'm making an application which uses semi-large datasets (pandas dataframes between 100MB to 700MB) and are trying to reduce each query time. For a lot of my queries the ...
<p>After talking to Simon on Slack we found the culprit:</p> <blockquote> <p>simon-mo: aha yes objects/strings are not zero copy. categorical or fixed length string works. for fixed length you can try convert them to np.array first</p> </blockquote> <p>Experimenting with this (categorical values, fixed length strin...
python|pandas|parquet|pyarrow|ray
1
366,735
62,359,704
Error: No axis named 1 for object type <class 'pandas.core.series.Series'> in python forloop on DataFrame
<p>I have a dataframe x:</p> <pre><code> T 0 1.0 1 2.0 2 NaN 3 4.0 4 5.0 5 6.0 6 7.0 </code></pre> <p>I want to multiply 2 to cummax if value is not NaN</p> <p>Code written:</p> <pre><code>for i in range(len(x)): print(i) if math.isnan(x["T"].iloc[i]): continue else: x[...
<p><code>cummax</code> return a <strong>series</strong>, but you need just the last value of this series:</p> <pre><code>x["T"].iloc[i] = x["T"].iloc[:i+1].cummax().iloc[-1] * 2 </code></pre> <p>or simply less convoluted:</p> <pre><code>x["T"].iloc[i] = x["T"].iloc[:i+1].max() * 2 </code></pre>
python|numpy|loops|dataframe
1
366,736
62,313,485
Multi Dimension Y_train on Keras
<p>i have 2 corpus for x_train and y_train, and after some treatment like this :</p> <pre><code>input_sequences = [] labels = [] indexCA = 0 for line in corpusMSA: lineCA = corpusCA[indexCA].split() # Save CA Line token_list = tokenizer.texts_to_sequences([line])[0] # Tokenize line for i in range(1, len(...
<p><code>y_train</code> before calling <code>to_categorical</code> seems to be a vector already so you don't need to use <code>to_categorical</code> however, if that vector contains more than one class in the case of mutlilabel classification then you need to use <code>to_categorical</code> then use <code>np.sum(axis=1...
python|tensorflow|keras|recurrent-neural-network|multiclass-classification
1
366,737
62,356,917
Pandas pivot table with column as dictionary
<p>I have a dataframe which looks like this. Only <code>order</code> is unique.</p> <pre><code>vendor order order_class time 33 33 42 22/12/2018 33 39 189 25/12/2018 35 197 91 19/01/2019 35 22 189 18/12/2018 35 11 189 30/11/2018 </cod...
<p>An alternative approach using <code>groupby</code>, <code>agg</code> and <code>zip</code>:</p> <pre><code>d1 = df.groupby(['vendor', 'order_class']).agg(list).reset_index(level=1) d2 = d1.apply(lambda s: {s['order_class']: list(zip(s['order'], s['time']))}, axis=1) d2 = d2.groupby(level=0).agg(lambda s: {k:v for d ...
pandas|dataframe|dictionary|pivot
3
366,738
62,165,561
import tensorflow error in windows server 2016 (DLL load failed importing _pywrap_tensorflow_internal)
<p>I want to run my tensorflow python program in Windows servre 2016 <em>(X 5650 x64 processor , Dell Power Edge 710)</em> The same environment works on local pc but showing error in server device.</p> <p><strong>ERROR :</strong></p> <blockquote> <p>Traceback (most recent call last): File "C:\Users\Administrato...
<p>After some more research i found that.. <strong>Intel X 5650 x64 processor</strong> does not support <strong>AVX instruction</strong> which is necessary for tensor-flow. So, it this happens one has to check if his/her CPU support AVX instructions or not.</p> <p>In most of older CPUs doesn't support this AVX instruc...
python|python-3.x|tensorflow|tensorflow2.0|windows-server-2016
1
366,739
62,434,037
Python, class dataset, how to concatenate images with their respective labels in pytorch
<p>I am new to PyTorch, and in the last couple of days I have been struggling with the class Dataset that lets you build your custom dataset.</p> <p>I am working with this dataset (<a href="https://www.kaggle.com/ianmoone0617/flower-goggle-tpu-classification/kernels" rel="nofollow noreferrer">https://www.kaggle.com/ia...
<p>Seems like you're nearly there. There are many ways to deal with this. For example, you could read both csv files during initialization to build a dictionary which maps the label string in the <code>flowers_idx.csv</code> to the label index specified in <code>flowers_label.csv</code>.</p> <pre><code>import os impor...
python|dataset|pytorch|torch|torchvision
0
366,740
62,265,056
Intersection of rows of a Dataframe based on the value in a column in the dataframe
<p>I have a df as shown below. I am trying to find the intersection of rows based on the value of the host column.</p> <pre><code>host values test ['A','B','C','D'] test ['D','E','B','F'] prod ['1','2','A','D','E'] prod [] prod ['2'] </code></pre> <p>the expected output is intersection of the a row...
<p>Not sure of the structure of expected result, but you could create a column per group of host with <code>shift</code>. then use <code>apply</code> where this new column is <code>notna</code> and do intersection of <code>set</code>s.</p> <pre><code>df['val_shift'] = df.groupby('host')['values'].shift() df['intersect...
python|python-3.x|pandas|dataframe|intersection
1
366,741
62,365,875
How do I .apply or .replace multiple columns at once in pandas?
<p>The code below works..</p> <p><code>df['Forecast'] = df['Forecast'].apply(lambda x: '0' if x == '' else x)</code></p> <p><code>df['Yield'] = df['Yield'].apply(lambda x: '0' if x == '' else x)</code></p> <p>but when I try to do together, it doesn't work</p> <p><code>to_change = ['Forecast', 'Yield']</code></p> <...
<p>What about using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer">pandas.DataFrame.replace</a> ?</p> <pre><code>to_change = ['Forecast', 'Yield'] df[to_change] = df[to_change].replace(to_replace='', value='0') # or df[to_chan...
python|pandas
1
366,742
62,286,596
How to log custom Pytorch model with Mlflow?
<p>I have been using Presumm <a href="https://github.com/nlpyang/PreSumm" rel="nofollow noreferrer">https://github.com/nlpyang/PreSumm</a> for text summarization.</p> <p>However, in <code>src/train_abstractive.py</code>, the model learner <code>trainer</code> is not a <code>torch.nn.Module</code>. However, the input <...
<p>After trainer runs, you should log the <code>AbsSummarizer</code>, which should be populated with the updated weights that correspond to the trained model.</p>
pytorch|mlflow
0
366,743
62,098,301
Ordering Timestamps for ARIMA model predicion
<p><strong>Info:</strong></p> <p>I am trying to predict the price of Bitcoin,as a test and to make it easier, 1 day after my most current datetime in my data. So t = 05/27/2020, t + 1 = 05/28/2020.</p> <p>So I loaded my data:</p> <pre><code>x = pd.read_csv('btcdata.csv', header=0, parse_dates=['Date'], index_col=0) ...
<p><code>ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g. forecasting.</code> means that ARIMA doesn't understand the format of your data. </p> <p>This should convert everything to DatetimeIndex with frequency as days.</p> <pre><code>x.index...
python|pandas|arima
2
366,744
62,219,558
Trouble with Python Pandas Merge
<p>I am merging two datasets:</p> <p><code>th_users_clean</code> has 12,000 rows. <code>th</code> has 207,917 rows.</p> <p>I have performed several merge types (inner, left, etc.) but can only seem to maintain 207,917 rows. I really want the information from <code>th</code> to be added on to <code>th_users_clean</cod...
<p>You want to concatenate data-frames, not merge them. Concatenating is like appending to the end.</p> <pre><code>concat = pandas.concat([th, th_users_clean]) </code></pre> <p>Output:</p> <pre><code> time_stamp user_id visited visits_7_days adopted_users creation_time name 0 2014-04-22 03:53...
python|pandas|dataframe
1
366,745
62,140,761
How to create a seperate dataframe of rows that contain NaN with pandas
<p>Is it possible to create a new dataFrame using pandas that contains any row that has NaN in any column from an existing datafram to be reviewed by a person?</p> <p>I'm able to get rows that contain NaN in a specific column with: <code>df_nan = df[pd.isna(df["sales_person"])]</code></p> <p>but is there a way to...
<p>Since you didn't include your data, I created some as an example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np X = np.random.RandomState(1).rand(10, 5) X[X &lt; 0.1] = np.nan df = pd.DataFrame.from_records(X) print(df) # 0 1 2 3 ...
python|pandas|dataframe|data-science
3
366,746
62,242,330
Error: When subclassing the `Model` class, you should implement a `call` method. on tensorflow custom model
<p>I am trying to train my custom model on Cifar 10 dataset. My model's code is below: -</p> <pre><code>class cifar10Model(keras.Model): def __init__(self): super(cifar10Model, self).__init__() self.conv1 = keras.layers.Conv2D(32, 3, activation='relu', input_shape=(32, 32, 3)) self.pool1 = keras.layers....
<p>The problem is with indentation. You've defined <code>call</code> method inside <code>__init__</code>. Try defining it outside the <code>__init__</code> method as follows:</p> <pre><code>class cifar10Model(keras.Model): def __init__(self): super(cifar10Model, self).__init__() self.conv1 = keras.layers.Con...
python|tensorflow|keras|deep-learning
10
366,747
62,285,475
Why am I having this error? TypeError: Failed to convert object of type <class 'tensorflow.python.keras.losses.BinaryCrossentropy'> to Tensor
<p>I'm practicing Dense Neural Network on Google Colab and had this error when doing model.fit. </p> <p>This is the whole code:</p> <p>I imported my data from Google drive and was able to passed in the data to panda.</p> <pre><code>import functools import numpy as np import pandas as pd import tensorflow as tf from...
<p>Nevermind. I found a solution.</p> <p>I just change the loss function on model.compile</p> <pre><code>model.compile(optimizer='adam', loss = tf.keras.losses.binary_crossentropy, metrics=['accuracy']) </code></pre>
python|pandas|tensorflow|keras|deep-learning
11
366,748
62,398,206
How to plot variables of each groupby group
<p>I have a DataFrame with colnames = ['cuit', 'nivel_0', 'nivel_1', 'nivel_2']). The 'nivel_...' columns are differente levels of aggregation for different types of industries. Such as: Durable Manufacturing (nivel_2) >> Computers (nivel_1) >> Laptops (nivel_0). All of them are <code>objects</code> dtypes. </p> <p>I...
<p>I think you can just do:</p> <pre><code>ax = df['nivel_2'].avlue_counts().plot.bar() # other plot/format commands </code></pre>
python|pandas|plot|group-by|bar-chart
0
366,749
62,141,848
Ndarray of lists with mix of floats and integers?
<p>I have an array of lists (corr: N-Dimensional array)</p> <pre><code>s_cluster_data Out[410]: array([[ 0.9607611 , 0.19538569, 0. ], [ 1.03990463, 0.22274072, 0. ], [ 1.09430461, 0.22603228, 0. ], ..., [ 1.10802461, -0.54190659, 2. ], [ 0.9288097...
<pre><code>In [87]: import numpy.lib.recfunctions as rf In [88]: arr = np.array([[ 0.9607611 , 0.19538569, 0. ], ...: [ 1.03990463, 0.22274072, 0. ], ...: [ 1.09430461, 0.22603228, 0. ], ...: [ 1.10802461, -0.54190659, 2...
python|numpy
1
366,750
62,414,149
Search values from a list in dataframe cell list and add another column with results
<p>I am trying to create a column with the result of a comparison between a Dataframe cell list and a list</p> <p>I have this dataframe with list values:</p> <pre><code>df = pd.DataFrame({'A': [['KB4525236', 'KB4485447', 'KB4520724', 'KB3192137', 'KB4509091']], 'B': [['a', 'b']]}) </code></pre> <p>and a list with th...
<p>You should simply compare the 2 lists like this: Loop through the values of <code>findKBs</code> and assign them to new list if they are not in <code>df['A'][0]</code></p> <pre><code>df['C'] = [[x for x in findKBs if x not in df['A'][0]]] </code></pre> <p>Result:</p> <pre><code> ...
python|pandas
1
366,751
62,304,811
Interacting with Multiindex Pandas in Python
<p>I have the following multiindex dataframe:</p> <pre><code>df Out[44]: Attributes Adj Close ... Volume new Symbols ADANIPORTS.NS ASIANPAINT.NS AXISBANK.NS ... WIPRO.NS ZEEL.NS Date ... ...
<p>you can generate the list of columns from the columns of Close like:</p> <pre><code>df[[('New',tc) for tc in df['Close'].columns]] = df['Close'].pct_change() </code></pre> <p>with an example:</p> <pre><code># random values and similar structure np.random.seed(1) df = pd.DataFrame(np.random.random(40).reshape(-1, ...
python|python-3.x|pandas|multi-index
1
366,752
62,201,226
Logging tf.variable during custom training loop
<p>I have written a custom training loop for a TD(Lambda) in TensorFlow, and I want to create a log that stores some of the variables that are computed during each epoch.</p> <p>In numpy, I would write something like list.append(variable_that_I_want_to_save) at the end of every epoch</p> <p>But in tf eager execution ...
<p>Could something like this work for you? I have added a property to the class that it will store the log.</p> <pre><code>class Trainer: def __init__(self, model): self.model = model self.log_variable = [] def train(self, xs, ys, lambda): for x,y in zip(xs,ys): v = learn(x...
python|tensorflow|machine-learning|logging
0
366,753
62,165,220
Pandas splitting Columns and creating Columns of tuples
<p>I have a dataframe which looks as follows:</p> <pre><code># df colA colB colC rqp 129 a pot 217;345 u ghay 716 b rbba 217;345 d tary 612;811;760 a kals 716 t </code></pre> <p>The ColB (any component out of two shown) &amp...
<p>Use, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a> to split the strings of column <code>colB</code> around the delimiter <code>;</code> then using <a href="https://pandas.pydata.org/pandas-docs/stable/refe...
python|pandas|dataframe|split|tuples
2
366,754
62,059,561
How to map the values in dataframe in pandas using python
<p>have a df with values </p> <pre><code>df name marks mark 10 mark 40 tom 25 tom 20 mark 50 tom 5 tom 50 tom 25 tom 10 tom 15 </code></pre> <p>How to sum the marks of names and count how many times it took </p> <p>expected_output:</p> <pre><cod...
<p>Here is possible use aggregate by named aggregations:</p> <pre><code>df = df.groupby('name').agg(total=('marks','sum'), count=('marks','size')).reset_index() print (df) name total count 0 mark 100 3 1 tom 150 7 </code></pre> <p>Or with specify column after <code>...
python|pandas|dataframe
2
366,755
62,201,480
Object has no atribute
<p>I have this problem</p> <pre><code>AttributeError: 'DataFrame' object has no attribute 'set_value' AttributeError Traceback (most recent call last) &lt;ipython-input-176-25558b9cd48f&gt; in &lt;module&gt; 3 visitor_team = row["Visitor Team"] 4 row["HomeLastWin"] =...
<p>Expanding on my comment: looks like <code>set_value</code> is <a href="https://pandas.pydata.org/pandas-docs/version/0.24.2/reference/api/pandas.DataFrame.set_value.html" rel="nofollow noreferrer">deprecated</a>, so you need to use a different method. They suggest using <code>at</code>:</p> <pre><code>dataset.at[...
python|pandas
0
366,756
62,367,511
to divide the rows with null values in a dataframe in another dataframe
<p>I want to convert the dataframe having null values into my test set so i can train the data with no null values and predict the null values using a regression model.</p> <pre><code>for i in df1: if (df1['dependents'].iloc[i].notnull())==False: test[i]=df1[i] </code></pre> <p>so far i tried this code bu...
<p>Following Code will allow u split Null values into different Data-frame:</p> <pre><code>test = df1[df1['dependents'].isnull()] </code></pre>
python|pandas|dataframe
1
366,757
62,155,396
How to extract elements in an array with regard to an index?
<p>I have a row <code>A = [0 1 2 3 4]</code> and an index <code>I = [0 0 1 0 1]</code>. I would like to extract the elements in <code>A</code> indexed by <code>I</code>, i.e. <code>[2, 4]</code>.</p> <p><strong>My attempt:</strong></p> <pre><code>import numpy as np A = np.array([0, 1, 2, 3, 4]) index = np.array([0, 0...
<p>I think you want boolean indexing:</p> <pre><code>A[index.astype(bool)] # array([2, 4]) </code></pre>
python-3.x|numpy|subset
2
366,758
62,374,510
Why does indexing not working in pandas columns function?
<p><a href="https://i.stack.imgur.com/FyuKJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FyuKJ.png" alt="df.columns code not working."></a></p> <p>When I run this code, it seems that there is an error somewhere, but I can't find it. Thanks for the help. </p>
<p>You can use <em>np.r_</em> to concatenate ranges of column indices and use them in <em>.iloc</em>, passing e.g.<code>:</code> as the row index. For example:</p> <pre><code>df.iloc[:, np.r_[0:3, 6:10, 10:14]] </code></pre> <p>produces:</p> <pre><code> Player Span Mat HS Ave BF SR 100 50 0 ...
pandas|indexing
1
366,759
62,124,844
How to properly resize an image?
<p>I am a starter for the CNN DL. During CNN code I faced this error: </p> <blockquote> <p>Negative dimension size caused by subtracting 3 from 1 for 'conv2d_3/convolution' (op: 'Conv2D') with input shapes: [?,19,1,64], [3,3,64,64]</p> </blockquote> <p>My image data show <code>300(w)</code>, <code>855(h)</code...
<p>you have an input with the shape (19x1x64) where 64 is the number of channels. That's why your 3x3 convolution operation cannot be performed. What probably is happening:<br> <strong>- you are resizing your image in a wrong way (hence the 19x1x64 dimension as opposed to the 28x28x3 you potentially intended to achieve...
python|tensorflow|keras|conv-neural-network|convolution
0
366,760
62,440,332
how can i delete an element in numpy array and use a for loop in python and its index
<p>This is what I made and it doesn't work, I made a for loop and I use it to get the index and use it in another thing why doesn't it work or can I found another method to delete the element and use the index of it.</p> <p>Here is <a href="https://i.stack.imgur.com/m7KAJ.png" rel="nofollow noreferrer">some of my code...
<p>Your task is something like filtering of an array. You want to drop all elements <em>== 1</em>.</p> <p>Assume that the source array (<em>arr</em>) contains:</p> <pre><code>array([0, 1, 2, 3, 4, 1, 0, 3, 7, 1]) </code></pre> <p>so it contains 3 elements <em>== 1</em> (to be dropped).</p> <p>A much simpler way to ...
python|numpy|loops
1
366,761
62,205,571
pd.to_datetime doesn't work with %a format
<p>I'm having a trouble with pandas to_datetime function<br> When I call the function in this way:</p> <pre><code>import pandas as pd pd.to_datetime(['Wed', 'Thu', 'Mon', 'Tue', 'Fri'], format='%a') </code></pre> <p>I get this result:</p> <pre><code>DatetimeIndex(['1900-01-01', '1900-01-01', '1900-01-01', '1900-01-0...
<p>This is not a pandas issue but with datetime in python.</p> <p>Here is the best documentation I can find why '1900-01-01' <a href="https://docs.python.org/3/library/datetime.html#technical-detail" rel="nofollow noreferrer">Python Datetime Technical Details</a>.</p> <p>Note: </p> <blockquote> <p>For the datetime...
pandas|datetime
2
366,762
62,317,900
How to prepare the inputs in Keras implementation of Wavenet for time-series prediction
<p>In Keras implementation of Wavenet, the input shape is (None, 1). I have a time series (val(t)) in which the target is to predict the next data point given a window of past values (the window size depends on maximum dilation). The input-shape in wavenet is confusing. I have few questions about it:</p> <ol> <li>How ...
<p>you are using extreme values for dilatation rate, they don't make sense. try to reduce them using, for example, a sequence made of [1, 2, 4, 8, 16, 32]. the dilatation rates aren't a constraint on the dimension of the input passed</p> <p>your network work simply passing this input</p> <pre><code>n_filters = 32 fil...
python|tensorflow|machine-learning|keras|deep-learning
5
366,763
62,326,063
How to fill zeroes of a day with the previous day values in Pandas
<p>I have some days with complete zeroes and would like to replace them with the previous day values as shown here.</p> <p>Input</p> <pre><code> count 2020-02-01 00:00:00 12 2020-02-01 00:01:00 3 2020-02-01 00:02:00 14 2020-02-01 00:03:00 0 2020-02-01 00:04:00 22 2020-02-02 00:00:00 0 20...
<p>you can use <code>mask</code> to replace the 0s with nan, then <code>groupby</code> the time in the DatetimeIndex and <code>ffill</code>, then <code>fillna</code> with 0 to complete the time where no value before.</p> <pre><code>df_ = (df.mask(df.eq(0)) .groupby(df.index.time) .ffill() #add the pa...
python|pandas
3
366,764
62,426,183
Tensorflow 2 LSTM model doesn't learn using a Sequence
<p>I'm currently using a LSTM model to make timeserie predictions with Tensorflow 2.2.0</p> <p>I've been using a large dataset and everything works nicely. However, the dataset creation takes a lot of RAM and I wanted to use a <code>tensorflow.keras.utils.Sequence</code> to solve the issue, my problem is the following...
<p>I solved it by taking a break and looking at the code once again (and I realized it was a silly mistake): the issue of my <code>Sequence</code> comes from the samples in each batch being consecutive samples in time, whereas my compute-everything-dataset's batches where nicely shuffled.</p> <p>My <code>Sequence</code...
python|tensorflow|keras
1
366,765
62,064,023
Python Dataframe: Get alternative days based on month?
<p>I have df with column <code>salary_day</code></p> <pre><code> salary_day 0 thursday 1 friday </code></pre> <p>I'm trying to get alternative dates present for each day.</p> <p>For <code>May 2020</code>:</p> <p>thursdays in may : <code>7,14,21,28</code> ,fridays in may : <code>1,8,...
<p>I think the most clean and general way to do this is create a a help table with all the days of the specified year. And create extra columns: <code>month, day_name, day</code>.</p> <p>Then to check which <code>day_names</code> are in <code>df['salary_day</code>]`.</p> <p>After this we check if the <code>day</code>...
python|pandas|numpy|dataframe|datetime
2
366,766
62,374,345
Reduce the number of rows in a dataframe based on a condition
<p>I have a dataframe which consists of 9821 rows and one column. The values in it are listed in groups of 161 produced 61 times (161X61=9821). I need to reduce the number of rows to 9660 (161X60=9660) by replacing the first 2 values of each group of 161 into an average of those 2 values. In more simple words, in my ex...
<p>I'm not super happy with this answer but I'm putting it out there for review.</p> <pre><code>&gt;&gt;&gt; df[df.index%4 == 0] = df.groupby(df.index//4).apply(lambda s: s.iloc[:2].mean()).values &gt;&gt;&gt; df = df[:-3] &gt;&gt;&gt; df 0 0 10.5 1 11.0 2 12.0 3 13.0 4 14.5 5 15.0 6 16.0 7 17.0 8 18.5 ...
python|pandas|dataframe
1
366,767
51,508,218
How to smooth a curve with large noise which is only in certain part?
<p>I'd like to smooth a scatter plot shown below (the points are very dense), and the data is <a href="https://drive.google.com/file/d/1M7ayjUFF1JZ6KjepqcCS1L7twggo2ip3/view?usp=sharing" rel="nofollow noreferrer">here</a>. </p> <p><a href="https://i.stack.imgur.com/le4aZ.png" rel="nofollow noreferrer"><img src="https:...
<p>If we firstly isolate the trouble area there are many ways to remove it. Here is an example:</p> <pre><code>tolerance = 0.2 increased_span = 150 filter_size = 11 #find noise first_pass = medfilt(y,filter_size) diff = (yhat-first_pass)**2 first = np.argmax(diff&gt;tolerance) - increased_span last = len(y) - np.arg...
python|numpy|scipy|smoothing|data-processing
6
366,768
51,354,170
Understand memory allocation for python numpy array
<p>I'd like to wrap my head around the memory allocation behavior in python numpy array. The question is as below:</p> <p>What happen when a smaller array replace a bigger array size in terms of the memory used? Example as below:</p> <pre><code>[1] arr = np.rand.randint(1, 10, size=(2000, 3000) ... [100] arr = np.ran...
<p>The assignment at [100] creates a new array object, and assigns it to variable <code>arr</code>. If there aren't any other references to the object originally assigned to <code>arr</code> (at [1]), then that object will be available for garbage collecting. Temporarily the large and small arrays will exist in memor...
python-3.x|numpy|memory-leaks
0
366,769
51,145,916
How can I only return the first product when using pd.multiIndex.from_product()? Or a better option
<p>I am using the code below to make a new index for a dataframe.</p> <pre><code>pd.DataFrame(pd.MultiIndex.from_product([df['Key'],pd.date_range(start='20160101', end='20160301',freq='MS')],names=['key','year_month'])) </code></pre> <p>Here is the current ouput:</p> <p><code>0 (A, 2016-01-01 00:00:00) 1 (A, 2016...
<p>Try using <code>unique</code></p> <pre><code>pd.DataFrame(pd.MultiIndex.from_product([df['Key'].unique(),pd.date_range(start='20160101', end='20160301',freq='MS')],names=['key','year_month'])) </code></pre>
python|pandas|dataframe|multi-index
1
366,770
51,399,915
Can change network architecture during training in tensorflow?
<p>I want to change channel dimensions of convolution layer during training, but in testing, always keeping same dimensions. I tried to implement this in tensorflow, and i failed. If the output dimension changes during training, an error occurs because the tensor flow does not recognize the changed graph. Does not the...
<p>You cannot change the number of channels of a convolution layer on the fly as it would basically amount to having a new network with a different structure, different number of weights, etc.</p> <p>The convolution weights are represented by a matrix <code>A</code> of shape <code>(k, k, cout, cin)</code> for a convol...
tensorflow|deep-learning|conv-neural-network
1
366,771
51,457,803
Pandas data frame spread function or similar?
<p>Here's a pandas df:</p> <pre><code>df = pd.DataFrame({'First' : ['John', 'Jane', 'Mary'], 'Last' : ['Smith', 'Doe', 'Johnson'], 'Group' : ['A', 'B', 'A'], 'Measure' : [2, 11, 1]}) df Out[38]: First Last Group Measure 0 John Smith ...
<p>Using <code>pivot_table</code></p> <pre><code>df.pivot_table(index=['First','Last'],columns='Group',values='Measure',fill_value=0) Out[247]: Group A B First Last Jane Doe 0 11 John Smith 2 0 Mary Johnson 1 0 </code></pre>
python|pandas
8
366,772
51,260,136
Reinforcement Learning, how can I sample action from Gaussian distribution with action dimension space larger than one?
<p>In the code of <a href="https://github.com/dennybritz/reinforcement-learning/blob/master/PolicyGradient/Continuous%20MountainCar%20Actor%20Critic%20Solution.ipynb?short_path=6b34a0b#L150" rel="nofollow noreferrer">Actor-Critic with Gaussian</a>, </p> <pre class="lang-py prettyprint-override"><code>class PolicyEstim...
<p>To create an action vector with shape <code>(40)</code>, you need the last layer of your network to output a vector with a shape of 40. So change:</p> <pre class="lang-py prettyprint-override"><code>self.mu = tf.contrib.layers.fully_connected( inputs=tf.expand_dims(self.state, 0), nu...
tensorflow|reinforcement-learning
2
366,773
51,504,274
Replace zeros in a column with string from the row above (Python/Pandas)
<p>I would like to replace the 0 with the string from the same column, previous row. Eg: 0 under Sheffield should read Sheffield. I am working with pandas.</p> <pre><code>file = file[['Branch', 'Type' ,'total']] #replace NaN with 0 file.fillna(0).tail(6) Out[48]: Branch Type total 394 Sh...
<p>Use <code>replace</code> with the method <code>ffill</code></p> <pre><code>file_df['Branch'].replace(to_replace='0', method='ffill', inplace=True) &gt;&gt;&gt; file_df Branch Type total 394 Sheffield Sum of Resend to Branch 0 395 Sheffield Number of PV Enquiries 83 396 W...
python|pandas
2
366,774
51,382,298
Python Pandas: Parse Into new DateTime Column
<p>How can I parse the content of this Python <code>DataFrame</code> into a new column that contains the existing columns as one <code>datetime</code> object?</p> <p>I would like to avoid a for loop (and if possible also a lambda) for time performance reasons.</p> <pre><code>import pandas as pd df = pd.DataFrame({"ce...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with joined all columns and format by <a href="http://strftime.org/" rel="nofollow noreferrer"><code>http://strftime.org/</code></a> for improve performance:</p> <pre><c...
python|pandas|datetime
2
366,775
51,470,602
Pandas combinations of Dataframe and series
<p>I have a dataframe:</p> <pre><code>df = pd.DataFrame({ 'A': [1,2,3,4], 'B': [12,23,34,45] }) </code></pre> <p>It looks like</p> <pre><code>---------------------------- index A B 0 1 12 1 2 23 2 3 34 3 4 45 -------------...
<p>Maybe using<code>pd.concat</code> is slightly faster than <code>reindex</code></p> <pre><code>pd.concat([df]*len([0,1,2])).sort_index().assign(time=[0,1,2]*len(df)) Out[275]: A B time 0 1 12 0 0 1 12 1 0 1 12 2 1 2 23 0 1 2 23 1 1 2 23 2 2 3 34 0 2 3 34 1 2 3 ...
python|pandas|combinations
6
366,776
51,373,072
tf.optimizer update all existed weights for sparse input
<p>I'm using tf to train a LR model via FTRLOp for sparse dataset. Code snippet as follows:</p> <pre><code>feature_columns = [ tf.feature_column.categorical_column_with_hash_bucket('query_id',15), tf.feature_column.categorical_column_with_hash_bucket('ad_id',15), tf.feature_column.categorical_colu...
<p>By far, I found at least one reason. The weights are updated via the the averaged gradients of each batch, which is nice for nn. Details here <a href="https://stats.stackexchange.com/questions/266968/how-does-minibatch-gradient-descent-update-the-weights-for-each-example-in-a-bat">https://stats.stackexchange.com/que...
python|tensorflow|logistic-regression|tfrecord
0
366,777
51,483,113
Dimension of hidden layer LSTM Pytorch
<p>I was reading the implementation of <a href="https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html" rel="nofollow noreferrer">LSTM</a> in Pytorch. The code goes like this:</p> <pre><code>lstm = nn.LSTM(3, 3) # Input dim is 3, output dim is 3 inputs = [torch.randn(1, 3) for _ in range(5)] # make...
<p>Apart from the hidden state, LSTM also has cell state, C. Therefore, a tuple is passed I think. See <a href="https://pytorch.org/docs/stable/nn.html#lstmcell" rel="nofollow noreferrer">https://pytorch.org/docs/stable/nn.html#lstmcell</a>. </p> <p>If you don't pass C, it is taken to be all zeros.</p> <p>Note that t...
lstm|pytorch|recurrent-neural-network
2
366,778
51,164,356
Python: how to delete duplicates in Nx3 numpy array
<p>I have Nx3 numpy array, let say: </p> <pre><code>a=[[1,1,1],[1,2,3],...,[2,1,3],[2,2,2]] </code></pre> <p>In my case, I don't care about the position of the elements in my "sub 3D array" and I consider them as duplicates:</p> <p>[1,2,3] == [2,1,3] == [3,1,2] = ... </p> <p>I would like to delete these duplicates ...
<p>Use <code>sort</code> and <code>unique</code>:</p> <pre><code>import numpy as np a=np.array([[1,1,1],[1,2,3],[2,1,3],[2,2,2]]) np.unique(np.sort(a, axis=1), axis=0) array([[1, 1, 1], [1, 2, 3], [2, 2, 2]]) </code></pre>
python|arrays|numpy|duplicates
2
366,779
51,315,526
Python: error in plotting data created with `period_range` (pandas)
<p>I have a problem in plotting time series data, created using pandas <code>date_range</code> and <code>period_range</code>. The former works, but the latter does not. To illustrate the problem, consider the following</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt # random numb...
<p>The indexes of the two dateframes are of different type:</p> <pre><code>print(type(df_date)) # pandas.core.indexes.datetimes.DatetimeIndex print(type(df_period)) # pandas.core.indexes.period.PeriodIndex </code></pre> <p>Matplotlib does not know how to plot a <code>PeriodIndex</code>. </p> <p>You may <a href="...
python|pandas|matplotlib
4
366,780
51,146,597
CNN with Tensorflow, low accuracy on CIFAR-10 and not improving
<p>On running the first training epoch of a 3-layer convnet on CIFAR-10, I am neither able to achieve a high enough validation accuracy nor minimize the objective function.</p> <p>Specifically, the <strong>accuracy varies on the first iteration</strong>, and then <strong>settles at 8.7%</strong> for the following iter...
<p>the problem is here </p> <pre><code>h1_conv = tf.nn.conv2d(x, conv_w1 + conv_b1, strides=[1, 1, 1, 1], padding='SAME' ) </code></pre> <p>This is wrong as here you are adding bias values (conv_b1) to the filter conv_w1 but bias has to be add...
python|tensorflow|neural-network|deep-learning
1
366,781
51,247,304
Does tflearn.models.dnn.DNN automatically turn off dropout layers and batch normalization when predicting?
<p>I'm quite new to Neural Networks, which is why I've decided to use Tflearn because it is quite intuitive. However I couldn't find an answer to my question. The tflearn documentation gives the following example for letting a deep neural network predict something:</p> <pre><code>network = ... model = DNN(network) mod...
<p>You need to set <code>tflearn.is_training</code> to True or False when you are training and predicting, and tflearn will take care of the rest. Once you define your model, you can train it by:</p> <pre><code>with tf.Session() as sess: tflearn.is_training(True, session=sess) model.fit(X, Y) </code></pre> <p>an...
python|tensorflow|machine-learning|deep-learning|tflearn
0
366,782
51,255,764
Tensorflow Object Detection API run eval.py,somewhere wrong
<p>when I finish the train.I want to python eval.py to look the precision,but when restoring from the model.ckpt,the The program is stuck.It's a bug?thank u</p>
<p>give some further explanation of the error. When it stuck before it even start and what command do you use to run the eval.py</p>
api|object|tensorflow|detection
0
366,783
51,514,212
How to detect obfuscated categorical data in pandas dataframe
<p>I have dataframe that except continous column contains 'obfuscated' categorical data. A few examples how categorical variables are encoded:</p> <ul> <li>binary category: c0, c1 -> 0, 1</li> <li>3-category: c0, c1, c2 -> 0, 1/2, 1 -> 0, 0.5, 1</li> <li>4-category: c0, c1, c2, c3 -> 0, 1/3, 2/3, 1 -> 0, 0.333.., 0.66...
<p>I suggest use <a href="https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.rank.html" rel="nofollow noreferrer"><code>DataFrame.rank</code></a> with <code>method='dense'</code> for category numbers, subtract <code>1</code> and prepend <code>c</code>:</p> <blockquote> <p><strong>dense</st...
python|pandas|dataframe|categorical-data
1
366,784
51,461,970
PyTorch Tensors of Inputs and Labels in LSTM
<p>I am new to PyTorch, and I'm working on a simple project to generate text, in order to get my hands on pytorch. I am using the concept of this code and converting it to PyTorch: <a href="https://machinelearningmastery.com/text-generation-lstm-recurrent-neural-networks-python-keras/" rel="nofollow noreferrer">https:/...
<p>In PyTorch, when using the <code>CrossEntropyLoss</code>, you need to give the output labels as integers in <code>[0..n_classes-1]</code> instead of as one-hot vectors. Right now pytorch thinks you are trying to predict multiple outputs.</p>
lstm|pytorch
3
366,785
51,548,666
Statsmodels (Patsy) illegal variable name / 'Series' object is not callable Error
<p><strong>Update:</strong></p> <p><strong>The error might have been caused by the fact that there is also a variable named "Q" in my dataset which conflicts the Q function. In this case, how do I elegantly solve it?</strong> </p> <hr> <p><strong>Update: You can download my dataset <a href="https://www.dropbox.com/s...
<p>According to this link: <a href="http://patsy.readthedocs.io/en/latest/builtins-reference.html#patsy.builtins.Q" rel="nofollow noreferrer">http://patsy.readthedocs.io/en/latest/builtins-reference.html#patsy.builtins.Q</a> you can use Q("var") in the formula to get rid of the error. </p> <p>The following code should...
python|pandas|statistics|regression|statsmodels
1
366,786
51,335,371
How can I create a lstm cell with only single time step in tensorflw?
<pre><code>layer_1 = tf.layers.dense(inputs=layer_c, units=512, activation=tf.nn.tanh, name='layer1') layer_2 = tf.layers.dense(inputs=1, units=512, activation=tf.nn.tanh, name='layer2') </code></pre> <p>Here my layer_2 output is [batch_size,512]. I need to send this layer_2 output through a single lstm unit. But whe...
<p>From the <a href="https://www.tensorflow.org/api_docs/python/tf/nn/static_rnn" rel="nofollow noreferrer">documentation for <code>static_rnn</code></a>, the <code>inputs</code> argument is expecting a list:</p> <blockquote> <p><strong><code>inputs</code>: A length T list</strong> of inputs, each a Tensor of shape ...
python|tensorflow|deep-learning|lstm
1
366,787
51,355,729
Why does the Keras API require the input shape in the first layer, since it actually works well without it?
<p>I am using <code>tf.keras</code> from TensorFlow 1.9.0. It seems that everything works fine without specifying the <code>input_shape</code> in the first layer when building a <code>Sequential</code> model:</p> <pre><code>import tensorflow as tf from tensorflow import keras import numpy as np X_train = np.random.ra...
<p>I think the choice of words in the guide (emphasis mine),</p> <blockquote> <p>The model <strong>needs</strong> to know what input shape it should expect.</p> </blockquote> <p>may be a bit unfortunate and, being a guide, should not been taken as a specification.</p> <p>Keras can accept <code>input_shape</code>s ...
tensorflow|keras
3
366,788
51,546,445
pandas df: add column if doesn't exist, add values to new column from dict
<p>I am new to pandas but I'm trying to create a large dataframe where I organize information about lots of sequences by their sequence IDs (Seq_ID) and add information about the sequences to the dataframe. Currently the df looks something like this:</p> <pre><code> Seq_ID mol_type 0 4_cDNA_v ...
<p>Whenever you find yourself frequently having to lookup a value to recover a key, it is usually best to reshape that dictionary to allow you to lookup by key, which is more efficient.</p> <p>Assuming all of the values in the inner lists are unique, you can reshape your lookup dictionary using the following snippet:<...
python-3.x|pandas|dataframe
2
366,789
51,498,521
How to construct personalized permutations
<p>I want to create a set of permutations of a given list , say <code>a = np.array([0,1,2])</code>. I am aware of <code>itertools.permutations</code>, but I need something that I can personalized so my permutations follows certain rules.</p> <p>For instance such a rule could be that 1 cannot be the second element. Cre...
<p>Edit: As explained by @Mr.T, <code>itertools</code> is a C library.</p> <p>This means that calling <code>itertools.permutations</code> first, then filtering may be faster than implementing your own &quot;optimized&quot; function in python.</p> <p>Ideally, you'd implement your &quot;optimized&quot; function in C, and...
python|numpy|scipy|itertools
0
366,790
51,238,306
Importing an irregular sized text file
<p>I would like to import a text file that has 11576 rows and 7 columns into a pandas dataframe and then reshape it so that it has 229 rows and 351 columns.</p> <p>In the text file, every 34 lines or so, there are 2 whitespaces (i.e the 6th and 7 th column of that row have no values).</p> <p>I want to slice the data ...
<p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> for create <code>DataFrame</code> and then <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow noreferrer"><code>numpy.re...
python|pandas|import|text-files
1
366,791
51,306,688
Use of copy in reindex and saving the newly indexed data
<p><strong>I have the following code:</strong></p> <pre><code>dat = pd.DataFrame(np.arange(16).reshape(4,4), index = ['a', 'b', 'c', 'd'], columns = ['A', 'B', 'C', 'D']) dat.reindex(['b', 'c', 'a', 'd']) dat </code></pre> <p>However, when I view <code>dat</code>, it still has the index as <code>['a', 'b', 'c', 'd']<...
<p>You have to save the result to access it. Some functions in <code>pandas</code> take an <code>inplace=True</code> parameter but reindex does not. </p> <pre><code>dat = dat.reindex(['b', 'c', 'a', 'd']) </code></pre> <hr> <p>To understand the use of the copy parameter, compare:</p> <pre><code>dat = pd.DataFrame(...
python|pandas
1
366,792
51,527,164
Python function: return an array without additional memory allocations
<p>Suppose I want to make a function that multiplies input vector by input matrix:</p> <pre><code>def MatMul(A,b): return A.dot(b) </code></pre> <p>Now, I execute the following code:</p> <pre><code>import numpy as np A=np.array([[1,2,3],[4,5,6],[7,8,9]],dtype='float64') b=np.array([4,5,6],dtype='float64') c=np.z...
<p><code>dot</code> doesn't know or care about the <code>c</code> variable or the array that variable already holds a reference to. It'll make a new array, and <code>=</code> will bind the <code>c</code> variable to that new array, leaving the old array to be cleaned up by the memory management system.</p> <p>If you w...
python|function|numpy|pass-by-reference
3
366,793
51,431,282
Subplot function not showing all subplots
<p>I've been trying to turn my plots into functions so I can reutilize them. Now, I'm trying to graph subplots, where each subplot graphs a category's sales over time. In its loop form, it looks like this:</p> <pre><code>Categories=dfs['Category'].unique() fig, ax=plt.subplots(figsize=(18,10)) for j,i in zip(Equipos,...
<p>The string <code>'Category'</code> has 8 characters. You loop over the length of this string and hence get 8 subplots. </p> <p>I would guess that instead you want to loop over all unique categories.</p> <pre><code>for i, j in enumerate(df[cat].unique()): </code></pre>
python|pandas|matplotlib|subplot
1
366,794
51,220,843
pandas query with list variables
<p>I made a list of id's each value is is an type int </p> <pre><code>temp_id = [7922, 7018, 5650, 209, 21928, 2294, 10507, 3623] type(tempasn) list </code></pre> <hr> <p>This works:</p> <pre><code>Temp = pd.read_sql("select count(*) as count\ from "+db+"\ where ids in (792...
<p>You need a string so you should implode your array </p> <pre><code>temp_id = [7922, 7018, 5650, 209, 21928, 2294, 10507, 3623] my_string = ",".join(temp_id ) Temp = pd.read_sql("select count(*) as count\ from "+db+"\ where ids in ("+my_string+")\ order...
mysql|pandas|jupyter-notebook
1
366,795
51,327,905
How to fill in pandas data frame of unknown size
<p>I am pretty new to Python and I am trying to scrape information of multiple sites which are all of the same structure, but of different length. What I am trying to do is add my information row by row from an empty data frame, like you can do in R by simply calling the indices and R adds a row to the data frame. In p...
<p>If you are certain you got 4 columns give them a name first, <code>columns=[0,1,2,3]</code>. Then you can use <code>.loc[]</code> to append data and if you have your columns defined as integers you can use append too:</p> <pre><code>import pandas as pd df = pd.DataFrame(columns=[0,1,2,3]) df.loc[len(df)] = [1,2,3,...
python|pandas
1
366,796
51,288,635
Pandas: get string value with most occurrence in group
<p>I have the following DataFrame:</p> <pre><code>item response 1 A 1 A 1 B 2 A 2 A </code></pre> <p>I want to add a column with the most given response for an item. which should result in:</p> <pre><code>item response mostGivenResponse 1 A ...
<p>There is <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.Series.mode.html" rel="noreferrer"><code>pd.Series.mode</code></a>:</p> <pre><code>df.groupby('item').response.transform(pd.Series.mode) Out[28]: 0 A 1 A 2 A 3 C 4 C Name: response, dtype: object </code></pre>
python|pandas
10
366,797
51,298,856
Find indices of each bin using numpy
<p>I'm encountering a problem that I hope you can help me solve. </p> <p>I have a 2D numpy array which I want to divide into bins by value. Then I need to know the exact initial indices of all the numbers in each bin. </p> <p>For example, consider the matrix</p> <pre><code> [[1,2,3], [4,5,6], [7,8,9]] </code></pr...
<p>You need to leave numpy and use a loop for this - it's not capable of representing your result:</p> <pre><code>bin_in_mat = np.digitize(a, bins, right=False) bin_contents = [np.argwhere(bin_in_mat == i) for i in range(len(bins))] </code></pre> <pre><code>&gt;&gt;&gt; for b in bin_contents: ... print(repr(b))...
python|numpy|indexing|histogram
2
366,798
51,402,053
Cannot import tensorflow to python 3.5 (imports successfully in 2.7)
<p>Please help</p> <p>I am able to import tensortflow when in python 2.7 but when importing into python 3.5, it fails with: <strong>ImportError: No module named 'tensorflow'</strong>.</p> <p>the {pip show tensorflow} command shows the following:</p> <p>Name: tensorflow Version: 1.9.0 Summary: TensorFlow is an open s...
<p>You can use the following to install tensorflow:</p> <pre><code>pip3 install --upgrade tensorflow </code></pre> <p>or with anaconda:</p> <pre><code>conda create -n tensorflow pip python=3.5 activate tensorflow pip install --ignore-installed --upgrade tensorflow </code></pre> <p>Taken from <a href="https://www.t...
python|tensorflow|importerror
1
366,799
51,219,830
How to covert compressed data to initial format data on pandas
<p>I've try to get data that compressed to txt format. Here's my dataset</p> <pre><code>1 0 1 01 0 0 00 1 0 1 </code></pre> <p>Here's what I want</p> <pre><code>column_1 column_2 column_3 column_4 1 0 1 0 1 0 0 0 0 1 0 1 </code></pre>
<p>Here's one way:</p> <pre><code>pd.DataFrame(np.array(list(s.replace(' ', ''))).reshape(3,4).astype(int)) </code></pre>
python|pandas|dataframe
1