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
371,800
43,402,320
Export tensorflow weights to hdf5 file and model to keras model.json
<p>I recently found this <a href="https://github.com/transcranial/keras-js" rel="nofollow noreferrer">Project</a> which runs inference of keras model in a browser with GPU support using webgl. I have a few tensorflow project that I would like to run inference on a browser, is there a way to export tensorflow models int...
<p>If you are using Keras, you can do something like this.</p> <pre><code>model.save_weights('my_model.hdf5') </code></pre>
python|tensorflow|keras|hdf5
0
371,801
43,437,385
Information content in Python for real number dataset
<p>This question is supplementary to a <a href="https://stackoverflow.com/questions/43301878/computing-information-content-in-python">previous question</a>.</p> <p>I need to compute information content from two Python lists. These lists contain real numbers. I understand that I can use the following formula where the ...
<p>For discrete distributions, you can use the aforementioned biopython or scikit-learn's <code>sklearn.metrics.mutual_info_score</code>. However, both compute the mutual information between "symbolic" data using the formula you cited (which is intended for symbolic data). In either case, you disregard that the values ...
python|numpy|scipy|entropy|information-theory
2
371,802
43,100,441
I am trying to run Dickey-Fuller test in statsmodels in Python but getting error
<p>I am trying to run Dickey-Fuller test in statsmodels in Python but getting error P Running from python 2.7 &amp; Pandas version 0.19.2. Dataset is from Github and imported the same</p> <pre><code>enter code here from statsmodels.tsa.stattools import adfuller def test_stationarity(timeseries): print 'Resu...
<p><em>tr</em> must be a 1d array-like, as you can see <a href="http://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.adfuller.html" rel="noreferrer">here</a>. I don't know what is <em>tr</em> in your case. Assuming that you defined <em>tr</em> as the dataframe that contains the time serie's data, you shou...
python-2.7|pandas|jupyter-notebook
11
371,803
43,162,731
How to write a multiple dataframes to same sheet without duplicating the column labels
<p>I have two questions regarding writing dataframe data to a file:</p> <p>My program produces summary statistics on many grouped rows of a dataframe and save those to a StringIO buffer which writes to my output.csv file at completion. I have a feeling the pd.concat would be better suited but I couldn't get that to wo...
<p>I'd agree that concatenating the dataframes is probably a better solution. You should probably ask a question specifically for that with some sample codes/dataframes.</p> <p>For your second question you can position a dataframe in an Excel worksheet using the <code>startrow</code> and <code>startcol</code> paramete...
pandas|xlsxwriter
3
371,804
43,209,391
Numpy is calculating wrong
<p>I am using numpy like this code</p> <pre><code>>>>import numpy as np >>>a=np.arange(1,100000001).sum() >>>a 987459712</code></pre> <p>I guess the result must be some like 5000000050000000</p> <p>I noticed that until five numbers the result is ok. Does someone knows what is happened?</p> <p>regards</p>
<p>Numpy is not doing a mistake here. This phenomenon is known as <a href="https://en.wikipedia.org/wiki/Integer_overflow" rel="nofollow noreferrer">integer overflow</a>.</p> <pre><code>x = np.arange(1,100000001) print(x.sum()) # 987459712 print(x.dtype) # dtype('int32') </code></pre> <p>The 32 bit integer type use...
python|numpy
9
371,805
43,258,102
Python: unziping special files into memory and getting them into a DataFrame
<p>I'm quite stuck with a code I'm writing in Python, I'm a beginner and maybe is really easy, but I just can't see it. Any help would be appreciated. So thank you in advance :)</p> <p>Here is the problem: I have to read some special data files with an special extension .fen into a pandas DataFrame.This .fen files are...
<p>Here is the solution I finally found in case it can be helpful for anyone. It uses the tempfile library to create a temporal object in memory.</p> <pre><code>import zipfile import tempfile import numpy as np import pandas as pd def readfenxfile(Directory,File,ExtractDirectory): fenxzip = zipfile.ZipFile(Dire...
python|numpy|unzip|zip
2
371,806
43,295,601
Keras: CNN multiclass classifier
<p>After starting with the official binary classification example of Keras (see <a href="https://gist.github.com/fchollet/0830affa1f7f19fd47b06d4cf89ed44d" rel="nofollow noreferrer">here</a>), I'm implementing a multiclass classifier with Tensorflow as backend. In this example, there are two classes (dog/cat), I've no...
<p>Considering the number of classes you need to differentiate, perhaps increasing the complexity of the model, as well as using a different optimizer, could yield better results. Try using this model, which is partially based on the VGG-16 CNN architecture, but not as complex:</p> <pre><code>model = Sequential() mode...
python|tensorflow|keras|convolution
0
371,807
43,151,128
Find the highest and lowest value locations within an interval on a column?
<p>Given this pandas dataframe with two columns, 'Values' and 'Intervals'. How do I get a third column 'MinMax' indicating whether the value is a maximum or a minimum within that interval? The challenge for me is that the interval length and the distance between intervals are not fixed, therefore I post the question.</...
<pre><code>isnull = data.iloc[:, 1].isnull() minmax = data.groupby(isnull.cumsum()[~isnull])[0].agg(['idxmax', 'idxmin']) data.loc[minmax['idxmax'], 'MinMax'] = 'max' data.loc[minmax['idxmin'], 'MinMax'] = 'min' data.MinMax = data.MinMax.fillna('') print(data) 0 1 MinMax 0 1879.289 NaN 1 1...
pandas|max|grouping|min|series
2
371,808
72,388,402
Check if dataframe satisfies database table column definitions
<p>Is there a way to check if pandas dataframe satisfies definitions of table comlumns in a database? I want to do this inspection before using pd.to_sql() funcion in order to avoid errors and exceptions.</p> <p>Say for example that a table column is of VARCHAR(50) type, but one record in df has length of more than 50 ...
<p>You can use <a href="https://pydantic-docs.helpmanual.io/usage/models/" rel="nofollow noreferrer">Pydantic</a> models to parse and <a href="https://pydantic-docs.helpmanual.io/usage/validators/" rel="nofollow noreferrer">validate</a> your data before inserting in the database.</p>
python|pandas|database|sqlalchemy
0
371,809
72,319,813
How do I add a row at the end of each month that show the sum for each month?
<p>Say I have pandas dataframe with index column having dates. And another column having some values.</p> <pre><code>Date Value 2021-04-05 101 2021-04-12 200 2021-04-20 15 2021-05-21 12 2021-05-28 11 </code></pre> <p>I want to add a row at the end of each month showing the total for that month:</p> <p...
<p>You can keep the last of <code>Date</code> , then pass the <code>searchsorted</code>, and use the <code>sort_index</code></p> <pre><code>s = df.groupby(df['Date'].dt.strftime('%B %Y')).agg({'Date':'last','Value':'sum'}) index = np.searchsorted(df.Date,s.Date) s = s.drop(['Date'],axis=1).reset_index() s.index = index...
python|pandas|dataframe
0
371,810
72,432,809
Fix batch size in custom loss function (to be able to use unstack)
<p>I have created a custom loss function by subclassing from <code>keras.losses.Loss</code>. Inside the method <code>call(self, y_true, y_pred)</code> I want to unstack the tensor <code>y_true</code>, but this does not work since it is of shape <code>(None,13,13,5,25)</code>, i.e. the batch dimension is unknown. Is the...
<p>I eventually figured it out: the problem goes away and the batch size is defined inside the call method if I set <code>drop_remainder=True</code> when batching the dataset:</p> <pre><code>dataset.batch(BATCH_SIZE,drop_remainder=True) </code></pre>
python|tensorflow|keras
0
371,811
72,449,422
Is there an easy way to "unformat" exotic excel files with pandas?
<p>I'm currently tasked to build a database using existing excel files. The problem is that the files were generated in such a way that pandas won't be able to read them right just by using <code>pd.read_excel()</code>.</p> <p>Here I built an example of what I call an &quot;exotic&quot; Excel file :</p> <p><a href="htt...
<p>Try checking out this post: <a href="https://stackoverflow.com/questions/43544514/pandas-read-specific-excel-cell-value-into-a-variable">Pandas: Read specific Excel cell value into a variable</a> you can specify the Sheet and the Cells that you want to import so you only pull in specific regions rather than the whol...
python|excel|pandas
0
371,812
72,389,561
pandas multIndex from product - ignore same row comparison
<p>I have a pandas dataframe like as shown below</p> <pre><code>Company,year T123 Inc Ltd,1990 T124 PVT ltd,1991 ABC Limited,1992 ABCDE Ltd,1994 tf = pd.read_clipboard(sep=',') tf['Company_copy'] = tf['Company'] </code></pre> <p>I would like to compare each value from <code>tf['compa...
<p>You can compare both levels of <code>MultiIndex</code> for not equal, comapre first and second level:</p> <pre><code>compare = pd.MultiIndex.from_product([tf['Company'].astype(str),tf['Company_copy'].astype(str)]).to_series() compare = compare[compare.index.get_level_values(0) != compare.index.get_level_values(1)] p...
python|pandas|dataframe|numpy|multi-index
1
371,813
72,405,003
Dataframe transformation based on repeating cell values based on column values
<p>Having a dataframe like this:</p> <p><a href="https://i.stack.imgur.com/A7tGH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A7tGH.png" alt="enter image description here" /></a></p> <p>I would like to know what would be the most efficient way to transform it into this othe one:</p> <p><a href="ht...
<p><strong>IF the original index is not important for you</strong>, You could also use the <code>.melt()</code> method which has the advantage of grouping the days so you have the values for 1 day after another:</p> <pre><code>df1 = df.melt(id_vars='Time', var_name='Day', value_name='Value') </code></pre> <p>Result:</p...
python-3.x|pandas|dataframe
2
371,814
72,446,323
how to convert a list of list to dataframe keeping the grouping value of another column?
<p>I have a df with a column in which each row is a list and another column with the list name. I want to convert the elements of each list in a row into separate rows while keeping the list name in another column. example below. <a href="https://i.stack.imgur.com/Ncz8P.png" rel="nofollow noreferrer"><img src="https://...
<p>This should work</p> <p><code>df = df.explode('Data').reset_index(drop=True)</code></p>
python|dataframe|sklearn-pandas
2
371,815
72,262,608
Steps for Machine Learning in Pytorch
<p>When we define our model in <code>PyTorch</code>. We run through different <code>#epochs</code>. I want to know that in the iteration of epochs. What is the difference between the two following snippets of code in which the order is different? These two snippet versions are:</p> <ol> <li>I found over tutorials</li> ...
<p>The only difference is when the gradients are cleared. (when you call optimizer.zero_grad()) the first version zeros out the gradients after updating the weights (optimizer.step()), the second one zeroes out the gradient after updating the weights. both versions should run fine. The only difference would be the firs...
python|machine-learning|pytorch
1
371,816
72,215,049
Modify the name of the elements only if they appear in the dictionary
<p>Let it be the following Python Pandas DataFrame.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>region</th> </tr> </thead> <tbody> <tr> <td>12</td> <td>FRA</td> </tr> <tr> <td>99</td> <td>GER</td> </tr> <tr> <td>13</td> <td>ESP</td> </tr> <tr> <td>69</td> <td>UK</td> </tr> <...
<p>I think what you want is that :</p> <pre><code>df.replace({&quot;region&quot;: dictionary}) </code></pre> <p><a href="https://i.stack.imgur.com/roakx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/roakx.png" alt="enter image description here" /></a></p>
python|pandas|dataframe|dictionary
1
371,817
72,322,656
How to replace values in numpy ndarray with values from a separate list
<p>I am trying to create a simulation where I have an numpy ndarry and want to replace the elements within the array with a numeric value that's generated in a separate list, which has all the random outcomes from each iteration of the simulation.</p> <p>I'm very new to using arrays so I'm just beginning to learn about...
<p><code>name_value</code> is a list of <code>dict</code>, <code>i</code> is a <code>str</code> from <code>name_list</code> from <code>names</code>. This search is already not efficient and <code>i not in name_value</code> should always be <code>True</code>. Since you are populating <code>name_value</code> you don't ei...
python|numpy-ndarray
0
371,818
72,408,051
Using the 'in' Operator in Python | Observation Specific vs Columns
<p>If the following code works and equates to 'True':</p> <pre><code>'1234567' in '1234567:AMC' </code></pre> <p>Why won't it work in the following arrays/data-frames/columns?</p> <pre><code>import pandas as pd x = {'Non-Suffix' : ['1234567', '1234568', '1234569', '1234554'], 'Suffix' : ['1234567:C', '1234568:VXCF', '...
<p>You can use <code>apply()</code> to perform the test row-wise</p> <pre><code>x.apply(lambda row: row['Non-Suffix'] in row['Suffix'], axis=1) </code></pre>
python|pandas|dataframe|operators
2
371,819
72,333,359
Create new column with loc() iloc() and apply after using groupby see pictures
<p>Given this code:</p> <pre><code>from bs4 import BeautifulSoup from lxml import etree import requests import pandas as pd URL = &quot;https://boards.4chan.org/x/archive&quot; HEADERS = ({'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \ (KHTML, like Gecko) Chrome/44.0.2...
<p>After digging stackoverflow a little bit more, I've finally found exactly what I wanted:</p> <pre><code>df1 = df.groupby('Threads IDs') df2 = df1.agg({'Posts IDs':'count'}).join(df1['Content'].nth(3)).fillna('Not enough data.').rename(columns={&quot;Posts IDs&quot;: &quot;Number of Posts&quot;}) df2 </code></pre> <p...
python|python-3.x|pandas|dataframe|group-by
0
371,820
72,280,597
Index of Position of Values from B in A
<p>I have a little bit of a tricky problem here...</p> <p>Given two arrays A and B</p> <pre><code>A = np.array([8, 5, 3, 7]) B = np.array([5, 5, 7, 8, 3, 3, 3]) </code></pre> <p>I would like to replace the values in B with the <em>index of that value</em> in A. In this example case, that would look like:</p> <pre><code...
<p>The solution of @mozway is good for small array but not for big ones as it runs in <code>O(n**2)</code> time (ie. quadratic time, see <a href="https://en.wikipedia.org/wiki/Time_complexity" rel="nofollow noreferrer">time complexity</a> for more information). Here is a much better solution for big array running in <c...
python|arrays|numpy
3
371,821
72,418,372
pandas timedelta with float argument
<p>pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html" rel="nofollow noreferrer">Timedelta</a> documentation states that the <code>value</code> input parameter should be of the following types:</p> <p><code>valueTimedelta, timedelta, np.timedelta64, str, or int</code></p> <p>However, whe...
<p>It's interesting to note that:</p> <p><code>pd.Timedelta(1.234234, &quot;h&quot;)</code></p> <p>Is equivalent to:</p> <p><code>pd.Timedelta(hours=1.234234)</code></p> <p>And later on in the documentation it states:</p> <blockquote> <p>**kwargs ... Values for construction in compat with datetime.timedelta. ... python...
python|pandas|timedelta
0
371,822
72,162,363
How to do a mathematical operation pandas dataframe
<p>If I have three columns in pandas dataframe (CSV File), and I need to do a mathematical operation in the third column depending on the other two columns' values how can I do it? for example, if I have three columns</p> <p><a href="https://i.stack.imgur.com/TJkgu.png" rel="nofollow noreferrer"><img src="https://i.sta...
<pre><code>df['C'] = df['A'] * 3 + df['B'] </code></pre>
python|pandas|dataframe
0
371,823
72,355,887
Creating a table through a list for Pandas
<p>I am having a heck of a time turning data that i have into a dataframe through Pandas. I feel like this is far from a difficult task but i can't seem to figure it out. I have the headers i want for the dataframe and i have the data but this is data from the web. I know i need to turn it into a list and then put that...
<p>As stated, you could have Selenium click through each, then use <code>pandas</code>' <code>.read_html()</code> to parse the tables. However, there's an espn api, and if there is an api available, it's far better (more robust and efficient) to fetch the data that way as opposed to using Selenium. There's also far mor...
python|pandas|dataframe|selenium|database-design
1
371,824
72,471,890
use specific columns to map new column with json
<p>I have a data frame with:</p> <pre><code>A B C 1 3 6 </code></pre> <p>I want to take the 2 columns and create column D that reads {&quot;A&quot;:&quot;1&quot;, &quot;C&quot;:&quot;6}</p> <p>new dataframe output would be:</p> <pre><code>A B C D 1 3 6 {&quot;A&quot;:&quot;1&quot;, &quot;C&quot;:&quot;6} </code></pre> ...
<p>It's not exactly what you ask but you can convert your 2 columns into a dict then if you want to export your data in JSON format, use <code>df['D'].to_json()</code>:</p> <pre><code>df['D'] = df[['A', 'C']].apply(dict, axis=1) print(df) # Output A B C D 0 1 3 6 {'A': 1, 'C': 6} </code></pre>...
python|json|pandas|dataframe
0
371,825
72,390,974
How to apply differential privacy on list of data?
<p>How to apply differential privacy on a list of data. OpenMined release a <a href="https://github.com/OpenMined/PyDP" rel="nofollow noreferrer">differential privacy project called PyDP</a> 2 years ago. On the examples provided, they showed how to compute the PyDP on the data by computing some <a href="https://github....
<p>Here are my two cents on the question,</p> <p>The idea of differential privacy is to publish aggregated information of sensitive values only if noise is added to the aggregated info. This will in terms make it infeasible to match sensitive values to their owners, and also make the dataset not highly dependent on any...
python|machine-learning|pytorch|statistics|private
1
371,826
72,161,115
RGB array to PIL image
<p>I am having an array of rgb tuples</p> <pre><code>array = [(144, 144, 133), (85, 87, 75), (140, 87, 70), (129, 107, 105), (129, 107, 105), (194, 179, 171), (178, 164, 159), (100, 105, 122), (36, 38, 57), (59, 48, 49), (59, 48, 49), (152, 149, 148), (152, 149, 148), (0, 0, 0), (0, 0, 0), (98, 81, 84)...] </code></pr...
<p>I beleive, thatour problem lies in your reshape function. You reshape your array into an 2d array with shape <code>[sqrt(size),sqrt(size)]</code>. What you need instead is a 3d array with shape <code>[sqrt(size),sqrt(size),3]</code> (x dimension, y dimension, 3 RGB values).</p> <p>To solve your problem you should do...
python|image|numpy|python-imaging-library
0
371,827
72,185,076
Generate x,y,z coordinates with meshgrid and save to .csv
<p>I'm trying to create an evenly spaced 3D pointcloud/grid and export it to csv.</p> <p>I managed to find a solution to this problem (see link and code bellow), but sadly there is no explanation and I'm scratching my head, trying to understand why the 3 FOR loops are for.</p> <p>Source: <a href="https://stackoverflow....
<p>You have 3 for loops because you are using 3 axes.</p> <p>nunpy meshgrid creates N-D coordinate arrays. For example, simple 2D array with 2 points in each direction:</p> <pre><code>x = ['x0', 'x1'] y = ['y0', 'y1'] x_mesh, y_mesh = np.meshgrid(x, y) print('x') print(x_mesh) print('y') print(y_mesh) print('---') </...
python|numpy|grid
0
371,828
72,449,976
Python4Delphi can't import numpy
<p>I was curious about <code>Python4Delphi</code> and installed it and looked through the demos a bit. Now I wanted to install <code>Numpy</code> via CMD with pip this went well without errors. but now when I enter the following code in DEMO01 of <code>Python4Delphi</code> I get an error message. If I enter the same co...
<p>Can you check you're using the same versions of python using both methods by checking what this returns...</p> <pre><code>import sys for p in sys.path: print(p) </code></pre> <p>Carefully compare the output of that little bit of code as it'll point out any obvious differences.</p> <p>From my experiments if you'v...
python|numpy|delphi|python4delphi
1
371,829
72,153,361
Iterate over CSV rows using pandas in a faster way
<p>I'm trying to read a CSV file through file upload from html template, and iterating over the rows and creating model object.</p> <p><strong>views.py</strong></p> <pre><code> ​@​login_required ​def​ ​uploadStudents1​(​request​): ​    ​if​ ​request​.​method​ ​==​ ​'POST'​: ​        ​uploaded_file​ ​=​ ​request​....
<p>You should use bulk_create because create will take time if you do it inside loop</p> <pre><code> ​@​login_required ​def​ ​uploadStudents1​(​request​): ​ ​if​ ​request​.​method​ ​==​ ​'POST'​: ​ ​uploaded_file​ ​=​ ​request​.​FILES​[​'document'​] ​ ​ext​ ​=​ ​os​.​path​.​splitext​(​uploaded_...
python|django|pandas|django-models
0
371,830
72,321,527
How to stop Pandas converting integer to decimal when reading in an .xlsx file?
<p>I have an .xlsx file that I am loading into a dataframe using the pd.read_excel method. However, when I do so, one of my columns appears to change format, with pandas adding a decimal point. Does anyone know why this is happening and how to stop it please?</p> <p>Example of data in the .xlsx file:</p> <pre><code>191...
<p>Your file most likely has infinite and nan values within the column.</p> <p>You will need to remove them first</p> <pre><code>import numpy as np df.replace([np.inf, -np.inf], np.nan, inplace=True) df.fillna(0, inplace = True) df.column1 = df.column1.astype(int) </code></pre>
python|pandas
0
371,831
72,469,487
Compare nth letter in one column to a single letter in another
<p>I have a df as follows:</p> <pre><code> Policy Letter Password Lower Upper Count Lower_Minus_1 Upper_Minus_1 0 4-5 l rllllj 4 5 4 3 4 1 4-10 s ssskssphrlpscsxrfsr 4 10 8 3 9 2 14-18 ...
<pre><code>df.apply(lambda x:x['Letter']== x['Password'][x.Lower_Minus_1], axis=1) 0 True 1 False 2 True 3 True 4 True dtype: bool </code></pre>
python-3.x|pandas|string
0
371,832
72,186,090
How would i merge these two datasets keeping columns from each?
<p>i want to include all columns from each dataset, how would i accomplish this?</p> <p><a href="https://i.stack.imgur.com/cCOCo.png" rel="nofollow noreferrer">Dataset1</a></p> <p><a href="https://i.stack.imgur.com/v4VFX.png" rel="nofollow noreferrer">Dataset2</a></p>
<p>If you provide more details of what you are looking for it would be easier to assist you, but IIUC this will give all columns and join them on the same column names</p> <pre><code>import pandas as pd df_merge = pd.merge(df1, df2) </code></pre>
python|pandas|dataframe|merge
0
371,833
72,314,605
Pandas Check two data frame columns and access third value
<p>I am very beginner to pandas though I solved same case with comparison here is data frame I was working</p> <pre><code>s= [ { 'from':0, 'to':400000000, 'value':0.01 }, { 'from':400000001, 'to':500000000, 'value':0.015 }, { 'from':500...
<p>You just need to apply those conditions correctly. Since there is no value that satisfies both conditions. You can do:</p> <pre><code>df[df['from'].le(0) &amp; df['to'].le(400000000)]['value'] </code></pre> <p>And it will result in:</p> <pre><code>0 0.01 Name: value, dtype: float64 </code></pre>
python|pandas|dataframe
2
371,834
72,243,632
Seaborn boxplot for classification with pandas wide to long
<p>I have data that I would like to train an ml classifier on. The data is in wide format. I'd like to do a boxplot with searborn <code>sns.boxplot(x='variable',y='value', hue='target', data=df_train)</code>. How do I reshape the data to be able to pass it to <code>sns.boxplot</code>?</p> <p>Sample data</p> <pre><code>...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer">pd.melt</a> is what you want to use.</p> <pre><code>dfg_train = df_train.melt(id_vars='y') sns.boxplot(x='variable',y='value', hue='y', data=dfg_train) </code></pre>
pandas|seaborn
0
371,835
72,388,246
(Hack to get Auth to work) ERROR: default: Authentication failed: password is incorrect or there is no user with such name (clickhouse sqlalchemy)
<p><strong>Issue:</strong> When using <strong>Sqlalchemy</strong>(Python/Pandas Dataframe) to connect to <strong>Clickhouse</strong> DB, below error occurs when attempting to <strong>authenticate</strong> credentials.</p> <p><strong>Error:</strong> <code>default: Authentication failed: password is incorrect or there is...
<p>That project is no longer actively maintained and has multiple issues when connecting with current versions of ClickHouse.</p> <p>For Pandas/Numpy you should look at either the native <a href="https://github.com/mymarilyn/clickhouse-driver" rel="nofollow noreferrer">https://github.com/mymarilyn/clickhouse-driver</a>...
python|pandas|sqlalchemy|clickhouse|clickhouse-client
0
371,836
72,168,663
Setting a list of (x,y) cooordinates into an array so polygons are drawn
<p>I have some code that prints out a list of coordinates (stored in points</p> <pre><code>f=open('139cm_2000_frame27.json') data=json.load(f) shapes=data[&quot;shapes&quot;] for i in shapes: print(i['label']) # prints the label first for c in i['points']: d=np.array(c) print(d) # a...
<p>From software engineering point of view, <strong>it is recomended to break your code into simple separate parts</strong> (i.e. make it modular).</p> <p><strong>First</strong> you will need a function for reading the input json and parsing it. I called it <code>read_input</code> in the code below. The format of the p...
python|json|numpy-ndarray|scikit-image
2
371,837
72,476,921
Adding a column to designate column observations in sportsreference scrape
<p>[Marko Prcać]provided the following answer to (<a href="https://stackoverflow.com/questions/67082305/sportsipy-api-request">Sportsipy API request</a>)</p> <pre><code>from sportsreference.nba.schedule import Schedule # MIL removed from league list as it is used to initiate league_schedule league = ['CHO','LAL','LAC'...
<p>After a little more work and a little help this is will work:</p> <pre><code>from sportsreference.nba.schedule import Schedule import pandas as pd league = ['MIL','CHO','LAL','LAC','SAC','ATL','MIA','DAL', 'POR','HOU','NOP','PHO','WAS','MEM','BOS','DEN', 'TOR','SAS','PHI','BRK','UTA','IND','OKC'...
python|pandas|dataframe
1
371,838
72,268,853
append data frame to existing worksheet for particular column by pandas or openpy excel
<p>Append data frame to existing workbook for particular column</p> <p><a href="https://i.stack.imgur.com/eEPrd.png" rel="nofollow noreferrer">1 table is excel work book</a></p> <p><a href="https://i.stack.imgur.com/aBGTf.png" rel="nofollow noreferrer">2 nd table is data frame</a></p> <p><a href="https://i.stack.imgur....
<p>first read excel files using <code>pd.read_excel(file path)</code>, then use:</p> <pre><code>df.append(df2) </code></pre> <p>Illustration:</p> <pre><code>df = pd.DataFrame({'code':[1,2], 'name': ['a', 'b'], 'class':[5,9], 'rol': ['y', 'h'], 'sub':['eng', 'math']}) df2 = pd.DataFrame({'name': ['c', 'd'], 'class':[5,9...
python|pandas|openpyxl
0
371,839
72,174,354
Pivot table based on monthly sales using python
<p>I have a dataframe df having sales by month:</p> <pre><code>customer product month revenue sam A 2021-11 221 tim A 2021-12 220 mi. B 2021-10 213 harry A 2011-11 210 eric. A. 2021-10 213 </code><...
<p>maybe this could help:</p> <pre><code>g_data = data.groupby(['product','month','customer'])['revenue'].sum().unstack('month').fillna(0) &gt;&gt;&gt; g_data ''' month 2021-10 2021-11 2021-12 product customer A eric. 213.0 0.0 0.0 harry 0....
python|python-3.x|pandas|pivot-table
0
371,840
72,415,981
Albumentations on Google Colab : module 'albumentations' has no attribute 'SomeOf'
<p>Originally, I posted this in <a href="https://github.com/albumentations-team/albumentations/issues/1173#issue-1251616985" rel="nofollow noreferrer">Albumentation's Github issues listing</a></p> <p>I used Albumentations on my local machine to do data augmentation using the latest version <code>1.1.0</code> through a ...
<p>I've tried changing the version installation and it worked</p> <p><code>!pip install -q opencv-python==4.5.5.64</code></p> <p><code>!pip install -q --force-reinstall albumentations==1.0.3</code></p> <p>It is also recommended to update Pillow to a recent version.</p>
python|tensorflow|keras|google-colaboratory|albumentations
0
371,841
72,354,731
How to use function from class Python in Pandas?
<p>I have a Python class with methods inside. One of them is public.</p> <p>How to apply this method in filtering rows data in Pandas?</p> <p>I meaan something like this:</p> <pre><code>class Math: def isTrue(value): return True </code></pre> <p>Pandas rule:</p> <pre><code>df[df[&quot;name&quot;].apply(Math.isT...
<pre class="lang-py prettyprint-override"><code>import re class Matcher: pattern = re.compile('^(?P&lt;num_pair&gt;\d\d)(?(num_pair)(?P=num_pair))$') @classmethod def has_num_pair(cls, n: int) -&gt; bool: if cls.pattern.match(str(n)) is None: return False return True </code...
python|pandas
1
371,842
72,289,889
How do I fix the "mach-o, but wrong architecture" error in Pycharm?
<p>I'm importing numpy and matplotlib in a Pycharm .py script on a Mac and I keep getting this error.</p> <pre><code>/usr/bin/python3 /Users/aksseet/PycharmProjects/Election/electorate.py /Users/aksseet/PycharmProjects/Election/electorate.py:1: UserWarning: The NumPy module was reloaded (imported a second time). This c...
<p><strong>Full disclaimer:</strong> I do not own a Mac, so I don't have any means of testing whether or not this solution will work. However, I'll give it my best go, and hopefully will have at least provided some useful resources for further digging.</p> <p>From what I'm reading across several GitHub issues citing si...
python|numpy|matplotlib|pycharm
1
371,843
72,186,518
Pandas - drop function
<p>I want to drop rows from a dataframe, based on the condition that the value of a specific column is in a list. If this is not the case I want the row to be dropped.</p> <p>Do you have any suggestions? Thanks in advance</p> <p>As an example, if the value in column 'C' is not inside the list l, I want to drop the enti...
<pre><code>df = df[df.apply(lambda x: any(x.isin(l)), axis=1)] </code></pre> <p>if only one column must be</p> <p>and if, only <code>C</code>:</p> <pre><code>df[df.apply(lambda x: x[&quot;C&quot;] in l, axis=1)] </code></pre> <p>or, if all columns:</p> <pre><code>df = df[df.apply(lambda x: all(x.isin(l)), axis=1)] </co...
python|pandas|dataframe|drop
1
371,844
72,192,367
How to replace words in list with Python
<p>I am trying to replace a certain set of words in a list with words from a different list.</p> <ol> <li>Check &quot;s&quot;</li> <li>If words in &quot;invalid_list&quot; are in &quot;s&quot; it should be replaced with xyz</li> </ol> <p>The outcome for &quot;s&quot; should be :</p> <p>['123xyz', '456xyz', '789xyz']</p...
<p>Iterate over the invalid_list and use the in-built <a href="https://www.geeksforgeeks.org/python-string-replace/?ref=leftbar-rightbar" rel="nofollow noreferrer">replace() function</a> to replace the substring.</p> <pre><code>for i in invalid_list: s = [string.replace(i, 'xyz') for string in s] </code></pre>
python|pandas|list|for-loop
2
371,845
72,352,736
How do i stop Vscode from truncating output of python dataframe column
<p>I've tried to mention pandas setting and set <strong>display width</strong> to no avail. I just want vscode to show me the full output. Some other posts said there was a <strong>setting called 'Data Science'</strong>. I could not find that anywhere in vscode.</p> <p>This was a .py file it was running some other code...
<p>There is no reason to make data casting or novel series conversions. You can change pandas' configurations.</p> <p>Check the documentation <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.set_option.html#pandas-set-option" rel="nofollow noreferrer">here</a>.</p> <p>Here a solution:</p> <pre...
python|pandas|visual-studio-code
1
371,846
72,301,367
Is there a way to variable slicing in numpy?
<p>I'm trying to slice an array in a variable way. For example, from row 0 up to row 10, slice the array using a step of 2. From row 10 to row 30 slice it using a step of 3.</p> <p>Also, it is worth mentioning that I'm trying to do so without writing any loops.</p> <p>So far I've tried the following:</p> <pre><code>&gt...
<p>As pointed out in the comments, you can only apply single slices per dimension. But you could apply the 2 slices separately and concatenate the parts of the array back together like so:</p> <pre><code>x = np.arange(64*128).reshape(64, 128).transpose() np.concatenate([x[s] for s in np.s_[0:10:2, 10:30:3]]) </code></p...
python|numpy|slice|numpy-slicing
1
371,847
72,290,949
Round a range in pandas
<p>I have df_surf_dist=</p> <pre><code> index surface_relle_bati 0 (8.718, 27.733] 442 1 (27.733, 46.467] 1485 2 (46.467, 65.2] 1296 3 (65.2, 83.933] 927 4 (83.933, 102.667] 288 5 (102.667, 121.4] ...
<p>You can use a custom function to recreate the intervals:</p> <pre><code>def round_interval(i, ndigits=2): return pd.Interval(round(i.left, ndigits), round(i.right, ndigits), i.closed) df['range'].apply(round_interval, ndigits=1) </code></pre> <p>output:</p> <pre><code>0 (8.7, 27.7] 1 (27.7, 46.5] 2 (4...
python|pandas
2
371,848
50,565,746
Map values from more dataframes to one by multiple values in Pandas
<p>I need help with some a little tricky mapping for me. </p> <p>It's not difficult to map on clean one value, but now I have multiple values in one cell to map on. There is no rule how many values can be, but the most often is between 1 and 4. </p> <p>Dataframes looks like this:</p> <pre><code>df: flag id 1 [A...
<p>First you have to define a new dataframe, the write like</p> <pre><code>d = {'col1':[0,0,0,0,0],'col2':[0,0,0,0,0],'col3':[0,0,0,0,0]} new_df = pd.DataFrame(d) new_df['col1']=df1['col1'] new_df['col2']=df1['col2'] new_df['col3']=df1['col3'] </code></pre> <p>check it</p>
python|list|pandas|dataframe|mapping
0
371,849
50,449,738
InterpolatedUnivariateSpline and ax.fill_between yield unexpected result (filling wrong area) with low Y-values
<p>I have a function that is supposed to take some raw data, plot it onto a canvas and then fill the area between the baseline and a pre-defined peak, which works well for high Y-values but gives the inverse result when using low Y-values. My question is then two-fold:</p> <ol> <li>Why does this occur?</li> <li>What i...
<p>I am sorry for answering my own question so fast but I noticed that I made a mistake when I initially implemented this that never came up before, as I always had high intensity data.</p> <p>The <code>ax.fill_between</code> expects <code>x</code>, <code>y1</code> and <code>y2</code>, and with the high Y-value data i...
numpy|matplotlib|scipy|curve-fitting
1
371,850
50,478,971
Pandas separate string and strip
<p>I have a Pandas column contains string like this:</p> <pre><code>(15:38) Hello, how are you? (15:39) I am fine. (15:40) That's good. </code></pre> <p>I want to separate the string by the time mark so I used regex: <code>r'\(\d{1,2}:\d{1,2}\)'</code> I only want to keep anything starting from the third time mark t...
<p>You may use <code>(?:(?:\(\d+:\d+\))[^\(]+){2,}(\(\d+:\d+\).*$)</code> to extract the last match to your pattern, along with <strong><code>extract</code></strong></p> <p>This will not work if any of the dialog has parenthesis.</p> <p><strong><em>Sample DataFrame</em></strong></p> <pre><code> ...
python|regex|pandas
0
371,851
50,313,521
Using scikit StandardScaler in Pipeline on a subset of Pandas dataframe columns
<p>I want to use sklearn.preprocessing.StandardScaler on a subset of pandas dataframe columns. Outside a pipeline this is trivial:</p> <pre><code>df[['A', 'B']] = scaler.fit_transform(df[['A', 'B']]) </code></pre> <p>But now assume I have column 'C' in df of type string and the following pipeline definition</p> <pre...
<p>You could check out <a href="https://github.com/scikit-learn-contrib/sklearn-pandas" rel="noreferrer">sklearn-pandas</a> which offers an integration of Pandas DataFrame and sklearn, e.g. with the DataFrameMapper:</p> <pre><code>mapper = DataFrameMapper([ ... (list_of_columnnames, StandardScaler()) ... ]) </code...
python|pandas|scikit-learn
7
371,852
50,401,149
Multiplying Pandas DataFrames with Column and Index Names
<p>I have two pandas dataframes that I am importing from excel workbooks. The have item names as the in the first column and Months as the column headers. They are the same size and have identical column headers/row index names. I would like to multiply these two dataframes together and end up with the same item nam...
<p>You can using <code>select_dtypes</code> to exclude the non numeric type columns , then we using <code>mul</code> , and <code>update</code> , to get the result and update the value accordingly </p> <pre><code>df.update(df.select_dtypes(exclude='object').mul(df1.select_dtypes(exclude='object'))) df Out[891]: ...
python|pandas|dataframe
1
371,853
50,454,573
Getting the average from a dataframe consisting of pandas timestamp
<p>I have two panda series, <code>closedDate</code> and <code>createdDate</code>, thats elements are pandas timestamps, <code>class 'pandas._libs.tslib.Timestampclass 'pandas._libs.tslib.Timestamp</code>. </p> <p>I have subtracted those two panda series to make a list, <code>age</code>, of pandas timedelta.</p> <pre...
<p>You can and should aim to use vectorised functions for this task.</p> <p>In this example, you can subtract one <code>pd.Series</code> from another. You can then use the <a href="https://pandas.pydata.org/pandas-docs/stable/timedeltas.html#reductions" rel="nofollow noreferrer"><code>mean</code></a> method to calcula...
python|pandas|datetime|timedelta
2
371,854
50,509,741
Optimizing Tensorflow for a 32-cores computer
<p>I'm running a tensorflow code on an Intel Xeon machine with 2 physical CPU each with 8 cores and hyperthreading, for a grand total of 32 available virtual cores. However, I run the code keeping the system monitor open and I notice that just a small fraction of these 32 vCores are used and that the average CPU usage ...
<p>TensorFlow will attempt to use all available CPU resources by default. You don't need to configure anything for it. There can be many reasons why you might be seeing low CPU usage. Here are some possibilities:</p> <ul> <li>The most common case, as you point out, is the slow input pipeline.</li> <li>Your graph might...
tensorflow|parallel-processing|cpu-usage
2
371,855
50,546,934
Python spyder + tensorflow cross validation freezes on Windows 10
<p>On Windows 10, I have installed <code>Anaconda</code> and launched <code>Spyder</code>. I have also successfully installed <code>Theano</code>, <code>Tensorflow</code> and <code>Keras</code>, since when I execute </p> <blockquote> <p>import keras</p> </blockquote> <p>the console outputs </p> <blockquote> <p...
<p>it seems Windows has an issue with "n_jobs", remove it in your "accuracies=" code and it will work, downside is it may take a while but at least it will work. </p>
windows|tensorflow|keras|spyder|cross-validation
1
371,856
50,237,761
Keras LSTM Dataset Sizing Issue
<p>I'm working on a project that involves LSTM prediction using the Keras library (run over Tensorflow). </p> <p><strong>SETUP</strong></p> <p>My training "X" dataset is (initially) a Pandas dataframe containing 52,000+ rows x 19 columns. These 19 columns contain 15 current exogenous readings and one time-step contai...
<p>LSTM accepts data in the form of </p> <pre><code>(no_of_samples,timesteps,no_of_features) </code></pre> <blockquote> <p>ValueError: Input arrays should have the same number of samples as target arrays. Found 1 input samples and 52590 target samples.</p> </blockquote> <p>Regarding the original issue, the model t...
python|numpy|keras
0
371,857
50,595,548
Filtering out rows with non-alphanumeric characters
<p>I am trying to get a DataFrame from an existing DataFrame containing only the rows where values in a certain column(whose values are strings) do not contain a certain character.</p> <p>i.e. If the character we don't want is a <code>'('</code></p> <p>Original dataframe:</p> <pre><code> some_col my_column 0 ...
<p>You're looking for <code>str.isalpha</code>:</p> <pre><code>df[df.my_column.str.isalpha()] some_col my_column 0 1 some 1 2 word </code></pre> <p>A similar method is <code>str.isalnum</code>, if you want to retain letters and digits. </p> <p>If you want to handle letters and whitespac...
python|pandas|dataframe
9
371,858
50,291,916
What does the update_op return variable mean, in precision_at_k metric, in TensorFlow?
<p>I have the following code:</p> <pre><code>&gt;&gt;&gt; rel = tf.constant([[1, 5, 10]], tf.int64) # Relevant items for a user &gt;&gt;&gt; rec = tf.constant([[7, 5, 10, 6, 3, 1, 8, 12, 31, 88]], tf.int64) # Recommendations &gt;&gt;&gt; &gt;&gt;&gt; metric = tf.metrics.precision_at_k(rel, rec, 10) &gt;&gt;&gt; &gt;&g...
<p>Below is the example detailing how the two returns from <code>tf.metrics.precision_at_k</code> works.</p> <pre class="lang-py prettyprint-override"><code>rel = tf.placeholder(tf.int64, [1,3]) rec = tf.constant([[7, 5, 10, 6, 3, 1, 8, 12, 31, 88]], tf.int64) precision, update_op = tf.metrics.precision_at_k(rel, rec...
tensorflow
6
371,859
50,501,261
tensorflow GradientDescentOptimizer: Incompatible shapes between op input and calculated input gradient
<p>The model worked well before optimization step. However, when I want to optimize my model, the error message showed up: </p> <blockquote> <p>Incompatible shapes between op input and calculated input gradient. Forward operation: softmax_cross_entropy_with_logits_sg_12. Input index: 0. Original input shape: (...
<p>Correct following things.</p> <p>First,</p> <p>Change placeholders input shape to this</p> <pre><code>X = tf.placeholder(tf.int32, shape=[None,400] Y = tf.placeholder(tf.float32, shape=[None,1] </code></pre> <p>Why <strong>None</strong> because this gives you freedom of feeding any size. This is preferred becaus...
python|tensorflow|gradient-descent
1
371,860
50,559,586
Deep Learning YOLO Object Detection: How to iterate over cells in a grid defined over the image
<p>I am trying to implement the YOLOv2 Object Detection algorithm myself, just to learn how the algorithm works. Of course I will use pre-trained weights to make things faster. I was using the code from the <a href="https://github.com/experiencor/keras-yolo2/blob/master/Yolo%20Step-by-Step.ipynb" rel="nofollow noreferr...
<p><code>Yolo v2</code>, per say, does not break the images into <code>13x13</code> grid, but makes predictions at a grid level instead of pixel level. </p> <p>The network takes the input image of size <code>416x416</code> and outputs <code>13x13</code> predictions, each of which is an array that contains class probab...
python|tensorflow|keras|deep-learning|convolutional-neural-network
3
371,861
50,504,743
while_loop with ValueError Shape must be rank 0 but is rank 2 for 'while/LoopCond'
<pre><code>x=([1.,2.], [2.,1.]) xtensor = tf.convert_to_tensor(x) A = xtensor B = xtensor def cond(now,pre): return (tf.greater(now,pre)) def body(now,pre): return pre,now A,now = tf.while_loop(cond,body,[A,B]) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) A = sess.run(A) B = ...
<p>The condition function (<code>cond</code>) of <code>tf.while_loop()</code> must return a boolean tensor of rank 0 (i.e. of shape <code>[]</code>, i.e. a single boolean). Your <code>cond</code> is returning a boolean tensor of rank 2 (as <code>tf.greater(now, pre)</code> returns a tensor of same shape as <code>now</c...
python|loops|tensorflow|rank
2
371,862
50,637,921
Weighted masking in TensorFlow
<p>I have the following task: having two vectors <code>[v_1, ..., v_n]</code> and <code>[w_1, ..., w_n]</code> build new vector <code>[v_1] * w_1 + ... + [v_n] * w_n</code>. </p> <p>For exmaple for <code>v = [0.5, 0.1, 0.7]</code> and <code>w = [2, 3, 0]</code> the result will be </p> <p><code>[0.5, 0.5, 0.1, 0.1, 0....
<p>Here is a simple solution using <code>tf.sequence_mask</code>:</p> <pre><code>import tensorflow as tf v = tf.constant([0.5, 0.1, 0.7]) w = tf.constant([2, 3, 0]) m = tf.sequence_mask(w) v2 = tf.tile(v[:, None], [1, tf.shape(m)[1]]) res = tf.boolean_mask(v2, m) sess = tf.InteractiveSession() print(res.eval()) # a...
python|tensorflow
1
371,863
50,325,142
CNN+LSTM OCR model not predicting "is" correctly
<p>I have made a model in tensorflow with the following structure for OCR. I trained it on a significantly large dataset(250K images) and also getting around 94% accuracy. But the model predicts "is" as "1s" or "1S" most of the times. I checked the dataset and it contains quite a lot of instances of "is" so I dont thin...
<p>Since probably most numbers in your dataset are preceded by spaces, and "1" and "i" look similar, it is somewhat of an understandable error.</p> <p>I do not thing changing the architecture of the network will help at all.</p> <p>What I would do is to artificially <em>oversample</em> the "is" instances. You say the...
tensorflow|deep-learning|ocr|lstm|convolutional-neural-network
1
371,864
50,468,990
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-dxjZrU/pyproj/ when installing 'geopandas'
<p>Before going to the topic, my computer information:</p> <p>OS: Debian jessie, Python version: 2.7</p> <p>I need to install the module "geopandas" for a project i am working on. The problem is that when i tried, i receive the following error:</p> <pre><code>root@debian:~# pip install geopandas Collecting geopandas...
<p>Debian 8 Jessie, 32bit</p> <blockquote> <p>'i586-linux-gnu-gcc': No such file or directory</p> </blockquote> <pre><code># apt install g++ gfortran python-all-dev python-numpy libgdal-dev libgeos-dev python-matplotlib # pip install geopandas . . Running setup.py install for munch Successfully installed geopa...
python-2.7|installation|geopandas
0
371,865
50,349,213
AttributeError: 'str' object has no attribute 'ndim', unable to use model.predict()
<p>I was trying to make an Image Captioning model in a similar fashion as in <a href="https://machinelearningmastery.com/develop-a-deep-learning-caption-generation-model-in-python/#comment-437586" rel="nofollow noreferrer">here</a></p> <p>I used ResNet50 instead off VGG16 and also had to use progressive loading via mo...
<p>You pass <code>inSeq = "START"</code> to <code>model.predict</code> as a string:</p> <pre><code>ID = model.predict([np.array(feature[0][0][0]), inSeq]) </code></pre> <p>without pre-processing it. You will need to encode it to an array.</p>
python-3.x|tensorflow|keras|deep-learning|captions
0
371,866
50,633,408
Striding a 2D model over an image to produce image of labels (NOT convolution)
<p>I have a model trained from RGB image samples that take a 31x31 pixel region as input and produces a single classification for the center pixel.</p> <p>I'd like to apply this model over an entire image to recover effectively a new image of classifications for each pixel. Since this isn't a convolution, I'm not sure...
<p>Make your model a <code>fully-convolutional</code> neural network, so for a <code>31x31</code> image it will produce a <code>single label</code> and for a <code>62x62</code> image it will produce <code>2x2</code> labels and so on. This will remove the redundant computation you talked about in case of windowing meth...
python|tensorflow|machine-learning|neural-network
0
371,867
50,471,846
Python looping two different dataFrames to create a new column
<p>I want to add a new column to a dataframe by referencing another dataframe. </p> <p>I want to run an if statement using startswith method to match df1['BSI'] column to df2['initial'] to assign the corresponding df2['marker'], and give df1 a new column that consists of markers, which I will use for cartopy marker st...
<p>Use map. Infact there are many similar answers using map but the only difference here is that you are using only a part of BSI in df1 for matching</p> <pre><code>df1['marker'] = df1['BSI'].str.extract('(.*)-', expand = False).map(df2.set_index('initial').marker) BSI Shelter_Number Location ...
python|pandas|loops|dataframe
1
371,868
50,313,441
ModuleNotFoundError: No module named 'tensorflow.examples'
<p>When I import tensorflow</p> <pre><code>import tensorflow as tf </code></pre> <p>I don't get an error. However, I do get the error below. I'm using spyder if that helps.</p> <p>As per other questions, I ensured up to date (v1.8) tensorflow using both conda and then pip installs. This didn't resolve the issue. Ple...
<p>I think you should use like bellow on tensorflow 2</p> <pre><code>import tensorflow_datasets mnist = tensorflow_datasets.load('mnist') </code></pre>
python|tensorflow|mnist
19
371,869
50,311,256
regarding analyzing unique values of image array
<p>There is the following function to read image, I add several lines to re-output the image, and to output the different pixel values of the image array. The image looks like this. However the <strong>a,indices =np.unique(img,return_index=True)</strong></p> <p>gives </p> <p><strong>a [0 1]</strong></p> <p><st...
<p>The indices give the first occurrences of unique values in the <em>flattened</em> input array. To convert those indices to 2-d indices into the input, you can use <code>np.unravel_index</code>.</p> <p>For example, suppose the shape of <code>img</code> is (1000, 1600):</p> <pre><code>In [110]: shape = (1000, 1600)...
python|numpy|image-processing|scipy|pillow
1
371,870
50,619,640
How to select percentage of rows in pandas dataframe
<p>In python I have a few dataframes structured like so:</p> <pre><code>0 0 0 0 1 1 1 1 2 2 2 2 . . . . n n n n </code></pre> <p><strong>How can I select the middle 33% rows (determined by index, not value)?</strong></p> <p>Here is what I attempted:</p> <pre><code>df.iloc[int(len(df)*0.33):int(len(df)*0.66)] </code...
<p>You can also use numpy percentile function on index. This method also works when your index doesn't start from zero.</p> <pre><code>df[(df.index&gt;np.percentile(df.index, 33)) &amp; (df.index&lt;=np.percentile(df.index, 66))] </code></pre>
python|pandas|dataframe
3
371,871
50,518,622
Anaconda Tensorflow runtime issue
<p>I am trying to run tensorflow with gpu support on my computer (NVIDIA 960 M) using anaconda and cuda but I keep running into this error. I have tried reinstalling cuda (normally and anaconda) multiple times. </p> <pre><code>&gt;Python 2.7.15 |Anaconda, Inc.| (default, May 1 2018, 23:32:55) [GCC 7.2.0] on linux2 T...
<p>The version of Tensorflow you have installed requires CUDA 9.0 (c.f. <code>libcublas.so.9.0</code> import attempt). You should check if you have it installed and properly setup. </p> <p>This <a href="https://stackoverflow.com/questions/42013316/after-building-tensorflow-from-source-seeing-libcudart-so-and-libcudnn-...
python|ubuntu|tensorflow|anaconda|conda
0
371,872
50,415,402
pandas calculates column value means on groups and means across whole dataframe
<p>I have a <code>df</code>, <code>df['period'] = (df['date1'] - df['date2']) / np.timedelta64(1, 'D')</code> </p> <pre><code>code y_m date1 date2 period 1000 201701 2017-12-10 2017-12-09 1 1000 201701 2017-12-14 2017-12-12 2 1000 201702 2017-12-15 2017...
<h3><code>pivot_table</code> with <code>margins=True</code></h3> <pre><code>piv = df.pivot_table( index='code', columns='y_m', values='period', aggfunc='mean', margins=True ) # housekeeping (piv.reset_index() .rename_axis(None, 1) .rename({'code' : -1, 'All' : 0}, axis=1) .sort_index(axis=1) ) -1 ...
python|pandas|dataframe|pandas-groupby
1
371,873
50,627,630
pandas data format to preserve DateTimeIndex
<p>I do a lot of work with data that has DateTime indexes and multi-indexes. Saving and reading as a .csv is tedious because every time I have to reset_index and name it "date" then when I read again, I have to convert the date back to a datetime and set the index. What format will help me avoid this? I'd prefer someth...
<p>feather was made for this: <a href="https://github.com/wesm/feather" rel="nofollow noreferrer">https://github.com/wesm/feather</a></p> <blockquote> <p>Feather provides binary columnar serialization for data frames. It is designed to make reading and writing data frames efficient, and to make sharing data acro...
python|pandas|datetime|file-format
3
371,874
50,569,899
pandas: how to group by multiple columns and perform different aggregations on multiple columns?
<p>Lets say I have a table that look like this:</p> <pre><code>Company Region Date Count Amount AAA XXY 3-4-2018 766 8000 AAA XXY 3-14-2018 766 8600 AAA XXY 3-24-2018 766 2030 BBB XYY ...
<p>Need aggregate by single non nested dictionary and then <code>rename</code> columns:</p> <pre><code>aggregation = {'Count': 'mean', 'Amount': 'sum'} cols_d = {'Count': 'Total Count', 'Amount': 'Total Amount'} df = df.groupby(['Company','Region'], as_index=False).agg(aggregation).rename(columns=cols_d) print (df) ...
python|pandas|pandas-groupby
8
371,875
50,439,217
How can I understand the order of the result of `numpy.narray.view` if I use it to view 2 `np.uint8` as 1 `np.uint16`?
<p>Let's say I have an array <code>a</code> with two elements of data type <code>np.uint8</code>. And I'd like to view this array as if its contents were of data type <code>np.uint16</code>. So I use the <code>numpy.narray.view</code> method:</p> <pre><code>import numpy as np a = np.array([1, 2], dtype=np.uint8) prin...
<p>Thanks to the comments from @WarrenWeckesser and @hpaulj I figured it out:</p> <p>The two parts of the <code>numpy.uint16</code> which can be interpreted as two <code>numpy.uint8</code> don't necessarily lie "consecutively" in the memory. How the bytes are stored in the memory depends on the platform's endianness. ...
python|numpy|binary|scientific-computing
0
371,876
50,614,545
Numpy Separating CSV into columns
<p>I'm trying to use a CSV imported from bballreference.com. But as you can see, the separated values are all in one row rather than separated by columns. On NumPy Pandas, what would be the easiest way to fix this? I've googled to no avail. </p> <p><a href="https://i.stack.imgur.com/oEXHp.png" rel="nofollow noreferrer...
<p>It seems that the first two rows of your CSV file are headers, but the default behavior of <code>pd.read_csv</code> thinks that only the first row is header.</p> <p>Also, the beginning and trailing quotes make <code>pd.read_csv</code> think the text in between is a single field/column.</p> <p>You could try the fol...
python|pandas|csv|numpy|jupyter-notebook
2
371,877
50,669,405
RNN not training when batch size > 1 with variable length data
<p>I'm implementing a simple RNN network which predicts 1/0 for some variable length time-series data. The network would first feed the training data into an LSTM cell, and then use a linear layer for classification. </p> <p>Usually, we would use mini-batches to train the network. But, the problem is that this simpl...
<p>I think one major problem is that you are passing <code>ht[-1]</code> as input to the linear layer.<br> The <code>ht[-1]</code> will contain the state from the last time-step which will only be valid for the input with maximum length.</p> <p>To solve this you need to unpack the output and get the output correspondi...
machine-learning|nlp|pytorch|rnn
0
371,878
50,440,487
pandas creating new table from two tables
<p>I have to join two tables and create a table with dates, but my code is way to long and I believe that I done it the super long way.Apparently the soulution to this only had 22 lines. Is there another way and more shorter way to approach this problem. Here is the question <a href="https://i.stack.imgur.com/QOKCM.png...
<p>I think that you can theoretically do this whole thing in one line:</p> <pre><code>finaldf = (pd.concat([pd.read_csv('data1.csv', parse_dates={'Date':['Year', 'Month', 'Day']}), pd.read_csv('data2.csv', parse_dates={'Date':['Year', 'Month...
python|pandas|csv
1
371,879
50,374,882
Two-sample Kolmogorov-Smirnov Test in Python Scipy on brain data
<p>I have brain anatomy measurements from 2 different groups of individuals. One group has more individuals than the other (say n and m individuals each). I have to run the KS test on this data. I am a little unclear about the arguments to pass to the scipy two sample KS test. Will arguments to the scipy 2 sample ks te...
<p>Let's say one of the measurements is brain mass. Gather all the brain mass measurements for group 1 into a sequence (or 1-d array), and do the same for group 2. Pass these two sequences to <code>ks_2samp</code>. That will test whether the brain masses of the two groups come from the same distribution.</p> <p>For ...
python|numpy|scipy|statistics
2
371,880
50,323,360
Python: Dividing a column in one data frame with another with a cumulative sum
<p>I have 2 data frames as shown below. I need a resultant data which has the cumulative sums of periods of data frame 1 divided by cumulative sum of periods of data frame 2 in python indexed at pin, site and department.</p> <h2>Dataframe 1:</h2> <pre><code> Pin Site Department Period1 Period2 Period3...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> for align indices in division by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow noreferrer"><code>...
python|pandas|numpy
1
371,881
50,622,525
Which TensorFlow and CUDA version combinations are compatible?
<p>I have noticed that some newer TensorFlow versions are incompatible with older CUDA and cuDNN versions. Does an overview of the compatible versions or even a list of officially tested combinations exist? I can't find it in the TensorFlow documentation. </p>
<p><strong>TL;DR</strong>) See this table: <a href="https://www.tensorflow.org/install/source#gpu" rel="noreferrer">https://www.tensorflow.org/install/source#gpu</a></p> <h2>Generally:</h2> <p>Check the CUDA version:</p> <pre><code>cat /usr/local/cuda/version.txt </code></pre> <p>and cuDNN version:</p> <pre><code>grep ...
tensorflow|cuda|version|compatibility|cudnn
362
371,882
50,611,024
How does pandas handle duplicate index?
<p>I have two <code>pandas.Series</code> with duplicate indexes, something like this:</p> <pre><code>&gt;&gt; x = pandas.Series(range(5,10), index = ['a' for _ in xrange(5)]) &gt;&gt; y = pandas.Series(range(-5,-10, -1), index = ['a' for _ in xrange(5)]) </code></pre> <p>which look like this</p> <pre><code> x ...
<p>I think pandas ignores the index when all the values are the same. If you add another value you get a different result:</p> <pre><code>x = pd.Series(range(5,10), index = ['a' for _ in range(4)]+['b']) y = pd.Series(range(-5,-10, -1), index = ['b']+['a' for _ in range(4)]) </code></pre> <p>with </p> <pre><code>x ...
python|pandas
1
371,883
50,287,212
Open .mat (matlab data) using python
<p>I tried to import and read .mat file from Python. I have tried two ways but been unsuccessful.</p> <p>Method 1 (In Python):</p> <pre class="lang-python prettyprint-override"><code>import scipy.io as sio mat = sio.loadmat('path/tmpPBworkspace.mat') </code></pre> <p>I get a message similar to:</p> <pre><code>{'Non...
<p>You can use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html#scipy.io.loadmat" rel="noreferrer"><code>scipy.io.loadmat</code></a> for this:</p> <pre><code>from scipy import io loaded = io.loadmat('/GAAR/ustr/projects/PBF/tmpPBworkspaceH5.mat') </code></pre> <p><code>loaded</code...
python-3.x|pandas|numpy|dataframe|scipy
5
371,884
45,578,714
Matplotlib animation iterating over list of pandas dataframes
<p>I have a list of pandas DataFrames with 2 columns each. So far I have a function that, when given an index i, it takes the frame corresponding to index i and plots a graph of data from the first column against the data of the second column.</p> <pre><code> list = [f0,f1,f2,f3,f4,f5,f6,f7,f8,f9] def getGraph(...
<p>Set animate function and init to axes, figure and line:</p> <pre><code>from matplotlib import pyplot as plt from matplotlib import animation import pandas as pd f0 = pd.DataFrame({'firstColumn': [1,2,3,4,5], 'secondColumn': [1,2,3,4,5]}) f1 = pd.DataFrame({'firstColumn': [5,4,3,2,1], 'secondColumn': [1,2,3,4,5]}) ...
python|pandas|animation|matplotlib
3
371,885
45,688,994
Create new QuarterEnd column in Python Pandas
<p>I'm trying to create a new column with the calendar year's quarter end date (e.g. if today is 4 August, this quarter's end date would be 30 September).</p> <p>My DataFrame has a set of dates in a column called <code>df['dates']</code>. Sample below:</p> <pre><code>03/08/2017 26/02/2015 31/12/2012 16/04/2014 13/04/20...
<p>You can simply add <code>pd.tseries.offsets.QuarterEnd(0)</code>:</p> <pre><code>df['qdate'] = pd.to_datetime(df['date']) + pd.tseries.offsets.QuarterEnd(0) print (df) date qdate 0 03/08/2017 2017-03-31 1 26/02/2015 2015-03-31 2 31/12/2012 2012-12-31 3 16/04/2014 2014-06-30 4 13/04/2016 2016-06-3...
python|pandas|date|dataframe
6
371,886
45,538,979
Tensorflow models/slim eval_image_classifier.py Number of images evaluated wrong
<p>I followed the <a href="https://github.com/tensorflow/models/tree/master/slim" rel="nofollow noreferrer">tutorial</a> to finetune the inception model for the Flowers dataset.</p> <p>The flowers dataset has 350 validation images specified in the flowers.py file.</p> <p>But when I ran <a href="https://github.com/ten...
<p>The reason of the number of image mismatches is the input queue the program is using. It feeds values with batches. You need to set the <code>batch_size</code> and <code>num_batches</code> as per your dataset size to solve this problem. <a href="https://github.com/tensorflow/models/blob/master/slim/eval_image_classi...
machine-learning|tensorflow|neural-network|deep-learning|conv-neural-network
1
371,887
45,442,662
Pandas removing duplicate range of data
<p>Hi all I have the following dataframe:</p> <pre><code>df1 WL WM WH WP 1 low medium high premium 2 26 26 15 14 3 32 32 18 29 4 41 41 19 42 5 apple dog fur napkins 6 orange cat ...
<p>You can use:</p> <pre><code>#get index values where low a = df.index[df.iloc[:,0] == 'low'] size = 2 #all index values (without first [1:]) #min is for last rows of df for avoid select non existed values arr = [np.arange(i, min(i+size+1,len(df)+1)) for i in a[1:]] idx = np.unique(np.concatenate(arr)) print (idx) [...
python|python-3.x|pandas|dataframe
1
371,888
45,639,196
Pandas updating values in a column using a lookup dictionary
<p>I have column in a Pandas dataframe that I want to use to lookup a value of cost in a lookup dictionary. </p> <p>The idea is that I will update an existing column if the item is there and if not the column will be left blank. </p> <p>All the methods and solutions I have seen so far seem to create a new column, suc...
<p>If I understood correctly:</p> <pre><code>mask = df1['Fruits'].isin(lookupDict.keys()) df1.loc[mask, 'Cost'] = df1.loc[mask, 'Fruits'].map(lookupDict) * df1.loc[mask, 'Pieces'] Result: In [29]: df1 Out[29]: Cost Fruits Pieces 0 6 Apple 6 1 55 Banana 3 2 15 Kiwi 5 3 55 Che...
python|pandas
4
371,889
45,395,269
Numpy uint8_t arrays to vtkImageData
<p>I am attempting to take 2D images of either one or three channels and display them in VTK using <code>vtkImageActor</code>. As I understand it, the current frame to be displayed can be updated by invoking <code>SetImageData</code> on <code>vtkImageActor</code> and providing an instance of <code>vtkImageData</code>.<...
<p>A slightly more complete answer (generalizing to 1-3 channels, different datatypes).</p> <pre><code>import vtk import numpy as np from vtk.util import numpy_support def numpy_array_as_vtk_image_data(source_numpy_array): """ :param source_numpy_array: source array with 2-3 dimensions. If used, the third dim...
python|numpy|vtk
8
371,890
45,323,136
TensorFlow object detection error when training
<p>Hej Guys ! </p> <p>I am trying to run locally the cat example and I got stuck on the trainning step. I get this very long error. Could someone help me out to understand what is wrong ? </p> <p>Thanks in advance. </p> <p>The command: bertalan@mbqs:~/tensorflow/models$ python object_detection/train.py --logtostderr...
<p>Your checkpoint model and feature extracting model is different.</p>
object|tensorflow|detection
2
371,891
45,587,242
What numpy dtypes h5py accepts?
<p>I am serializing a Python dictionary with numpy types to an H5 file.</p> <p>generally, the code is </p> <pre><code>for key, value in dict.items(): if isinstance(value, str): f.attrs[key] = value.encode('utf-8') elif isinstance(value, XXXXXX): param_dset = f.create_dataset(key, value.shape, ...
<p>From the h5py documentation:</p> <p>Fully supported types:</p> <pre><code>Type Precisions Notes Integer 1, 2, 4 or 8 byte, BE/LE, signed/unsigned Float 2, 4, 8, 12, 16 byte, BE/LE Complex 8 or 16 byte, BE/LE Stored as HDF5 struct...
python|numpy|h5py
2
371,892
45,395,798
Tensorflow - training weights via GD by hand
<p>I am new to Tensorflow and I want to train a toy neural network to solve the xor problem. I want to be able to pass in two bits as inputs and have 1 bit as an output. I will have 4 training examples: <code>[0,0], [0,1], [1,0], [1,1]</code></p> <p>I understand how the forward feed works but I do not exactly know how...
<p>In the usual approach, you use dimension 0 as the batch dimension. You are doing this for <code>x</code> in <code>x_vals = np.array([[1.0, 0.0], [0.0,0.0]])</code> (assuming <code>(1,0)</code> and <code>(0,0)</code> are your two training examples for <code>x</code>). You write your graph operations in such a way tha...
tensorflow
0
371,893
45,533,496
How do you slice a DF using .loc with a list which might have elements not found in index / column
<p>I have couple of list which might have elements that are not found in the index / columns for a DataFrame. I want to get the particular rows / columns using these indices such that the if the elements in the list is not found in the index / column then it is ignored.</p> <pre><code>df1 = pd.DataFrame({"x":[1, 2, 3,...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html" rel="nofollow noreferrer"><code>Index.intersection</code></a>:</p> <pre><code>a = ['c', 'd', 'e', 'f'] b = ['x', 'z'] print (df1.index.intersection(a)) Index(['c', 'd', 'e'], dtype='object') print (df1...
python|pandas|dataframe|indexing|slice
3
371,894
45,592,965
Using Tensorflow to set up a RNN modle, when calculating the loss with "tf.nn.ctc_loss()"
<p>Use the Tensorflow's internal method "tf.nn.ctc_loss(labels, inputs,sequence_length, preprocess_collapse_repeated=False, ctc_merge_repeated=True)" to calculate the loss, however, i occur an error.</p> <pre><code>Caused by op 'CTCLoss', defined at: File "/home/liu/PythonCode/single_deepspeech/util/data_process.py"...
<p>In the CTC model there is a blank label with value "num_classes", if that value or a higher value is included in the label you will get this error. Check your labels, and remember that a white space between words is not your blank label, but just another class (normal label).</p>
tensorflow
0
371,895
45,701,073
ImportError: libcudnn.so.5: cannot open shared object file: No such file or directory, Python 2.7 with Tensorflow-gpu
<p>Trying to enable tensorflow-gpu over python2.7 after installing Nvidia Quadro M4000. I got the below error message: Strange thing is that it's complaining about libcudnn.so.5, but I have libcudnn.so.7 in /usr/local/cuda/lib64</p> <p>Thanks for any suggestions!</p> <blockquote> <p>~$ python Python 2.7.13 |Anaco...
<p>Updating with my own solution. It turns out I installed cudnn7.0 rather than cudnn5.1. Problem solved after I install the cudnn5.1. cheers!</p>
python|ubuntu|tensorflow
0
371,896
45,548,426
Store numpy.array in cells of a Pandas.DataFrame
<p>I have a dataframe in which I would like to store 'raw' <code>numpy.array</code>:</p> <pre><code>df['COL_ARRAY'] = df.apply(lambda r: np.array(do_something_with_r), axis=1) </code></pre> <p>but it seems that <code>pandas</code> tries to 'unpack' the numpy.array.</p> <p>Is there a workaround? Other than using a wr...
<p>Use a wrapper around the numpy array i.e. pass the numpy array as list </p> <pre><code>a = np.array([5, 6, 7, 8]) df = pd.DataFrame({"a": [a]}) </code></pre> <p>Output:</p> <pre> a 0 [5, 6, 7, 8] </pre> <p>Or you can use <code>apply(np.array)</code> by creating the tuples i.e. if you have a datafr...
python|pandas|numpy|dataframe
64
371,897
45,505,738
np.split() with output from tf.nn.softmax
<p>I am using Tensorflow to do part of speech tagging. I am getting the output of a softmax layer (it uses tf.nn.softmax) this way:</p> <pre><code>pos_tags_confidences = sess.run( self.pos_tags_softmax_op, feed_dict=self.feed_dict(batch, is_test=True) ) </code></pre> <p>POS-tags confidence has a s...
<pre><code>pos_tags_confidences = pos_tags_confidences.squeeze() assert pos_tags_confidences.shape==(580, 21) split_arrays = np.split(pos_tags_confidences, [550], axis=0) </code></pre>
python|arrays|numpy|tensorflow
2
371,898
45,315,242
Transform Shape of a Pandas Dataframe
<p>I would like to transform a dataframe table like below. It is similar to reverse a one-hot encoding, but not exactly same. Is there an elegant way to do it?</p> <p>from</p> <p><a href="https://i.stack.imgur.com/TeAUh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TeAUh.png" alt="enter image des...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow noreferrer"><strong><code>pd.melt</code></strong></a></p> <pre><code>pd.melt(df, 'website_id', var_name='date').sort_values('website_id') website_id date value 0 3142 17-07-05 1.0 2 3142 17-0...
pandas|dataframe
2
371,899
45,531,290
Merging certain rows in pandas dataframe
<p>I have this dataframe, consisting in 73 rows:</p> <pre><code>Date Col1 Col2 Col3 1975 float float float 1976 float float float 1976 float float float 1977 float float float 1978 float float float .... .... </code></pre> <p>There are certain years appearing twice because the values ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby()</code></a> and then <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mean.html" rel="nofollow noreferrer"><code>mean()</code></a> for th...
python|python-2.7|pandas|dataframe
1