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
3,100
46,474,393
Quantile threshold/filter within pandas groupby
<p>I have one categorical variable and two numeric cols:</p> <pre><code>np.random.seed(123) df = pd.DataFrame({'group' : ['a']*10+['b']*10, 'var1' : np.random.randn(20), 'var2' : np.random.randint(10,size=20)}) </code></pre> <p>I want to find, by <code>group</code>, the mean ...
<p>Are you looking for this ?</p> <pre><code>new = df.groupby('group').apply(lambda x : \ x[x.var2&gt;=x.var2.quantile(0.75)] \ .var1.mean()).to_frame() </code></pre> <pre> 0 group a -1.471336 b 0.155121 </pre>
python|pandas|pandas-groupby|split-apply-combine
5
3,101
58,554,905
Difference between max and min value of columns
<p>I have a pandas dataframe with 2000+ columns. All the columns have numeric values. I want to find the difference between minimum and maximum values of each column. And then I want to filter top 10 columns having biggest differences.</p> <pre><code>Col1 Col2 Col3 ..... Col2500 4 1 3 ..... 6 7 5 10...
<p>This will give you the result in <code>Series</code>:</p> <pre><code>df.T.apply(lambda x: x.max() - x.min(), axis=1).nlargest(10) </code></pre> <p>Example:</p> <pre><code>df Col1 Col2 Col3 Col2500 0 4 1 3 6 1 7 5 10 17 2 1 22 4 2 df.T.apply(lambda x: x...
python|pandas
1
3,102
58,565,389
Install Anaconda along with Spyder and Tensorflow on Windows 7 PC that doesn't have internet connectivity
<p>I'm in need of installing Anaconda along with Spyder and Tensorflow on a Windows 7 laptop that does not have a connection to the internet. Is this possible and if so, would there be directions on how to do this?</p> <p>Thanks...</p>
<p>From <a href="https://docs.anaconda.com/anaconda/install/" rel="nofollow noreferrer">https://docs.anaconda.com/anaconda/install/</a>:</p> <blockquote> <p><strong>Installing Anaconda on a non-networked machine (air gap)</strong></p> <p>Obtain a local copy of the appropriate Anaconda installer for the non-ne...
python|tensorflow|anaconda|spyder|windows-7-x64
1
3,103
69,002,340
How to create a Data frame and prevent creation of new columns and additional rows during a for loop for each dataset
<p>I'm new to posting here.</p> <p>I'm currently trying to extract tables from a word document and have them laid out in a transposed data frame that can be exported as a csv.</p> <p>My issue lies on the data frame I get from the following code:</p> <pre><code>from docx.api import Document import pandas as pd def extr...
<p>Your data is organized &quot;vertically&quot; with the records in columns rather than rows. So you need something like this:</p> <pre><code>from docx.api import Document import pandas as pd def extract_tables_from_docx(path): document = Document(path) data = [] for table in document.tables: ke...
python|python-3.x|pandas|dataframe|python-docx
0
3,104
44,762,525
How to save the result from equation(float) to column, python
<p>I have data frame look line this:</p> <p><code>df:</code></p> <pre><code> 1 2 3.4 -2 2 1.1 2 3 4 -5 5 5 </code></pre> <p>I can use this data on my equation like:</p> <p><code>result=abs(int(df[0])) +( int(df[1]) / 2 + float(df[2]) / 32)</code></p> <p>So after this calculation I receive a list with results for ...
<p>Assign directly to the new column you're trying to create.</p> <pre><code>df[3] = abs(int(df[0])) +( int(df[1]) / 2 + float(df[2]) / 32) </code></pre>
python|pandas|dataframe
4
3,105
44,372,638
pandas / numpy np.where(df['x'].str.contains('y')) vs np.where('y' in df['x'])
<p>As a newb to python and pandas, I tried:</p> <pre><code>df_rows = np.where('y' in df['x'])[0] for i in df_rows: print df_rows.iloc[i] </code></pre> <p>returned no rows, but</p> <pre><code>df_rows = np.where(df['x'].str.contains('y'))[0] for i in df_rows: print df_rows.iloc[i] </code></pre> <p>did work an...
<p>Pandas requires specific syntax for things to work. Looking for a <code>str</code> <code>y</code> using the operator <a href="https://docs.python.org/3/reference/expressions.html#in" rel="nofollow noreferrer">in</a> checks for membership of the string <code>y</code> in a pandas <code>Series</code>.</p> <pre><code>&...
python|string|pandas|numpy|where
1
3,106
60,880,271
Pandas: Count days in each month between given start and end date
<p>I have a pandas dataframe with some beginning and ending dates. </p> <pre><code>ActualStartDate ActualEndDate 0 2019-06-30 2019-08-15 1 2019-09-01 2020-01-01 2 2019-08-28 2019-11-13 </code></pre> <p>Given these start &amp; end dates I need to count how many days in each month between beginning and ending...
<p>Idea is create month periods by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.to_period.html" rel="nofollow noreferrer"><code>DatetimeIndex.to_period</code></a> from <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="nofollow nore...
python|pandas|datetime
1
3,107
61,054,359
InvalidArgumentError: 2 root error(s) found. (0) Invalid argument: Incompatible shapes: [4,3] vs. [4,4]
<p>I am facing below error when trying to train a multi-class classification model ( 4 classes) for Image dataset. Even though my output tensor is of shape 4 I am facing below issue. Please let me know how to fix this issue.</p> <pre><code> Epoch 1/10 ----------------------------------------------------------------...
<p>I think, there is nothing wrong with the shapes, but with the loss function, you are trying to use. Ideally for multiclass classification, the final layer has to have <strong>softmax</strong> activation (for your logits to sum up to 1) and use <strong>CategoricalCrossentropy</strong> as your loss function if your la...
python|tensorflow|keras|deep-learning|multiclass-classification
0
3,108
60,870,128
Can't install geopandas in Anaconda environment
<p>I am trying to install the <code>geopandas</code> package with Anaconda Prompt, but after I use <code>conda install geopandas</code> an unexpected thing happened:</p> <pre class="lang-bash prettyprint-override"><code>Collecting package metadata (current_repodata.json): done Solving environment: failed with initial f...
<p>Install it in a new env, and include <code>ipykernel</code> if you plan to use it in Jupyter:</p> <pre><code>conda create -n my_env geopandas ipykernel </code></pre> <p>Note, <code>nb_conda_kernels</code> should be installed install in your base env (i.e. where you launch Jupyter from). This enables Jupyter to aut...
python|anaconda|conda|geopandas
14
3,109
60,845,365
Date formatting in chr when concatenating CSV files in pandas
<p>I've got an issue with the below function mergeit2. </p> <p>The function is concatenating two files together. </p> <p>A current year file and a historic file. In the historic file, the dates are in chr(10) format whilst in the current file the dates are in date format. As I'm then loading the data in Tableau, I wa...
<p>First of all, a big kudos to Serge Ballesta. You cannot imagine how many manhours of work you saved me and thank you for your kind explanations over our discussion.</p> <p>Serge mentioned:</p> <blockquote> <p>Hint: you could ask pandas to parse the dates in the current file and use <code>dt.strftime</code> to ...
python|pandas|csv|date|tableau-api
1
3,110
71,455,791
Grouping the data in python
<p>Suppose, I have the data like this,</p> <pre><code> Date Time Energy_produced 01.01.2016 00:00 500 01.01.2016 00:15 580 01.01.2016 00:30 600 01.01.2016 00:45 620 01.01.2016 01:00 580 01.01.2016 01:15 520 01.01.2016 01:30 590 01.01.2016 01:45 570 01.01.2...
<p>If you want to keep Date/Time as strings, you could use:</p> <pre><code>(df.groupby(['Date', df['Time'].str[:3].rename('Hour')+'00']) ['Energy_produced'].sum() .reset_index() ) </code></pre> <p>Output:</p> <pre><code> Date Hour Energy_produced 0 01.01.2016 00:00 2300 1 01.01.2016 01...
python|pandas|dataframe|data-analysis
0
3,111
71,782,405
Pandas dropna() not removing entire row
<p>When I serached a way to remove an entire column in pandas if there is a null/NaN value, the only appropriate function I found was dropna(). For some reason, it's not removing the entire row as intended, but instead replacing the null values with zero. As I want to discard the entire row to then make a mean age of t...
<p>you have to specify the axis = 1 and any to remove column see : <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dropna.html</a></p> <pre><code>df.dropna(axis=1, inplace= True, how='any') </cod...
python|python-3.x|pandas
3
3,112
69,854,674
Python generate lat/long points from address
<p>How do I take addresses and generate lat, long coordinates from them in python? I have a few addresses that I would like get lat, long points but seems it doesn't work.</p> <p>I used geopandas but it returns me nothing. I am also a bit confused about what to use for the <strong>user_agent</strong>. Here is my code,<...
<p>You can use <code>apply</code> directly on a DataFrame column:</p> <pre><code>import pandas as pd from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent=&quot;myApp&quot;) df2 = pd.DataFrame({'Location': ['2094 Valentine Avenue,Bronx,NY,10457', '1123 East Tremont Avenue,Br...
python|pandas|latitude-longitude|geopandas|geopy
4
3,113
69,914,296
How to find each row and column data type in pandas dataframe using apply, map or applymap?
<p>I have dataframe as shown in image. I want each row and columns data type using apply/map/applymap. How to get this datatype? Some columns have mixed datatype as highlighted e.g. list and str, some have list and dict.</p> <p>[![samplepandasdataframe][1]][1]</p> <p>[1]:</p>
<p>If you want to have the evaluated type value of every cell you can use</p> <pre><code>def check_type(x): try: return type(eval(x)) except Exception as e: return type(x) df.applymap(check_type) </code></pre> <p>If you want to also get how many datatypes you have you can use things like</p...
python|pandas|dataframe|complex-data-types
5
3,114
43,321,814
How to vectorize fourier series partial sum in numpy
<p>Given the Fourier series coefficients <code>a[n]</code> and <code>b[n]</code> (for cosines and sines respectively) of a function with period <code>T</code> and <code>t</code> an equally spaced interval the following code will evaluate the partial sum for all points in interval <code>t</code> (<code>a</code>,<code>b<...
<p>Here's one vectorized approach making use <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> to create the <code>2D</code> array version of cosine/sine input : <code>2*pi*n*t/T</code> and then using <code>matrix-multiplication</code> with ...
python|numpy|fft|vectorization|series
3
3,115
43,127,996
How get latitude and longitude through address without too many requests error in python
<p>I have a database contains 5000 building approx, I want to locate them through its address, so I use GeoPy like this:</p> <pre><code>def getLalo(address): geolocator = Nominatim() location = geolocator.geocode(address) if location == None: return [0,0] return [location.latitude,location.long...
<p>When you send requests in short of time, rate-limiting must be taken into account.</p> <p>You will receive: Too Many Requests 429 HTTP error or timing out.</p> <p>Try with RateLimiter </p> <pre><code>from geopy.extra.rate_limiter import RateLimiter geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1) ...
python|pandas|geopy
0
3,116
72,166,401
Adding rows of values to a dataframe in new columns, based on values in existing columns
<p>Columns that I already have saved as a dataframe: 'date', 'high', 'close,' 'target,' and 'portion'</p> <p>I am trying to create columns 'capital,' 'trade,' 'quantity,' and 'gain_loss' to the existing dataframe by performing operations row by row.</p> <p>I'm trying to:</p> <ol> <li>Start with a value of 1000 for cap...
<p>As I can see there is a problem with the conditional &quot;if&quot;. In that line, you are comparing the whole column, not just the rows' values.</p> <p>On the other hand, maybe you need to set some initial conditions in first row. And add some controls to your loop.</p> <pre class="lang-py prettyprint-override"><co...
python|pandas|dataframe
0
3,117
50,448,034
Reshuffle tensor according to other specific tensor in Tensorflow
<p>Given certain tensors <code>a</code> and <code>b</code> where <code>b</code> is of type <code>uint</code> and <code>max(b) &lt; len(a)</code>, I would like to get a tensor <code>c</code>:</p> <pre><code>c = a[b] </code></pre> <p>This would essentially reshuffle tensor <code>a</code> according to order given by <co...
<p>Just to close the question - as per @jdehesa 's comment:</p> <pre><code>c = tf.gather(a, b) </code></pre> <p>This was exactly needed. Thanks @jdehesa!</p>
python|tensorflow
0
3,118
50,261,680
Issues concerning 'brew link numpy'
<p>Dear Stackoverflow community,</p> <p>I have a problem with <code>brew link numpy</code>. I have installed the latest python but it still uses python 2.7. With the error logs shown below, with what ever way I did, I'm still stuck here. Furthermore, I have a problem installing opencv functionalities with the current ...
<p>If you have 2 different versions of python you should create a virtual environment for each flavor of python.</p> <p>If python 3.6 was installed using Anaconda, search the Anaconda documentation for creating virtual environment.</p> <p>If you installed python 3.6 another way, there are unix commands to create virt...
python|macos|numpy|homebrew
0
3,119
45,292,014
Placeholder settings for a simple neural network
<p>My data is the following CVS file:</p> <pre><code>1,0 2,0 3,0 4,0 5,1 6,0 7,1 8,1 9,1 10,1 </code></pre> <p>I want to perform logistic regression on this with the first column as x and the second column as y. Furthermore, I want to do this using TensorFlow with a simple neural network consisting of a single input ...
<p>I see where you are confused about (if you know how logistic regression works).<br> 1. For this single-dimension logistic regression setting, you just need <code>tf.placeholder(tf.float32, [1])</code>, as @Eric mentioned.<br> 2. If a placeholder is set to have shape <code>[None, dim]</code>, it means the data batch ...
tensorflow|placeholder|logistic-regression
0
3,120
45,482,755
Compare headers of dataframes in pandas
<p>I am trying to compare the headers of two pandas dataframes and filter the columns that match. df1 is my big dataframe with two headers, df2 is sort of a dictionary where I have saved every column header I will need from df1.</p> <p>So if df1 is something like this:</p> <pre><code> A B C ...
<p>Here's are couple of methods, for given <code>df1</code> and <code>df2</code></p> <pre><code>In [1041]: df1.columns Out[1041]: Index([u'A', u'B', u'C', u'D'], dtype='object') In [1042]: df2.columns Out[1042]: Index([u'B', u'D', u'E'], dtype='object') </code></pre> <p>Columns in both <code>df1</code> and <code>df2...
python|python-3.x|pandas
29
3,121
62,866,152
NaN Values inputed into test and train data
<p>I am working on a Data Science project with the Fifa dataset. I cleaned the data and took care of any NaN values in the Data to get it ready to be split into test and train. I need to use StratifiedShuffleSplit in order to split the data. Updated to a cleaner way to divided the value data into groups, but I am still...
<p>Here's one solution.</p> <pre><code>import numpy as np import pandas as pd n = 100 folds = 3 # Make some data df = pd.DataFrame({'id':np.arange(n), 'value':np.random.lognormal(mean=10, sigma=1, size=n)}) # Sort by value df.sort_values('value', ascending=False, inplace=True) # Insert 'group' ids, 0, 0, 0, 1, 1, 1...
python|pandas|data-science|linear-regression|sklearn-pandas
0
3,122
54,301,388
Saving an image as numpy array
<p>I am not able to load images into numpy array and getting an error like this...</p> <blockquote> <p>ValueError: could not broadcast input array from shape (175,217,3) into shape (100,100,3)</p> </blockquote> <p>The function code:</p> <pre><code>import cv2 import numpy as np import os train_data_dir = '/home/...
<p><code>opencv2</code> already returns a numpy array. Don't make a new one, especially not one with an additional level of nesting:</p> <pre><code>img = cv2.imread(os.path.join(train_data_dir, label, image_name), cv2.IMREAD_COLOR) img = cv2.resize(img, (100, 100)) </code></pre>
python|image|numpy|opencv|multidimensional-array
1
3,123
54,578,809
Simple workable example of multiprocessing
<p>I am looking for a simple example of python <code>multiprocessing</code>.</p> <p>I am trying to figure out workable example of python <code>multiprocessing</code>. I have found an example on breaking large numbers into primes. That worked because there was little input (one large number per core) and lot of computi...
<p>This doesn't directly answer your question but if you were using RxPy for reactive Python programming you could check out their small example on multiprocessing: <a href="https://github.com/ReactiveX/RxPY/tree/release/v1.6.x#concurrency" rel="nofollow noreferrer">https://github.com/ReactiveX/RxPY/tree/release/v1.6.x...
python|numpy|multiprocessing
1
3,124
54,437,822
RuntimeError: empty_like method already has a docstring
<p>I am working on a project that was developed using python 3.6 and I am using python 3.7 instead. I tried to run the tests that passed. However in the end I got a series of errors like this one:</p> <pre><code>Error in atexit._run_exitfuncs: Traceback (most recent call last): File "&lt;frozen importlib._bootstrap&...
<p>According to Numpy's Github issues page, the errors the OP reported, as well as the other errors reported by the commenters were known Numpy bugs, that seem to have been solved by now.</p>
python|python-3.x|numpy|python-3.6|python-3.7
1
3,125
73,697,322
How to convert column values into new columns showing frequency
<p>I created a new dataframe by splitting a column and expanding it.</p> <p>I now want to convert the dataframe to create new columns for every value and only display the frequency of the value.</p> <p>I wrote an example below.</p> <p>Example dataframe:</p> <pre><code>import pandas as pd import numpy as np df= pd.Data...
<p>Based on the description of what you want, you would need a <code>crosstab</code> on the reshaped data:</p> <pre><code>df2 = df.reset_index().melt('index') out = pd.crosstab(df2['index'], df2['value'].str.lower()) </code></pre> <p>This, however, doesn't match the provided output.</p> <p>Output:</p> <pre><code>value...
python|pandas|dataframe|split|pivot
0
3,126
73,825,612
Why is dataframe.sum(axis=0) getting NAN's when every value in every column is a real number?
<p>All column values in the selected <code>measure_cols</code> of the <code>dfm</code> DataFrame are real numbers - in fact all are between <code>[-1.0..1.0]</code> inclusive.</p> <p>Following gives <code>False</code> for all Series/Columns in the <code>dfc</code> dataframe</p> <pre><code>[print(f&quot;{c}: {dfc[c].has...
<p>Oh I made the mistake of using <code>axis=0</code> intending to do <code>row</code> sums. But it's <code>axis=1</code> to do row sums. I will never agree with that decision on polarity.</p>
python|pandas
0
3,127
73,613,153
Set all values between 2 ranges in numpy array to certain value
<p>I have 2 1d arrays of type int and a start and a stop value that look like this:</p> <pre><code>y_start = #some number y_end = #some number x_start = #some array of ints x_end = #some array of ints </code></pre> <p>What I want is to simulate the following behavior without loops:</p> <pre><code>for i, y in enumerate(...
<p>You can use indexing and a crafted boolean arrays converted to integer:</p> <pre><code>v = np.arange(arr.shape[0])[:,None] # conversion to int is implicit arr[:, y_start:y_end] = ((v&gt;=x_start) &amp; (v&lt;x_end))#.astype(int) </code></pre> <p>output:</p> <pre><cod...
python|arrays|numpy
3
3,128
71,215,246
ValueError: Incompatible indexer with Series while adding date to Date to Data Frame
<p>I am new to python and I can't figure out why I get this error: ValueError: Incompatible indexer with Series.</p> <p>I am trying to add a date to my data frame.</p> <p>The date I am trying to add:</p> <pre><code>date = (chec[(chec['Día_Sem']=='Thursday') &amp; (chec['ID']==2011957)]['Entrada']) date </code></pre> <p...
<p>Try <code>date.iloc[0]</code> instead of <code>date</code>:</p> <pre><code>rep.loc[2039838,'Thursday'] = date.iloc[0] </code></pre> <p>Because <code>date</code> is actually a Series (so basically like a list/array) of the values, and <code>.iloc[0]</code> actually selects the value.</p>
python|pandas|date|valueerror
0
3,129
71,166,840
Return mask from numpy isin function in 1 dimension
<p>I am trying to use numpy's function isin to return a mask for a given query. For example, let's say I want to get a mask for element 2.1 in the numpy array below:</p> <pre><code>import numpy as np a = np.array( [ [&quot;1&quot;, &quot;1.1&quot;], [&quot;1&quot;, &quot;1.2&quot;], [&quot;...
<p>If you want the rows that &quot;2.1&quot; appears in <code>a</code>, you want the <code>any</code> method on axis:</p> <pre><code>&gt;&gt;&gt; np.isin(a, &quot;2.1&quot;).any(axis=1) array([False, False, True, False, True, True, False, False]) </code></pre> <p>If you want the indexes of where &quot;2.1&quot; appe...
python|numpy|isin
2
3,130
71,380,792
Pandas groupby two columns, one by row and another by column
<p>I have a csv file that contains n rows of sales of houses.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">House</th> <th style="text-align: center;">House_type</th> <th style="text-align: center;">Sale_year</th> </tr> </thead> <tbody> <tr> <td style="text-ali...
<p>You can achieve the same using get_dummies method of pandas. It basically creates multiple columns for a categorical column and fills it with values.</p> <pre><code>df = pd.DataFrame({'House_type':['Semi','Flat','Bungalow','Semi','Semi'],'sale_year':[2010,2011,2012,2013,2013]}) df_final = pd.get_dummies(df,columns=[...
python|jupyter-notebook|pandas-groupby
3
3,131
71,306,892
How to group columns based on unique values from another columns in pandas
<p>Let's say I have a pandas dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">brand</th> <th style="text-align: center;">category</th> <th style="text-align: right;">size</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">nike</td> <td style="...
<p>Maybe their is a little error in the size from the example (mean is 9 instead of 10.5), but a solution might be :</p> <pre class="lang-py prettyprint-override"><code>df.groupby(['brand'], as_index=False).agg({'category': list, 'size': 'mean'}) </code></pre> <p>Output :</p> <pre><code> brand category ...
pandas|dataframe
1
3,132
71,377,763
Plot a dataframe based on index values only
<p>I have a simple question. I have a dataframe with multiple columns for date and 2 index rows like this:</p> <p><a href="https://i.stack.imgur.com/rgVg3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rgVg3.png" alt="enter image description here" /></a></p> <p>I wish to plot this given dataframe as...
<p>With a DataFrame like this:</p> <pre class="lang-py prettyprint-override"><code>data = pd.DataFrame(data = {'2021-01-01': [0,1], '2021-01-02': [2.3, 2.4], '2021-01-03': [3.1, 4.2]}, index=['ptf', 'bmk']) data.columns = pd.to_datetime(data.colu...
python-3.x|pandas|matplotlib
1
3,133
71,329,493
Pandas: winsorize feature outliers for each group
<p>I am having dataframe with 100 features and I want to winsorize outliers for each 'group'. You can use the following code to generate the dataframe.</p> <pre><code>import numpy as np import pandas as pd from scipy.stats import mstats data = np.random.randint(1,999,size=(500,101)) cols = [] for i in range(101): ...
<p>There must be a more elegant way than this, but it seems to work for me and it's just a tiny addition to your solution:</p> <pre><code>for col in df.columns: for group in df.group.unique(): df[col][df.group==group] = mstats.winsorize(df[col][df.group==group], limits=[0.01, 0.01]) </code></pre> <p>As you ...
python|pandas|dataframe|pandas-groupby
1
3,134
52,048,757
How to split every sentence into individual words and average polarity score per sentence and append into new column in dataframe?
<p>I can successfully split a sentence into its individual words and take of every average of the polarity score of every word using this code. It works great. </p> <pre><code>import statistics as s from textblob import TextBlob a = TextBlob("""Thanks, I'll have a read!""") print(a) c=[] for i in a.words: ...
<p>I have the impression the sentiment polarity only works on TextBlob type.</p> <p>So my idea here is to split the text blob into words (with the split function -- see doc <a href="https://textblob.readthedocs.io/en/dev/api_reference.html#textblob.blob.WordList" rel="nofollow noreferrer">here</a>) and convert them to...
python|pandas|dataframe|nlp|textblob
1
3,135
72,728,456
Clip value of cumprod during calculation
<p>Say I have the following dataframe</p> <pre class="lang-py prettyprint-override"><code>x = pd.DataFrame({'value': [1.0, 1.1, 1.1, 1.1, 1.2, 1.0, 0.9, 1.9, 1.7, 0.8, 0.5, 0.3]}) </code></pre> <p>and I want to calculate the cumulative product without the value ever going below <code>1.0</code> or above <code>3.0</code...
<p>This type of cacluation is very difficult / impossible to vectorize using pandas/numpy, but you could use <a href="https://numba.readthedocs.io/en/stable/index.html" rel="nofollow noreferrer"><code>numba</code></a>:</p> <pre><code>@njit def mycumprod_numba(values, start, low, high): products = np.empty_like(valu...
python|pandas|numpy
3
3,136
72,590,955
Merging multiple csv files(unnamed colums) from a folder in python
<pre><code>import pandas as pd import os import glob path = r'C:\Users\avira\Desktop\CC\SAIL\Merging\CISF' files = glob.glob(os.path.join(path, '*.csv')) combined_data = pd.DataFrame() for file in files : data = pd.read_csv(file) print(data) combined_data = pd.concat([combined_data,data],axis...
<p>For the header problem while reading csv , u can do this:</p> <pre><code>pd.read_csv(file, header=None) </code></pre> <p>While dumping the result u can pass list containing the header names</p> <pre><code>df.to_csv(file_name,header=['col1','col2']) </code></pre>
python|pandas|csv|merge|directory
1
3,137
72,688,258
Pinv not inverting my complex matrix entirely correct
<p>I have quite an extensive code so I'm not sure how I can share it and it be easy for you to read but my main question concerns the pinv function in numpy.linalg. I am inverting a non-square complex matrix. Upon inverting I find myself with absolute values that are correct but the real or the complex (always one is i...
<p>I wrote a code about it without using <code>np.linalg.pinv</code>. it worked fine.</p> <p>it is my code:</p> <p>X and Y are my matrix</p> <pre><code>Xt = np.transpose(X) X1 = np.matmul(Xt,X) X2 = np.matmul(X,Xt) try: Xinv = np.linalg.inv(X1) W = np.matmul(Xinv,Xt) print(&quot;1&quot;) except: ...
python|numpy|matrix-multiplication|complex-numbers
1
3,138
59,827,696
pandas schema validation with specific columns
<p>I have a pandas dataframe with almost 56 columns and 120000 row.</p> <p>I would like to implement validation only on some columns and not for all of them.</p> <p>I followed article at <a href="https://tmiguelt.github.io/PandasSchema/" rel="nofollow noreferrer">https://tmiguelt.github.io/PandasSchema/</a></p> <p>W...
<p>As Yuki Ho mentioned in his answer, by default you have to specify as many columns in the schema as your dataframe.</p> <p>But you can also use the <code>columns</code> parameter in <code>schema.validate()</code> to specify which columns to check. Combining that with <code>schema.get_column_names()</code> you can d...
pandas|validation|schema
4
3,139
59,695,656
Find out the difference in two dataframe with same column pandas
<p>I have three dataframe as shown below</p> <p>df1:</p> <pre><code>Unit_ID Price 1 10 2 20 3 10 </code></pre> <p>after one day df1 is updated as df2 as shown below.</p> <p>df2:</p> <pre><code>Unit_ID Price 1 10 2 20 3 10 4...
<p>For each day is necessary copy <code>DataFrame</code> to new one:</p> <pre><code>df1 = df.copy() </code></pre> <p>and after adding new rows you can use test membership by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></...
pandas|pandas-groupby
1
3,140
59,662,725
Find Consecutive Repeats of Specific Length in NumPy
<p>Say that I have a NumPy array:</p> <pre><code>a = np.array([0, 1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9, 9, 10, 11, 12, 13, 13, 13, 14, 15]) </code></pre> <p>And I have a length <code>m = 2</code> that the user specifies in order to see if there are any repeats of that length within the time series. In this case, the re...
<p><strong>Approach #1</strong></p> <p>We could leverage <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html" rel="nofollow noreferrer"><code>1D convolution</code></a> for a vectorized solution -</p> <pre><code>def consec_repeat_starts(a, n): N = n-1 m = a[:-1]==a[1:] return ...
python|numpy
2
3,141
32,244,019
How to rotate x-axis tick labels in a pandas plot
<p>With the following code:</p> <pre><code>import matplotlib matplotlib.style.use('ggplot') import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]}) df = df[["celltype","s1","s2"]] df.set_index(["celltype"],inplace=True) df.plot...
<p>Pass param <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html" rel="noreferrer"><code>rot=0</code></a> to rotate the xticklabels:</p> <pre><code>import matplotlib matplotlib.style.use('ggplot') import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({ 'cellt...
python|pandas|matplotlib
264
3,142
40,416,056
How to download previous version of tensorflow?
<p>For some reason, I want to use some previous version of tensorflow('tensorflow-**-.whl', not source code on github) and where can I download the previous version and how can I know the corresponding <code>cuda version</code> that is compatible.</p>
<p>It works for me, since I have 1.6</p> <pre><code>pip install tensorflow==1.5 </code></pre>
tensorflow
55
3,143
61,755,445
How do I iterate a function on two sides in python?
<p>I have a list called 'y' that is composed of the lowest chi squared values in a data table. So my list of y looks something like </p> <blockquote> <p>y = [0.014, 0.048, 3.53, 3.61, 9.08, 12.93, 13.15, 25.03, 26.55, 27.14]</p> </blockquote> <p>I also have a list called "chi2".</p> <p>In this list, I look for the...
<p>You need the left-hand side to be some kind of data structure supporting assignment to its elements, as many elements as you have in <code>y</code>.</p> <p>For example, adapting your idea with a <code>list</code>:</p> <pre><code>indices = [] for i in arange(0, 9, 1): indices[i] = np.where(chi2 == y[i]) </code...
python|numpy
2
3,144
61,707,434
How do I rank rank values from a very large csv excel file when I only need a few data points from the file?
<p>I uploaded an incredibly large Excel file as such </p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("C:\\Users\\willi\\Downloads\\Formatted Corona Virus Data.csv") index = ['ARG', 'BOL', 'CHL', 'COL', 'CRI', 'CUB', 'ECU', 'PAN', 'PER', 'PRY'] </code></pre> <p>and it looks like ...
<p>How about</p> <p><code>df[df.iso_code.isin(index)].groupby(['index','date']).total_cases.rank()</code>?</p>
python|excel|pandas|csv|matplotlib
0
3,145
61,738,530
Indexing with Boolean arrays
<pre><code>a = np.arange(12).reshape(3,4) b1 = np.array([False,True,True] b2 = np.array([True,False,True,False]) a[b1,b2] </code></pre> <p>output: </p> <pre><code>array([4,10]) </code></pre> <p>I am not getting how it comes 4 and 10 in a[b1,b2]</p>
<p>Apparently you expected to see <code>array([[ 4, 6],[ 8, 10]])</code>.</p> <p>In boolean indexing NumPy returns only diagonal elements as described <a href="https://numpy.org/devdocs/reference/arrays.indexing.html" rel="nofollow noreferrer">here</a>:</p> <blockquote> <p>without the <code>np.ix_</code> call, onl...
python|numpy|numpy-ndarray|numpy-slicing
3
3,146
61,929,275
AttributeError: module 'tensorflow' has no attribute 'keras' in conda prompt
<p>*I try to install tensorflow and keras</p> <p>I installed tensorflow and I imported it with no errors</p> <p>Keras is installed but I can't import it *</p> <pre><code>(base) C:\Windows\system32&gt;pip uninstall keras Found existing installation: Keras 2.3.1 Uninstalling Keras-2.3.1: Would remove: c:\users\a...
<p>Thanks for all answers But I solve it I follow this tutorial with CUDA 10.1 <a href="https://towardsdatascience.com/installing-tensorflow-with-cuda-cudnn-and-gpu-support-on-windows-10-60693e46e781" rel="nofollow noreferrer">https://towardsdatascience.com/installing-tensorflow-with-cuda-cudnn-and-gpu-support-on-windo...
python|tensorflow|keras|deep-learning
0
3,147
57,865,531
custom function to merge two csv files based on common cloumn with different names
<pre><code>a,b,c 5,Ugh,wq 2,Kj,asd 3,Yu,Dx 4,Po,Cv d,e 3,8i 4,Y6 2,X09 5,m3 </code></pre> <p>Write a function that uses pandas create_result(“X.a|X.b|X.c|Y.e” , “X.a=Y.d”)</p> <p>This will create result.csv with columns from X and Y as passed as parameters as above, and column values are mapped according to the key ...
<p>You can <code>rename</code> column and merge by <code>a</code> from both <code>DataFrame</code>s:</p> <pre><code>df = pd.merge(df1,df2.rename(columns={'d':'a'}), on='a') print (df) a b c e 0 5 Ugh wq m3 1 2 Kj asd X09 2 3 Yu Dx 8i 3 4 Po Cv Y6 </code></pre>
python|pandas
0
3,148
57,982,158
ValueError: Unknown loss function:focal_loss_fixed when loading model with my custom loss function
<p>I designed my own loss function. However when trying to revert to the best model encountered during training with </p> <pre><code>model = load_model("lc_model.h5") </code></pre> <p>I got the following error:</p> <pre><code>--------------------------------------------------------------------------- ValueError ...
<p>You have to load the <code>custom_objects</code> of focal_loss_fixed as shown below:</p> <pre><code>model = load_model("lc_model.h5", custom_objects={'focal_loss_fixed': focal_loss()}) </code></pre> <p>However, if you wish to just perform inference with your model and not further optimization or training your mode...
python|python-3.x|tensorflow|keras|loss-function
38
3,149
34,168,200
Concatenating Numpy array to Numpy array of arrays
<p>I'm trying to make a for loop that each time adds an array, to the end of an array of arrays and I can't quite put my finger on how to. The general idea of the program:</p> <pre><code>for x in range(0,longnumber): generatenewarray add new array to end of array </code></pre> <p>So for example, the output o...
<p>Is this what you need?</p> <pre><code>list_of_arrays = [] for x in range(0,longnumber): a = generatenewarray list_of_arrays.append(a) </code></pre>
python|arrays|numpy
1
3,150
34,193,538
pandas Groupby after groupby
<pre><code>df = pd.DataFrame({'A': [1,2,3,1,2,3], 'B': [10,10,11,10,10,15], 'key1':['a','b','a','b','c','c'],'key2':1}) df1 = pd.DataFrame({'A': [1,2,3,1,2,3], 'B': [100,100,110,100,100,150], 'key1':['a','c','b','a','a','c'],'key2':1}) dfn = pd.merge(df,df1,on='key2') dfn_grouped = dfn.groupby('key1_y') the list(dfn_...
<p><strong>Is this what you need?:</strong></p> <pre><code>&gt;&gt; grouped = dfn.groupby(['key1_y','key1_x','A_x']) &gt;&gt; dfg = pd.DataFrame(grouped.apply(lambda x: [a for a in x.A_y])).reset_index() &gt;&gt; dfg.columns = [u'key1_y', u'key1_x', u'A_x', 'dic_values'] &gt;&gt; dfg['dic'] = [{a:b} for a,b in zip(df...
pandas
1
3,151
54,802,328
Why am I getting different values between loss functions and metrics in TensorFlow Keras?
<p>In my CNN training using TensorFlow, I am using <code>Keras.losses.poisson</code> as a loss function. Now, I like to calculate many metrics alongside that loss function, and I am observing that <code>Keras.metrics.poisson</code> gives different results - although the two are the same function.</p> <p>See here for s...
<p>This has been confirmed as a bug and fixed. For more information, see <a href="https://github.com/tensorflow/tensorflow/issues/25970" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/25970</a>.</p>
tensorflow|keras|loss-function
2
3,152
55,019,437
Getting the first 2 numbers from a value of 5 numbers and entered in a new column in pandas
<p>I've been looking for hours for a solution to this problem: I would like to sort a column consisting of 5 numbers (integers). Then I want to use the first 2 numbers of this value to make a grouping. then I want to Count that groupings.</p> <p>Is there a simple way to do that? I use that for counting:</p> <pre><cod...
<p>Convert the dtype of the column to string and use a <code>str</code>slicer , You can use:</p> <pre><code>worksheet['new_col']=worksheet['postalcolumn'].astype(str).str[:2].astype(int) </code></pre>
python-3.x|pandas|slice|pandas-groupby
1
3,153
55,003,543
Python: Converting a seconds to a datetime format in a dataframe column
<p>Currently I am working with a big dataframe (12x47800). One of the twelve columns is a column consisting of an integer number of seconds. I want to change this column to a column consisting of a datetime.time format. Schedule is my dataframe where I try changing the column named 'depTime'. Since I want it to be a da...
<p>I'm adding a new solution which is much faster than the original since it relies on pandas vectorized functions instead of looping (pandas apply functions are essentially optimized loops on the data). </p> <p>I tested it with a sample similar in size to yours and the difference is from 778ms to 21.3ms. So I definit...
python|pandas|datetime|seconds
6
3,154
54,808,848
Pandas to_sql - Increase table's index when appending DataFrame
<p>I've been working to develop a product which centers in the daily execution of a data analysis Python 3.7.0 script. Everyday at midnight it will proccess a huge amount of data, and then export the result to two MySQL tables. The first one will only contain the data relative to the current day, while the other table ...
<p>Even though Pandas has a lot of export options, its main purpose is not intented to use as database management api. Managing indexes is typically something a database should take care of. </p> <p>I would suggest to set <code>index=False, if_exists='append'</code> and create the table with an auto-increment index:</...
python|mysql|pandas|dataframe|sqlalchemy
16
3,155
49,501,538
Custom weight initialization tensorflow tf.layers.dense
<p>I'm trying to set up custom initializer to <code>tf.layers.dense</code> where I initialize <code>kernel_initializer</code> with a weight matrix I already have.</p> <pre><code>u_1 = tf.placeholder(tf.float32, [784, 784]) first_layer_u = tf.layers.dense(X_, n_params, activation=None, ke...
<p>There are at least two ways to achieve this:</p> <p>1 Create your own layer</p> <pre><code> W1 = tf.Variable(YOUR_WEIGHT_MATRIX, name='Weights') b1 = tf.Variable(tf.zeros([YOUR_LAYER_SIZE]), name='Biases') #or pass your own h1 = tf.add(tf.matmul(X, W1), b1) </code></pre> <p>2 Use the <code>tf.constant_initia...
python|python-3.x|tensorflow|deep-learning
16
3,156
49,690,794
ValueError: invalid literal for int() with base 10: '10025.0'
<pre><code>COD_CUST 10025.0 10761.0 10869.0 12361.0 </code></pre> <p>trying to convert the above column into integer as below:</p> <pre><code>mser_offus['COD_CUST']=mser_offus['COD_CUST'].astype(int) </code></pre> <p>but getting the <strong><em>following error:</em></strong></p> <blockquote> <p>Va...
<p>you may use, print (int(float(COD_CUST))) </p>
python|pandas
0
3,157
27,954,343
How to use `str.replace()` method on all columns in a scraped Pandas dataframe?
<p>I'm a Python/Pandas beginner in data analysis. I am trying to import(/scrape) a table from a Wikipedia article on letter frequency, clean it, and turn it into a data frame. </p> <p>Here's the code I used to turn the table into a dataframe called <code>letter_freq_all</code>:</p> <pre><code>import pandas as pd impo...
<p>The most succinct way to accomplish your goal is to use the str.replace() method with regular expressions:</p> <p>1) Rename columns:</p> <pre><code>letter_freq_all.columns = pd.Series(letter_freq_all.columns).str.replace('\[\d+\]', '').str.strip() </code></pre> <p>2) Replace asterisks and percent signs and conver...
python|string|pandas|dataframe|web-scraping
3
3,158
73,222,905
Pandas : Count the number of occurrence of all matched patterns in a column
<p>Say I have a dataframe</p> <pre><code>df = pd.DataFrame({ 'column_1': ['ABC DEF', 'JKL', 'GHI ABC', 'ABC ABC', 'DEF GHI', 'DEF', 'DEF DEF', 'ABC GHI DEF ABC'], 'column_2': [9, 2, 3, 4, 6, 2, 7, 1 ] }) </code></pre> <pre><code>df column_1 column_2 0 ABC DEF 9 1 GHI ABC ...
<p>You can get the desired result with your approach if you sum the <code>notna</code> instead of <code>first</code>, and then join back with the original <code>df</code></p> <pre class="lang-py prettyprint-override"><code> df.join(df['column_1'].str.extractall('(ABC)|(DEF)').notna().groupby(level=0).sum(), how='left')...
python|pandas|regex|dataframe|group-by
3
3,159
35,124,435
Finding the maximum, miniumum and nearest data in the Pandas dataframe
<p>I have the pandas data frame like below : </p> <pre><code> A B C D E 2014 132 463 52 463 413 2015 31 71 237 71 149 2016 64 138 305 138 21 2017 33 338 338 338 177 2018 20 413 413 413 187 2019 237 149 149 149 214 2020 209 21 21 21 456 2021 4 177 177 71 52 2022 169 18...
<p>If you think minimal <code>sum</code> of absolute values, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.min.html" rel="nofollow"><code>min</cod...
python-2.7|pandas
1
3,160
30,879,104
Will numpy.roots() ever return n different floats when a polynomial only has <n unique (exact) roots?
<p>I think the title says it all, but just to be specific, say I have some list of numbers named "coeffs". Assuming the polynomial with said coefficients has exactly k unique roots, will the following code ever set number_of_unique_roots to be a number greater than k?</p> <pre><code>import numpy as np number_of_uniq...
<p>Yes.</p> <pre><code>&gt;&gt;&gt; len(set(numpy.roots([1, 6, 9]))) 2 &gt;&gt;&gt; numpy.roots([1, 6, 9]) array([-3. +3.72529030e-08j, -3. -3.72529030e-08j]) </code></pre>
numpy|scipy
2
3,161
30,973,503
AttributeError: 'numpy.ndarray' object has no attribute 'A'
<p>I am trying to perform tfidf on a matrix. I would like to use gensim, but <code>models.TfidfModel()</code> only works on a corpus and therefore returns a list of lists of varying lengths (I want a matrix).</p> <p>The options are to somehow fill in the missing values of the list of lists, or just convert the corpus ...
<p><code>self.A</code> is either an <code>np.matrix</code> or <code>sparse</code> matrix. For both <code>A</code> means, return a copy that is a <code>np.ndarray</code>. In other words, it converts the 2d matrix to a regular numpy array. If <code>self</code> is already an array, it would produce your error.</p> <p>...
python|numpy|matrix|gensim
0
3,162
67,496,720
Converting Yolov4 Tiny to tflite. error:cannot reshape array of size 372388 into shape (256,256,3,3)
<p>i'm converting my custom weights file to tflite by using open source from <a href="https://github.com/haroonshakeel/tensorflow-yolov4-tflite" rel="nofollow noreferrer">https://github.com/haroonshakeel/tensorflow-yolov4-tflite</a>.</p> <p>there is no error when i convert Yolov4.weights to tflite but when i switch to ...
<p>I solved it doing 2 changes; replacing classes names and installing specific version of tensorflow-cpu (2.3.0)</p> <ol> <li>In my case I changed the <code>core/config.py</code> file at the line 14 containing the code:</li> </ol> <blockquote> <p>__C.YOLO.CLASSES = &quot;./data/classes/coco.names&quot;</p...
tensorflow|yolov4
0
3,163
34,762,463
Install Tensorflow pip wheel without internet
<p>I do not have internet access on my linux computer therefore I installed TF from source by following <a href="https://www.tensorflow.org/versions/master/get_started/os_setup.html#installing-from-sources" rel="nofollow">TensorFlow Get Started</a>.<br> I ran into a few trouble to build trainer_example due to the lack ...
<p>If you are happy to create a PIP package <strong>without TensorBoard</strong>, you should be able to avoid rewriting the Polymer dependencies by removing <a href="https://github.com/tensorflow/tensorflow/blob/03b5bef1ddbb5841aaf059a8b77267becbe8ea21/tensorflow/tools/pip_package/BUILD#L29" rel="nofollow">this line</a...
tensorflow|tensorboard|bazel
2
3,164
34,642,595
Tensorflow Strides Argument
<p>I am trying to understand the <strong>strides</strong> argument in tf.nn.avg_pool, tf.nn.max_pool, tf.nn.conv2d. </p> <p>The <a href="https://www.tensorflow.org/versions/master/api_docs/python/nn.html#max_pool" rel="noreferrer">documentation</a> repeatedly says </p> <blockquote> <p>strides: A list of ints that h...
<p>The pooling and convolutional ops slide a "window" across the input tensor. Using <a href="https://www.tensorflow.org/versions/master/api_docs/python/nn.html#conv2d"><code>tf.nn.conv2d</code></a> as an example: If the input tensor has 4 dimensions: <code>[batch, height, width, channels]</code>, then the convolutio...
python|neural-network|convolution|tensorflow|conv-neural-network
227
3,165
65,189,843
Use Image classification model trained with coco
<p>i need to work with an image classification trained with the dataset named coco. I searched on internet but i only find objects detectors.</p> <p>Anyone know pre-trained models image classification for tensorflow 2?</p>
<p>Object Detection is different from Image Classification.</p> <blockquote> <p>Object Detection algorithms act as a combination of image classification and object localization. It takes an image as input and produces one or more bounding boxes with the class label attached to each bounding box. These algorithms are ca...
tensorflow|tensorflow2.0
1
3,166
65,303,008
Bug in Neural Network with cost function rising
<p>I have been working on my first neural net, building it completely from scratch. However when printing the cost function to track the models progress it only rises, the data I am using is just 1s,0s I wanted something simple for my first model. It has one hidden layer of two tanh nodes and then outputs into a sigmoi...
<p>Apart from any other possible bugs, sigmoid(z) should be defined as:</p> <pre><code>def sigmoid(z): a = 1/(1 + np.exp(-z)) # ^ return a </code></pre>
python|numpy|deep-learning|neural-network|activation-function
-2
3,167
49,875,667
How to deal with duplicate fields in a pandas dataframe?
<p>I want to do some analysis on data I have scraped from a forum. This is the first time I'm doing something like this so it's possible that my method is wrong from the start but here is what I have at the moment.</p> <p>I have scraped 17k discussions, each of which contains a certain number of posts (for a total of ...
<p>The columns look fine to me. You can use:</p> <pre><code>df.drop_duplicates('thread_id').thread_length.plot.hist() </code></pre> <ul> <li><code>drop_duplicates</code> identifies duplicates by considering the <code>thread_id</code> column only, keeping the first occurrence (by default).</li> <li>I then take the <co...
python|pandas
2
3,168
64,069,388
Google Colab - pandas/pyplot will only accept column references not titles
<p>I've opened a Google Sheet in Colab using gspread</p> <pre><code>document = gc.open_by_url('https://docs.google.com/myspreadsheet') sheet = elem.worksheet('Sheet1') data = sheet.get_all_values() df = pd.DataFrame(data) </code></pre> <p>The document contains element data and a print of head() looks like this:</p> ...
<p>I've just figured one solution out, which I'm happy with so I'll mark this question as resolved.</p> <p>The problem seems to be from the way I was creating my dataframe:</p> <pre><code>data = sheet.get_all_values() df = pd.DataFrame(data) </code></pre> <p>If I instead use the 'Get_all_records()' function then the d...
python|pandas|matplotlib|google-colaboratory|gspread
1
3,169
63,791,464
Why does this not split the genres properly? (Python)
<p>I am trying to find the best-rated genres for this <a href="https://www.kaggle.com/isaactaylorofficial/imdb-10000-most-voted-feature-films-041118" rel="nofollow noreferrer">data set</a>. I started off splitting the genres because there were multiple genres in most rows. Then I sorted through the genres and their sco...
<p>Because there might be some spaces before or after the <code>comma</code> separating two genres, hence you need to use the regex pattern <code>\s*,\s*</code> with <code>Series.str.split</code> to properly split the <code>Genres</code>:</p> <pre><code>s = data[['Score']].assign( Genre=data['Genre'].str.split(r'\s...
python|pandas|dataframe|csv|matplotlib
2
3,170
63,777,388
how can use some(numbers) cores of cpu from all cores, with tensorflow attributes
<p>I'm trying to use the university server for my deep code, all CPU's core on the server is 64 but I have to use just 24 cores to everybody can use the server too. I try to limit my CPU resource. I search all StackOverflow to find a solution but all suggestion doesn't work for me for example downgrade tensorflow and u...
<p>If you have Admin rights on the server and its running a Version of Windows, you can simply restrict the resources via the task-manager.</p> <p>If you want to do it by code... It looks like its a bug in Tensorflow, which might be fixed, regarding to the <a href="https://github.com/tensorflow/tensorflow/issues/29968"...
python|tensorflow|deep-learning
2
3,171
46,996,261
sorting dataframe python by alphabets then by year
<p>I am trying to sort the following data frame first in alphabetical order, and within that alphabetical order I want the date (mmddyear) to be in chronological order. i.e. I have this data frame:</p> <pre><code>0 A11 01011997 1 C11 07202005 2 A12 02011997 3 B12 12102001 4 A13 10012000 5 B11 1101200...
<p>You need to sort on both fields using <code>df.sort_values(['account', 'date'])</code>. </p> <p>But you can't just sort the data frame when the date is represented as a string or an integer because in many cases you will get the wrong order, e.g. integer 1011997 sorts before 1021980 although the latter represents a...
python|pandas|sorting
1
3,172
47,003,318
Stack vectors of different lengths in Tensorflow
<p>How can I stack vectors of different length in tensorflow, e.g. from</p> <pre><code>[1, 3, 5] [2, 3, 9, 1, 1] [6, 2] </code></pre> <p>get zero-padded matrix</p> <pre><code>[1, 3, 5, 0, 0] [2, 3, 9, 1, 1] [6, 2, 0, 0, 0] </code></pre> <p>Vector count is known at definition time, but their lengths are not. Vectors...
<p>One way you can do this is like:</p> <pre><code>In [11]: v1 = [1, 3, 5] In [12]: v2 = [2, 3, 9, 1, 1] In [14]: v3 = [6, 2] In [38]: max_len = max(len(v1), len(v2), len(v3)) In [39]: pad1 = [[0, max_len-len(v1)]] In [40]: pad2 = [[0, max_len-len(v2)]] In [41]: pad3 = [[0, max_len-len(v3)]] # pads 0 to original vec...
python|tensorflow|neural-network|tensor|zero-padding
3
3,173
46,877,403
numpy `rint` weird behavior
<p>This question is about <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.rint.html" rel="nofollow noreferrer"><code>numpy.rint</code></a>, which by definition rounds to the nearest integer. However, the following code produces inconsistent results.</p> <pre><code>In [1]: import numpy as np ...
<p>Since the near-universal adoption of the IEEE 754 standard, numeric functions have flocked to "round half to even" rounding, a description of which can be found on the same Wikipedia page you linked to, but <a href="https://en.wikipedia.org/wiki/Rounding#Round_half_to_even" rel="nofollow noreferrer">a bit down</a>.<...
python|python-3.x|numpy
5
3,174
32,697,958
Is there a way to track which DataFrame Column corresponds to which Array Column(s) after LabelBinarizer Transform in sklearn?
<p>I have a series of variables of string type and I have to transform them in order to use sklearn estimators. </p> <p>I'm using DataFrameMapper from the library sklearn_pandas. </p> <p>In the following example I have a dataframe with columns A,B,C,D,E. Suppose that 'A', 'B' &amp; 'C' are string features: A has 25 u...
<p>Combining DictVectorizer() and mapper it is possible to keep track the column variable names. This is useful if one wants to visualize a DecisionTree with export_graphviz.</p> <p>The answer is based on: <a href="http://nbviewer.ipython.org/github/rasbt/pattern_classification/blob/master/preprocessing/feature_encodi...
python|pandas|machine-learning|scikit-learn|sklearn-pandas
2
3,175
38,576,674
Neo4j Bolt StatementResult to Pandas DataFrame
<p>Based on example from <a href="https://neo4j.com/developer/python/" rel="nofollow">Neo4j</a> </p> <pre><code>from neo4j.v1 import GraphDatabase, basic_auth driver = GraphDatabase.driver("bolt://localhost", auth=basic_auth("neo4j", "neo4j")) session = driver.session() session.run("CREATE (a:Person {name:'Art...
<p>The best I can come up with is a list comprehension similar to yours, but less verbose:</p> <pre><code>df = pd.DataFrame([r.values() for r in result], columns=result.keys()) </code></pre> <p>The <a href="http://py2neo.org/v3/" rel="noreferrer"><code>py2neo</code></a> package seems to be more suitable for DataFrame...
python|pandas|neo4j
9
3,176
38,812,923
how to get given value from dataframe in Pandas?
<p>Lets say a dataframe DF looks like</p> <pre><code>record_id species wgt 33321 DM 44 33322 DO 58 33323 PB 45 </code></pre> <p>If I wanted to get the value for <code>wgt</code> when <code>record_id==33323</code> and <code>species=='PB'</code>, then what do we have to type in Pandas? So...
<p>try this for filter method. </p> <pre><code>DF[(DF.species=='PB') &amp; (DF.record_id==33323)]['wgt'] 2 45 Name: wgt, dtype: int64 Use this to get only value list(DF[(DF.species=='PB') &amp; (DF.record_id==33323)]['wgt'].values) [45] </code></pre>
pandas|dataframe
0
3,177
38,728,722
pandas install issues in gitlab and docker
<pre><code>Collecting numpy (from -r requirements.txt (line 21)) Downloading numpy-1.11.1.zip (4.7MB) Collecting pandas (from -r requirements.txt (line 22)) Downloading pandas-0.18.1.tar.gz (7.3MB) Complete output from command python setup.py egg_info: Download error on https://pypi.python.org/simple/numpy/...
<p><code>pip</code> is unable to verify the certificate. You need to manually say which certificate it should use to verify it.</p> <p>This should work:</p> <pre><code>pip --cert /etc/ssl/certs/DigiCert_High_Assurance_EV_Root_CA.pem install -r requirements.txt </code></pre>
python|pandas|numpy|continuous-integration|gitlab
0
3,178
38,656,284
Visible deprecation warning using boolean operation on numpy array
<p>I'm having an issue where I keep receiving a warning stating:</p> <pre><code>VisibleDeprecationWarning: boolean index did not match indexed array along dimension 0; dimension is 744 but corresponding boolean dimension is 1 </code></pre> <p>When I try to use this:</p> <pre><code>x_low = xcontacts[(xcontacts[5:6]...
<p>Thanks to @Syrtis Major for this:</p> <pre><code>x_low = xcontacts[(xcontacts[:,5] &lt;= 2000)] x_med = xcontacts[(xcontacts[:,5] &lt;= 4000)] x_med = xcontacts[(xcontacts[:,5] &gt; 2000)] x_hi = xcontacts[(xcontacts[:,5] &gt; 4000)] </code></pre>
python|arrays|numpy|boolean-operations
0
3,179
38,532,055
Numba not speeding up function
<p>I have some code I'm trying to speed up with numba. I've done some reading on the topic, but I haven't been able to figure it out 100%.</p> <p>Here is the code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np import scipy.stats as st import seaborn as sns from numba import jit...
<p>I was able to make a few changes to your code to make it so the jit version could compile completely in <code>nopython</code> mode. On my laptop, this results in:</p> <pre><code>%timeit solver_jit(200, 25) 1 loop, best of 3: 50.9 ms per loop %timeit solver_norm(200, 25) 1 loop, best of 3: 192 ms per loop </code></...
python|performance|numpy|numba
2
3,180
38,849,992
How do i change color based on value of an HTML table generated from a pd.DataFrame using to_html
<p>I have a pandas dataFrame which I am converting to an HTML table using <code>to_html()</code> however I would like to color certain cells based on values in the HTML table that I return. </p> <p>Any idea how to go about this? </p> <p>Eg: All cells in a column called 'abc' that have a value greater than 5 must appe...
<p>here is one way to do this:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,10, (5,3)), columns=list('abc')) def color_cell(cell): return 'color: ' + ('red' if cell &gt; 5 else 'green') html = df.style.applymap(color_cell, subset=['a']).render() with open('c:/temp/a.html', 'w') as f: f.write(html) <...
python|html|css|pandas
2
3,181
38,532,939
Pandas - join item from different dataframe within an array
<p>I am a first data frame looking like this</p> <pre><code>item_id | options ------------------------------------------ item_1_id | [option_1_id, option_2_id] </code></pre> <p>And a second like this:</p> <pre><code>option_id | option_name --------------------------- option_1_id | option_1_name </code></...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>apply</code></a>.</p> <p>For the record, storing lists in <code>DataFrames</code> is typically unnecessary and not very "pandonic". Also, if you only have one column, you can do this with a <cod...
python|pandas
0
3,182
38,531,670
Create pandas pivot table on new sheet in workbook
<p>I am trying to send my pivot table that I have created onto a new sheet in the workbook, however, for some reason when I execute my code a new sheet is created with the pivot table (sheet is called 'Sheet1') and the data sheet gets deleted.</p> <p>Here is my code:</p> <pre><code>worksheet2 = workbook.create_sheet(...
<p>Just use <code>margins=True</code> and <code>margins_name='Grand Total'</code> parameters when calling <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table()</a></p> <p>Demo:</p> <pre><code>In [15]: df = pd.DataFrame(np.random.randint(0, 5, size=(10, 3)...
python|pandas|dataframe|openpyxl
5
3,183
63,110,589
GridSearchCV results are not reproducable
<p>Im new to Keras and I need your professional help. I have used GridSearchCV to optmize my regression network. When i try to use the results, the newly created network is far worse in regards to the mean squared error than the one calculated by GridSearch. The GridSearchCV code:</p> <pre><code>import os import numpy ...
<p>The Output layer had its initialization weight missing:</p> <p>NN_model.add(Dense(1, kernel_initializer='he_uniform', activation='linear'))</p>
python|tensorflow|keras|grid-search
0
3,184
62,909,038
Use pandas to create multi plot in a loop?
<p>I am using the jupyter notebook to draw a bar chart, and I want to draw a pandas plots in a for loop.</p> <p>Here is my Dataframe that I want to draw a bar chart in a for loop</p> <pre><code>In[7]: test_df Lehi Boise 1 True True 2 True True 3 False False 4 True True 5 True True 6 Tru...
<p>The issue is that without extra specification, the loop is overwriting the same plotting axes. You can more explicitly create a new Axes within the loop for each plot, and map <code>df.plot</code> to those Axes:</p> <pre><code>colors = ['red', 'green'] place = ['Lehi','Boise'] for p in place: fig, ax = plt.subp...
python|pandas|matplotlib|seaborn
1
3,185
63,257,855
Pandas keep latest row and aggregate value
<p>I have a dataframe for Projects. If a project fails a test then that test is repeated at a later data and passed value updated. df_Project =</p> <pre><code>Date Project_ID TestA TestB TestC TestD 27072020 Project1 Pass Pass Pass Fail 30072020 Project1 None None None Pass </cod...
<p>You can do <code>groupby</code> with <code>max</code></p> <pre><code>out=df.groupby('Project_ID').max().reset_index() Out[115]: Project_ID Date TestA TestB TestC TestD 0 Project1 30072020 Pass Pass Pass Pass </code></pre> <p>The reason why this work</p> <pre><code>'Pass'&gt;'Fail' Out[116]: True </cod...
python|pandas
3
3,186
67,675,432
PANDAS dataframe concat and pivot data
<p>I'm leaning python pandas and playing with some example data. I have a CSV file of a dataset with net worth by percentile of US population by quarter of year. I've successfully subseted the data by percentile to create three scatter plots of net worth by year, one plot for each of three population sections. However,...
<p>I don't see the categories mentioned in your code in the csv file you shared. In order to concat dataframes along columns, you could use <code>pd.concat</code> along <code>axis=1</code>. It concats the columns of same index number. So first set the <code>Date</code> column as index and then concat them, and then aga...
python|pandas|dataframe
1
3,187
32,092,169
merge few pivot tables in pandas
<p>How I can merge two pandas pivot tables? When I try run my code I have error: keyerror</p> <blockquote> <pre><code>data_pivot= pandas.DataFrame(data.pivot_table(values = 'NR_ACTIONS', index=["HOUR", "OPID", "NAME"], columns='CONTACTED_PERSON_NEW', aggfunc='sum')) data_pivot.fillna(0, inplace=True) data2_pivot= pan...
<p>answer for my question is :</p> <pre><code>data_pivot= pandas.DataFrame(data.pivot_table(values = 'NR_ACTIONS', index=["HOUR", "OPID", "NAME"], columns='CONTACTED_PERSON_NEW', aggfunc='sum')) data_pivot.fillna(0, inplace=True) data_pivot.reset_index( inplace=True) data2_pivot= pandas.DataFrame(data2.pivot_table(val...
python|python-3.x|pandas
8
3,188
41,589,717
Finding minimum value for each level of a multi-index dataframe
<p>I have a DataFrame that looks like this:</p> <pre><code> data a b 1 1 0.1 2 0.2 3 0.3 2 1 0.5 2 0.6 3 0.7 </code></pre> <p>and I want to find the minimum value for each level of <code>a</code> ignoring the <code>b</code> level, so as an output I'm looking for something like...
<p>The simpliest is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.min.html" rel="noreferrer"><code>min</code></a> with parameter <code>level=0</code>:</p> <pre><code>print (df.data.min(level=0).reset_index(name='min')) a min 0 1 0.1 1 2 0.5 </code></pre> <p>If need output as...
python|pandas
7
3,189
41,613,767
tf.parse_example used in mnist export example
<p>I am new to tensorflow and are reading mnist_export.py in tensorflow serving example.</p> <p>There is something here I cannot understand:</p> <pre><code> sess = tf.InteractiveSession() serialized_tf_example = tf.placeholder(tf.string, name='tf_example') feature_configs = { 'x': tf.FixedLenFeature(shape=...
<p>The below mentioned code provides the simple example of using parse_example</p> <pre><code>import tensorflow as tf sess = tf.InteractiveSession() serialized_tf_example = tf.placeholder(tf.string, shape=[1], name='serialized_tf_example') feature_configs = {'x': tf.FixedLenFeature(shape=[1], dtype=tf.float32)} tf_exa...
tensorflow|tensorflow-serving
3
3,190
27,585,577
Centralising data in numpy
<p>I have matrices with rows that need to be centralised. In other words each row has trailing zeros at both ends, while the actual data is between the trailing zeros. However, I need the number of trailing zeros to be equal at both ends or in other words what I call the data (values between the trailing zeros) to be c...
<pre><code>import numpy as np def centralise(arr): # Find the x and y indexes of the nonzero elements: x, y = arr.nonzero() # Find the index of the left-most and right-most elements for each row: nonzeros = np.bincount(x) nonzeros_idx = nonzeros.cumsum() left = y[np.r_[0, nonzeros_idx[:-1]]] ...
python|numpy
3
3,191
61,328,489
Assigning values based on existing numeric values in a column in pandas
<p>I would want to implement the following logic in pandas:</p> <p>if df['xxx'] &lt;= 0 then df['xyz']== 'a'</p> <p>if df['xxx'] between 0.5 and 10.97 then df['xyz']== 'b'</p> <p>if df['xxx'] between 11 and 89.57 then df['xyz']== 'c'</p> <p>if df['xxx'] > 100 then df['xyz']== 'd'</p> <p>How can I do this in the si...
<p>Define a function and use apply method</p> <pre><code>def fun(x): if x &lt;= 0: return 'a' elif (0 &lt; x &lt;= 1000): return 'b' elif (1000 &lt; x): return 'c' np.random.seed(3) df = pd.DataFrame(dict(xxx=np.random.choice([-1, 10, 2000],1000))) df['xyz'] = df.xxx.apply(fun) d...
python|pandas
1
3,192
61,236,399
AssertionError: Number of manager items must equal union of block items # manager items: 6004, # tot_items: 6005
<p>My code:</p> <pre><code>for column_name, column_data in summary_words.iteritems(): if column_name != "summary" and column_name != "text" and column_name != "score" and column_name != "helpfulness": summary_words[column_name] = summary_words["summary"].str.count(column_name) </code></pre> <p>where summa...
<p>It is very likely that your special-use keywords, like <code>summary</code> and <code>helpfulness</code>, are colliding with words in the vocabulary you are analyzing.</p> <p>You should be able to check this pretty quickly by looking at the lengths:</p> <pre class="lang-py prettyprint-override"><code>len(summary_w...
python|python-3.x|pandas|dataframe|iteritems
5
3,193
68,818,356
Tensorflow2: How to convert string tensor to bag of words? Help needed after days of struggling
<p>I am trying to write a function that takes tensor of strings as an input and return sparse tensor of ones and zeros so that each row is a bag of words representation of one string from input.</p> <p><strong>About input</strong></p> <ul> <li>each input string is a name consisting of 1 up to 7 words</li> <li>a word oc...
<p>There is no direct method available, but there is some workaround to get to your solution using below code.</p> <pre><code>import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer import tensorflow_datasets as tfds inputs = [ &quot;one two three&quot;, &quot;three&quot;, &quot;o...
python|tensorflow|nlp|tensorflow2.0|word2vec
0
3,194
68,867,557
pandas resample nested ohlc data
<p>I have ohlc data that is contained in a 'mid' column and am not sure how to resample to keep the correct ohlc data</p> <p>Here is my data ... Columns are time, mid, volume , complete</p> <pre><code>candle_data time \ 0 2021-08-20 19:43:00+00:00 1 2021-08-20 19:44:00+00:00 2 2021-08...
<p>Convert the nested dictionaries to their own columns and then resample. Then, convert back if needed:</p> <pre><code>df[[&quot;o&quot;, &quot;h&quot;, &quot;l&quot;, &quot;c&quot;]] = df[&quot;mid&quot;].apply(pd.Series) df = df.drop(&quot;mid&quot;, axis=1) \ .set_index(&quot;time&quot;) \ .resample(&...
python|pandas
1
3,195
68,834,726
How to create a nested dataframe in pandas
<p>I am trying to create a nested json as a target</p> <pre><code>[{'id':0, name:'Albert', last_name:'Einstein', info:{'dob':1903}}, ... 'id':100000, name:'Zooey', last_name:'Deschanel;', info:{'dob':1980}} ] </code></pre> <p>I am operating with an existing json converted into a dataframe, how can I form a valid nest...
<p>Use <code>pd.json_normalize</code> and then <code>apply</code> a custom function on column &quot;dob&quot;:</p> <pre><code>import json import pandas as pd #assuming your json is stored in a file called &quot;myjson.json&quot; df = pd.json_normalize(json.loads(open(&quot;myjson.json&quot;).read())) df[&quot;dob&quot...
python|pandas|dataframe
0
3,196
36,465,746
Save several Pandas DataFrames into single Excel file
<p>I have several Pandas data frames that i would like to save into single MS Excel file, each dataframe as separate sheet in this file. Any advice more than welcome. Felix</p>
<p>You can use <code>sheet_name</code> argument of <code>to_excel</code> like below example.</p> <blockquote> <p><strong>pandas.DataFrame.to_excel</strong></p> <p>If passing an existing ExcelWriter object, then the sheet will be added to the existing workbook. This can be used to save different DataFrames to on...
excel|pandas|dataframe
2
3,197
36,674,399
How to remove duplicates in pandas?
<p>I have lots of data in excel files. I would like to concatenate these datas into one excel file by removing duplicate records according to id column information.</p> <pre><code>df1 id name date 0 1 cab 2017 1 11 den 2012 2 13 ers 1998 df2 id name date 0 11 den 20...
<p>I think you need add parameter <code>subset</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a> for filtering by column <code>id</code>:</p> <pre><code>print pd.concat([df1,df2]).drop_duplicates(subset='id')....
python|pandas
1
3,198
36,394,340
Centering a Numpy array of images
<p>I have some numpy arrays of images that I want to center (subtract the mean and divide by the standard deviation). Can I simply do it like this?</p> <pre><code># x is a np array img_mean = x.mean(axis=0) img_std = np.std(x) x = (x - img_mean) / img_std </code></pre>
<p>I don't think this is what you are trying to do.<br> Let's say we have an array like this:</p> <pre><code>In [2]: x = np.arange(25).reshape((5, 5)) In [3]: x Out[3]: array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) </...
python|arrays|numpy|computer-vision
5
3,199
53,195,614
Python: Pandas Module - Nested IF Statement that Fills in NaN (Empty Values) in a Dataframe
<p>I've created a function that tests multiple IF statements given the data in the 'Name' column. </p> <p>Criteria 1: If 'Name' is blank, return the 'Secondary_Name'. However, if 'Secondary_Name' is also blank, return the 'Third_Name'. </p> <p>Criteria 2: If 'Name' == 'GENERAL', return the 'Secondary_Name'. However, ...
<p>Consider this df</p> <pre><code>df = pd.DataFrame({'Name':['a', 'GENERAL', None],'Secondary_Name':['e','f',None], 'Third_Name':['x', 'y', 'z']}) Name Secondary_Name Third_Name 0 a e x 1 GENERAL f y 2 None None z </code></pre> <p>Since you are writing t...
python-3.x|pandas|dataframe|null
0