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
364,600
60,640,873
Creating numpy array from c-pointer crashes ipython kernel
<p>With this code I am trying to create a numpy array from a malloc'ed c pointer, inspired by a <a href="http://gael-varoquaux.info/programming/cython-example-of-exposing-c-computed-arrays-in-python-without-data-copies.html" rel="nofollow noreferrer">blog post from Gaël Varoquaux</a>.</p> <p>The line that creates the ...
<p>Before using numpy's Array API, you need to call <code>np.import_array()</code>:</p> <pre><code>%%cython -f from libc.stdlib cimport malloc import numpy as np cimport numpy as np np.import_array() cdef array_from_pointer(double* ptr, int size): cdef np.npy_intp shape_c[1] shape_c[0] = &lt;np.npy_intp&gt; ...
python|numpy|cython
0
364,601
60,627,060
Trying to pull dataframe from html table, however when I run df.info, error occurs (AttributeError: 'list' object has no attribute 'info')
<p>Excerpt from code below:</p> <pre><code>soup = BeautifulSoup(page.content, 'html.parser') souptable = soup.find(text='header').findParent('table') df = pd.read_html(str(souptable)) df.info </code></pre> <p>I am just starting out with python.</p> <p>First I am using BeautifulSoup to pull information from a webp...
<p>Basically, according to the <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.read_html.html" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>Returns:<br> dfs : list of DataFrames</p> </blockquote> <p>When you run <code>pd.read_html</code>, it returns a <em>list</em> of dat...
python|pandas|dataframe|beautifulsoup
0
364,602
60,609,722
How to load a Keras model with a custom loss function?
<p>I have created the following custom loss function:</p> <pre class="lang-r prettyprint-override"><code>RMSE = function(y_true,y_pred) { k_sqrt(k_mean(k_square(y_pred - y_true))) } </code></pre> <p>And it works fine when I saved the model. However, when I loaded the model back using:</p> <pre class="lang...
<p>Since you are using a <em>custom</em> loss function in your model, the loss function would not be saved when persisting the model on disk and instead only its name would be included in the model file. Then, when you want to load back the model at a later time, you need to inform the model of the corresponding loss f...
r|tensorflow|keras|loss-function
2
364,603
60,529,313
Combining rows based on matching columns pandas
<p>I have a csv file containing games and stats for each team for an entire season. I am wanting to move the away team into the same row as the home team it faced for that week.</p> <p>Current dataframe:</p> <pre><code> Week Team H/a Opp Pf Pa Pyards 1 A C 3 14 100 ...
<p>I believe the operation you are looking is <code>self-join</code> with some manipulation afterwards. As Quang Hoang stated, merging the same dataframe/table in different columns is called self-join. I believe this is an approach which gets the expected output:</p> <pre><code>df = pd.DataFrame({'Week':[1,1,1,1], ...
python|pandas|numpy|dataframe
1
364,604
60,607,729
Is there a better way of doing this (ideally with a single loop)
<p>i'm trying to create a pandas dataframe with the Total cryptocurrency marketcap indexed by date. Data are taekn from Coingecko API. I'm able to achieve this with:</p> <pre><code>import requests import json r = requests.get('https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&amp;days=200') ...
<p>You can use <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer"><code>list comprehensions</code></a> passed directly to the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer"><code>DataFrame</...
python|pandas|loops|dataframe|cryptocurrency
4
364,605
60,591,053
How do we split a numpy array at multiples of a number? (eg: array 1 : 0-33, array 2: 34-66, array 3: 67-100)
<p>I have been trying to split a n dimensional array. I want to split it at multiples of 100//3 (=33)</p> <p>I want to split array of length 100 into 3 groups such that group 1 is from indices 0-33 group 2 is from 34-66 group 3 is from 67-100</p> <p>This is what I tried.</p> <pre><code>numberblocks=3 array=np.arang...
<p>You can just use:</p> <pre><code>np.array_split(array, n) </code></pre> <p>to split the array <code>array</code> into <code>n</code> equal parts if possible, and if not the last split will be smaller than the rest.</p> <p>In your case,</p> <pre><code>&gt;&gt;&gt; array = np.arange(100) &gt;&gt;&gt; split_arrs = ...
python|numpy|numpy-ndarray|numpy-slicing
2
364,606
60,543,452
How to extract all data keys and values in a nested python dict
<p>I have a JSON response from an API call in python, this is of dict type and I need to extract all the keys and values by traversing through the nested dictionary. I need some help to achieve this, what could be the best approach to check whether an item in the primary dict is another dict or just a key with a single...
<pre><code>import json, pandas as pd df = pd.json_normalize(json.loads(json_data)['results']) df.head() </code></pre> <p>I finally discovered a pandas json_normalize method which does the trick. Initially, I was building a nested conditional to extract all the required feature, which could be a potential solution as w...
python|json|pandas|dictionary|multidimensional-array
0
364,607
60,574,546
Filtering a database based on the content of another
<p>So I need to assign a new dataframe of features without protected attributes; I'm provided 2 .csv's where one has all information for each instance and another which labels each column as 1 if the attribute is a protected feature, 2 if the attribute is the value to be predicted, and 0 otherwise.</p> <p>I'm not enti...
<p>You need to use <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.any.html" rel="nofollow noreferrer">any</a> with negation to find all the columns with <code>0</code> value in second dataframe (<code>df2</code>) and use that as a list of columns to fetch from <code>df1</code>:...
python|pandas
1
364,608
60,565,702
Why the inverse of the inverse of one matrix is not itself in python?
<p>Why the inverse of the inverse of one matrix is not itself in python? Why the inverse of the inverse of one matrix is not itself in python? <a href="https://i.stack.imgur.com/FVCS4.png" rel="nofollow noreferrer">code</a></p> <p><a href="https://i.stack.imgur.com/lis42.png" rel="nofollow noreferrer">code</a></p>
<p>(Deleted the previous answer, since I made a mistake copying the matrix)</p> <p>Your matrix is perfectly singular, so the inverse does not actually exist. Due to limits of numerical precision, <code>numpy.linalg.inv</code> gives you a matrix with very large values that is the inverse of another (similar) matrix.</p...
numpy
0
364,609
60,578,552
RK45 code w an error that says "index 50 is out of bounds for axis 0 with size 50"
<p><strong>Here is my code:</strong></p> <pre><code>import numpy as np import time import matplotlib as plt def fun1(t,y): f=np.exp(-6*t) return (f) def RK45Classic(h,f,t,yold): k1=h*f(t,yold) k2=h*f(t+h/2,yold+k1/2) k3=h*f(t+h/2,yold+k2/2) k4=h*f(t+h,yold+k3) ynew=yold+(1/6)*(k1+2*k2+2*k...
<p>What you implement in <code>RK45Classic</code> is the classical Heun-Kutta 4th order Runge-Kutta method, it is neither of Cash-Karp, Fehlberg nor Dormand-Prince embedded 45 methods.</p> <p>A first measure would be to try to see why that error happens, so before starting the loop put</p> <pre><code>print(t.size, t[...
python|numpy|runge-kutta
0
364,610
60,577,437
How to select and order elements of a column in python?
<p>i need the help of the community to solve an issue. Basically i have a excel database with a series of information: train number, departure date, fare, owner of the train (NTV or TRN) and the market (which station the train is going to cover). </p> <p>Now, i have created a code that filter some of those information...
<p>Not knowing exactly how your data looks like, I would suggest the following approach:</p> <ul> <li>Split your data into two dataframes - one for each of the trains: <code>df1 = data.loc[data['CXR']=='NTV']</code> and <code>df2 = data.loc[data['CXR']=='TRN']</code></li> <li>Then, merge both dataframes again using <a...
python|excel|pandas
0
364,611
60,543,598
How to replace some rows in 2-D tensors in Tensorflow
<p>Here is an example of my question.</p> <pre><code>origin_embeddings = tf.constant([[1.1,2.2,3.3], [4.4, 5.5, 6.6], [7.7, 8.8, 9.9], [10.10, 11.11, 12.12]]) # 4 * 3 indice_updated_embeddings= tf.constant([[1.0, 2.0,...
<p>If you are not using an old version of TensorFlow, you can do that with <a href="https://www.tensorflow.org/api_docs/python/tf/tensor_scatter_nd_update" rel="nofollow noreferrer"><code>tf.tensor_scatter_nd_update</code></a>:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf origin_embeddi...
python|tensorflow
1
364,612
60,730,583
Dropping values in pandas data frame using operators e.g >,<,= and etc
<p>How do i write the python code to drop certain values? E.g. I want to drop an extreme value in the data frame column. I tried to select first before dropping which failed. </p> <p>data[['Metabolic rate']>2000] also tried; data['Metabolic rate'>2000]</p> <p>TypeError Traceback (...
<p>Assuming <code>data</code> is the name of the dataframe:</p> <pre><code>data.drop(data[data['Metabolic rate'] &gt; 2000].index, inplace=True) </code></pre>
pandas
0
364,613
60,409,122
NumPy: efficiently assign a row/column to an array
<p>Let's say I want to assign two values, <code>x</code> and <code>y</code> to an existing matrix of shape <code>(100,100,2)</code>. The normal way of assigning them to a row/column would be:</p> <pre><code>my_array[row, column] = [x, y] </code></pre> <p>But I have found that the following is much more efficient:</p>...
<p>Only thing that comes to mind as an exact answer is this:</p> <pre><code>my_array[row, column, 0], my_array[row, column, 1] = x, y </code></pre>
python|numpy
0
364,614
60,605,291
Pandas dataframe grouping function to compute date difference
<p>I have a DataFrame like this:</p> <pre><code>id_a | date 12 | 2020-01-01 12 | 2020-01-02 13 | 2020-01-01 13 | 2020-01-03 14 | 2020-01-01 14 | 2020-01-02 14 | 2020-01-06 </code></pre> <p>I would like to be able to make the diff between the max date and min date of each group based on id_a To get some...
<p>You want <code>transform</code> instead of <code>apply</code>. Also <code>np.ptp</code> would do:</p> <pre><code> # convert to datetime, ignore if already is df['date'] = pd.to_datetime(df['date']) df['date_diff'] = df.groupby('id_a')['date'].transform(np.ptp) </code></pre> <p>Output:</p> <pre><code> id_a ...
python|pandas
5
364,615
60,460,196
python pandas iterating rows of two different columns and returning the repeated one once and corresponding values of repeated values in single row
<p>for instance, I have a .csv file with 1000s of rows like below:</p> <pre><code>year,name 1992,Alex 1992,Anna 1993,Max 1993,Bob 1993,Tom </code></pre> <p>so on...</p> <p>I want my output to be:</p> <pre><code> year name 1992 Alex, Anna 1993 Max, Bob, Tom </code></pre> <p>this looks simple ...
<p>You can achieve this by using groupby and aggregation. Try the below code:</p> <pre><code>df = df.groupby("year").agg({ "year":"first", "name":", ".join }) </code></pre> <p>You can save the dataframe values to csv by ignoring index </p> <pre><code>df.to_csv("output.csv",index=Fal...
python|pandas|loops|csv
3
364,616
60,457,043
Pandas dataframe change value according to condition from another filed
<p>I have a pandas dataframe <em>res</em> with 4 columns: Account, Currency, Balance LCY, Balance FCY</p> <p>i also have a dictionary <em>rates</em> that holds all different currency rates (key currency name: value rate as string) i need to change Balance LCY on accounts that the currency is not EUR to be <em>Balance ...
<p>There's simple design solution to that - you should always add your base currency to your dictionary with FX rate equal 1.</p> <p>In your case:</p> <pre class="lang-py prettyprint-override"><code>rates["EUR"]=1 erates = pd.DataFrame(list(rates.items()), columns=['Currency', 'Rate']) res = pd.merge(res, erates, ho...
python|pandas|dataframe
0
364,617
60,408,187
new column in Pandas python based on condition
<p>I am quite new to pandas, hence, I need help from you experts out there!</p> <p>I'm quite confusing on concatenation the data from a multiple row. </p> <pre><code>#copy selected row and column. Set specific column into a appropriate data type filep2 = pd.read_csv(r'/Users/syafiq/Downloads/RoutingPractice01/my_raw....
<p>Welcome to Stack Overflow.</p> <p><strong>Edited based on your file actual column name and desired column name:</strong></p> <p>I just realize you want to group them by <code>Sender</code> as well as <code>UHG</code> that starts with the same characters (how many? You didn't specify, so I just stick to 5 chars in ...
python|pandas|csv
3
364,618
60,531,162
Colormap for errorbars
<p>I am trying to match the color of the errorbars with the color of the data points using the code below but I am getting the following error</p> <p>raise ValueError("RGBA sequence should have length 3 or 4")</p> <p>ValueError: RGBA sequence should have length 3 or 4</p> <p>What I am doing wrong? Any advice would b...
<p>Thank you for the help. I managed to get it working from adapting the code (shown below) from this question <a href="https://stackoverflow.com/questions/10208814/colormap-for-errorbars-in-x-y-scatter-plot-using-matplotlib">Colormap for errorbars in x-y scatter plot using matplotlib</a></p> <pre><code>import matplot...
python|pandas|matplotlib
1
364,619
60,419,239
Openpyxl/Pandas - Convert CSV to XLSX
<p>I'm trying to convert a <code>CSV</code> file to an <code>Excel</code> file but after trying most of the suggestions from the web, the closest I got is using this piece of code:</p> <p>Input file looks like <a href="https://i.stack.imgur.com/9X8VR.jpg" rel="nofollow noreferrer">this</a></p> <pre><code>pathcsv = r'...
<p>I found the solution on this one. </p> <p>I just added the encoding param as utf-8 and it worked fine.</p> <p><code>with open(pathcsv, 'r+', encoding="utf-8") as f:</code></p> <p>Thanks everyone for your help. It was a nice first post :) </p>
python|excel|pandas|csv
0
364,620
60,547,703
Scrapy to df how to not overwrite data
<p>So, rookie here, having a Hard time to write the <strong>scraped</strong> data to a xlsx. Well, the first page, is great, the problem is that other pages overwrite previous ones. I believe that's due to Yield behavior but honestly, I can't clearly understand why.</p> <p>So as u can see in the code below, I can read ...
<p>add the sheet name for each excel sheet like so: <code>df.to_excel(writer, sheet_name=sheet_name, index=False)</code> what you are doing above is re-creating the same sheet with the same name. That will definitely overwrite the excel sheet created previously</p>
python|excel|pandas|scrapy
1
364,621
60,740,834
Parse Pandas dataframe columns to check for the same value
<p>I am working out of a huge csv file (873,323 x 271) that looks similar to what is below:</p> <pre><code>| Part_Number | Type_Code | Building_Code | Handling_Code | Price to Buy | Price to Sell | Name | |:-----------:|:-------------:|:--------------:|:-------------:|:------------:|:-------------:|:----...
<p>This looks like a custom function which splits <code>,</code> and joins it back after removing duplicates for which I have used <code>dict.fromkeys</code></p> <pre><code>f = lambda x:','.join(dict.fromkeys([i.strip() for i in x.split(',')]).keys()) df.loc[:,df.dtypes.eq('object')]=df.select_dtypes('O').applymap(f)...
python|pandas|list
2
364,622
72,672,068
X has 19 features, but MLPRegressor is expecting 100 features as input. MLPregressor SkLEARN
<p>this is the first time I ask a question on this platform. I'm using Sklearn's MLPregressor model to do the bike rental prediction. I need to test and verify the &quot;RMSE&quot; in the test base, however when I perform the prediction, this error is returned ( X has 19 features, but MLPRegressor is expecting 100 feat...
<p>Do you know that this line is creating a new random dataset with the X, y variables?</p> <pre><code>X, y = make_regression(n_samples=200, random_state=1) </code></pre> <p>Why are you using it?</p> <p>It creates a new dataset with 100 features, and that is probably the reason of your error.</p>
python|pandas|numpy|machine-learning|scikit-learn
0
364,623
72,747,719
How to calculate the time difference groupby ID between the min date and the date were values changed
<p>For each unique ID, I want to calculate the time difference (in days) between their initial date (min(DATE)) and the date were their C1 is greater than their initial C1 OR their C2 is less than their initial C2. want to skip that ID's that has only one record and ID's that value doesn't change</p> <pre><code>ID ...
<p>use dataframe sort_values and iloc</p> <pre><code> txt=&quot;&quot;&quot;ID,DATE,C1,C2 AACH,2022-06-10 05:00:00+00:00,70,2 AAHA,2022-01-12 06:00:00+00:00,60,6 AAHA,2022-04-07 05:00:00+00:00,60,4 AAHA,2022-05-20 05:00:00+00:00,60,5 AALU,2021-09-10 05:00:00+00:00,70,0 AALU,2021-11-29 06:00:00+00:00,70,4 AALU,2022-05-1...
python|pandas|dataframe
0
364,624
72,570,640
How do I add a new column that increments by 1 every 3 rows?
<p>How do I add a new column that increments by 1 every 3 rows? .....................................</p> <pre><code>Dataframe a b 0 20 30 1 44 12 2 58 23 3 20 30 4 44 12 5 58 23 6 20 30 7 44 12 8 58 23 Expected Output: a b ...
<p>Use ineteger division by <code>3</code> by default index values:</p> <pre><code>df['year'] = df.index // 3 + 1995 </code></pre> <p>Or for general solution create helper array:</p> <pre><code>df['year'] = np.arange(len(df.index)) // 3 + 1995 </code></pre>
pandas
2
364,625
72,752,287
From a pandas series of dates, match against a particular year
<p>From a pandas Series of dates, which pandas Series method can I use to match against a particular year?</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd date_series = pd.Series([&quot;1 jan 2022&quot;, &quot;2021-01-31&quot;, &quot;19 dec 2016&quot;]) print(date_series.**someMethod**(&quot;20...
<pre class="lang-py prettyprint-override"><code>import pandas as pd date_series = pd.Series([&quot;1 jan 2022&quot;, &quot;2021-01-31&quot;, &quot;19 dec 2016&quot;]) date_series = pd.to_datetime(date_series) date_series.dt.year == 2021 &gt;&gt; 0 False 1 True 2 False dtype: bool </code></pre>
python|pandas|date
3
364,626
72,547,485
Calculating the cosign distance between two Dataframes and appending result to a new dataframe
<p>I have the following example dataframes.</p> <pre><code>group_a = {'0':[2.0,9.4,10.8,0.6,9.4,0.1], '1':[4.2,7.1,3,6.3,7.8,0.01], '3':[8.1,9.5,6.1,5.6,2,2.2] } A = pd.DataFrame(group_a, index=['aa','ab','ac','ad','ae','af']) group_b = {'0':[7.0,5.8,11.0,5.8,2.1,2.4], '1':[5.3...
<p>You can use scipy's cdist:</p> <pre><code>from scipy.spatial.distance import cdist pd.DataFrame(cdist(A,B, metric='cosine'), index=A.index, columns=B.index) </code></pre> <p>Output:</p> <pre><code> ba bb bc bd be bf aa 1.110223e-16 1.116861e-01 0.2...
python|pandas|cosine-similarity
2
364,627
72,504,159
Create new columns in pandas df by grouping and performing operations on an existing column
<p>I have a dataframe that looks like this (Minimal Reproducible Example)</p> <pre><code>thermometers = ['T-10000_0001', 'T-10000_0002','T-10000_0003', 'T-10000_0004', 'T-10001_0001', 'T-10001_0002', 'T-10001_0003', 'T-10001_0004', 'T-10002_0001', 'T-10002_0003', 'T-10002_0003', 'T-100...
<p>Use <code>groupby</code> by splitting with your delimiter <code>_</code>. Then, just aggregate with whatever functions you need.</p> <pre><code>&gt;&gt;&gt; df.groupby(df['thermometers']\ .str.split('_'). \ .str.get(0)).agg(['min', 'mean', 'max']) </code></pre> <hr /> <pre><code> ...
python|python-3.x|pandas|dataframe
2
364,628
72,534,795
generating random values and append the results in next columns
<p>The first thing I want to do is get four numbers from the user and put them in the first column.(For example: 10,30,60,80) Then I need to create another columns(second), in addition to the first column, and the rows of the second column should vary as shown below.</p> <pre><code>10 Values should range from 1-2 30 v...
<p>You can do this with pandas and <a href="https://numpy.org/devdocs/reference/random/generated/numpy.random.Generator.uniform.html" rel="nofollow noreferrer">numpy</a>:</p> <pre><code>import pandas as pd import numpy as np inp_data=[10, 30, 60, 80] # mapping dict for the ranges ranges = {10: [1,2], 30: [3...
python|dataframe|numpy
0
364,629
72,581,083
Python Reading Variable Whitespace Text Table Format
<p>I have this weird output from another tool that I cannot change or modify that I need to parse and do analysis on. Any ideas on what pandas or python library i should use? It has this space filling between columns so that each column start is aligned properly which makes it difficult. White space and tabs are not th...
<p>If the columns are consistent and every cell has a value, it should actually be pretty easy to parse this manually. You can do some variation of:</p> <pre><code>your_file = 'C:\\whatever.txt' with open(your_file) as f: for line in f: total_capacity, existing_load, recallable_load, new_load, excess_load,...
python|pandas|parsing
0
364,630
72,804,521
Removing a custom stop words list from a column in a pandas data frame
<p>I'm working on analyzing a long list of survey responses. I can remove the stopwords in the standard nltk list perfectly fine. However, I've created a modified list and can't seem to noodle how to incorporate it into the code. The original code I used for the standard list was:</p> <p>#creating a column where the st...
<p>I am not sure if I understand completely, but why can't you use the same line of code but then check for membership in the new set? So:</p> <pre><code>df['stopwords_removed'] = df['no_punc'].apply(lambda x: [word for word in x if word not in new_stopwords]) </code></pre>
python|pandas
1
364,631
72,799,869
How to replace NaN in pandas dataframe with calculated value from other columns
<p>I have below dataframe where I added last row as latest data.</p> <pre><code>df.tail() Open High Low Close %K %D Date 2022-06-22 23.71 25.45 23.55 24.29 21.74 18.01 2022-06-23 24.94 25.57 24.17 25.33 31.30 25.15 2022-06-24 26.11 28.04 2...
<p>One way to do this would be to use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer">pandas fillna() method</a>.<br /> You will still need the first calculations:</p> <pre><code>df['14-high'] = df['High'].rolling(14).max() df['14-low'] = df['Low'].rolli...
python|pandas
0
364,632
72,523,863
Add second row and assign values to them based on values of first row
<p>I have a dataframe like this, but much larger:</p> <pre><code> velocity mass volume acceleration temperature pressure 0 100 4.5 12 1.3 45 6.5 1 120 5.5 15 2.1 60 7 2 130 6 11 2 55 12 </code></pre> ...
<p>I think yes you can define a dict first and go like:</p> <pre><code>uom_dict={'velocity':'m/s', 'mass': 'kg', 'volume':'gal', 'acceleration': 'm/s2', 'temperature':'deg C', 'pressure':'atm'} df.columns = pd.MultiIndex.from_arrays([df.columns, df.columns.map(uom_dict...
python|pandas|numpy
0
364,633
72,546,560
Calculate column value count as a bar plot in Python dataframe
<p>I have time series data and want to see total number of Septic (1) and Non-septic (0) patients in the <strong>SepsisLabel</strong> column. The Non-septic patients don't have entries of '1'. While the Septic patients have first 'Zeros (0)' then it changes to '1' means it now becomes septic. The data looks like this:<...
<p>For 1) use <code>np.where</code>. For 2), you can use <code>seaborn</code> for the second purpose:</p> <pre><code>dedup = df.groupby('P_ID')[['SepsisLabel', 'Gender']].max().reset_index() dedup['SepticType'] = np.where(dedup.SepsisLabel, 'Septic', 'NonSeptic') sns.countplot(data=dedup, x='SepticType', hue='Gender')...
python|pandas|dataframe|pandas-groupby|bar-chart
0
364,634
72,503,761
ValueError: all the input array dimensions for the concatenation axis must match exactly
<p>I am trying to use the <code>predict</code> method in my logistical regression class with list <code>X_test</code>. However, the code crashes with this error:</p> <blockquote> <p>ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has ...
<p>There are some problems with the code - <code>LogisticRegression()</code> should not be initialized with training data</p> <p><code>model.fit</code> will have train and test data as its params</p> <p><code>accuracy_score</code> is a function, and should not be mixed with a variable</p> <p>try this -</p> <pre><code>k...
pandas|scikit-learn
0
364,635
72,815,098
Dimension 2 in both shapes must be equal, but are 3 and 1
<p>I am getting a value error while trying to make a GAN work on RGB photos in Tensorflow.</p> <p>in the video that I'm following it works in black and white(59:50): <a href="https://www.youtube.com/watch?v=LZov6445YAY&amp;list=WL&amp;index=4&amp;t=3426s&amp;ab_channel=SundogEducationwithFrankKane" rel="nofollow norefe...
<p>Let us start by inspecting your error alongside the code you have provided.</p> <pre><code> x = tf.concat([data, fake], axis=0) ValueError: Dimension 2 in both shapes must be equal, but are 3 and 1. Shapes are [28,28,3] and [28,28,1]. for '{{node concat_1}} = ConcatV2[N=2, T=DT_FLOAT, Tidx=DT_INT32](data...
python|tensorflow|keras|neural-network|keras-layer
1
364,636
72,691,548
Julia: sort two arrays (like lexsort in numpy)
<p><strong>Python example</strong></p> <hr /> <p>In Numpy there is <a href="https://numpy.org/doc/stable/reference/generated/numpy.lexsort.html" rel="nofollow noreferrer">lexsort</a> to sort one array within another:</p> <blockquote> <p>Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, ...
<p>Use <code>sort</code> and <code>sortperm</code> functions with a vector of tuples:</p> <pre><code>julia&gt; a = [1, 1, 1, 2, 2, 2]; julia&gt; b = [10, 8, 11, 4, 8, 0]; julia&gt; x = collect(zip(a, b)) 6-element Vector{Tuple{Int64, Int64}}: (1, 10) (1, 8) (1, 11) (2, 4) (2, 8) (2, 0) julia&gt; sort(x) 6-elem...
numpy|julia
3
364,637
72,542,964
To check if few values in dataframe column exists in another dataframe column
<p>I am trying to check if values present in df1 column is present in df2 column. df2 contains more values than df1 and cant use <code>for</code> loop</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'one': [2,4,6,8]}) df2 = pd.DataFrame({'one': [4,2,6,8,10]}) print(df1.isin(df2)) </code></pre> <p>expected re...
<p>You can compare columns:</p> <pre><code>print(df1['one'].isin(df2['one'])) 0 True 1 True 2 True 3 True Name: one, dtype: bool </code></pre> <p>Or convert values of DataFrame to 1d array and then list:</p> <pre><code>print(df1.isin(df2.to_numpy().ravel().tolist())) one 0 True 1 True 2 True 3 T...
python|pandas|dataframe|compare|difference
1
364,638
72,831,448
Why is my generator and discriminator loss converging at higher values in WGAN-GP?
<p>This is the loss plot of WGAN-GP after training for 14000 iterations. My image size is 128 by 128. Though the loss plot seems to be converging, the generator loss at iteration 14000 is -26646 and critic loss is -249909.</p> <p><a href="https://i.stack.imgur.com/FCWMK.png" rel="nofollow noreferrer">Loss plot</a></p>
<p>Batch Normalization in the discriminator breaks Wasserstein GANs with gradient penalty. The authors themselves advocate the usage of layer normalization instead, but this is clearly written in bold in their paper (<a href="https://papers.nips.cc/paper/7159-improved-training-of-wasserstein-gans.pdf" rel="nofollow nor...
deep-learning|pytorch|generative-adversarial-network
2
364,639
72,635,105
How to create an array with values along specified axis?
<p><a href="https://numpy.org/doc/stable/reference/generated/numpy.full.html" rel="nofollow noreferrer"><code>numpy.full()</code></a> is a great function which allows us to generate an array of specific shape and values. For example,</p> <pre><code>&gt;&gt;&gt;np.full((2,2),[1,2]) array([[1,2], [1,2]]) </code></...
<p>Edit: adding ideas from Michael Szczesny</p> <pre class="lang-py prettyprint-override"><code>import numpy as np shape = (10, 48, 271, 397) root = np.arange(shape[0]) </code></pre> <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.full.html" rel="nofollow noreferrer"><code>np.full</code>...
python|arrays|numpy
2
364,640
72,632,868
Some cells are empty when printing pandas output with xlsxwriter
<p>I have two excel sheets with multiple rows and columns. My task is to compare both excels and print only the matching values. The output has to be print into a new excel. My idea is to use pandas and xlsxwriter engine for this.</p> <p>Pseudocode:</p> <ol> <li>Read Excel 1 --&gt; Dataframe 1</li> <li>Read Excel 2 --&...
<p>it seems to me that this problem is related to different column names in MatchedData and OutputData. i tryed init OutputData as</p> <blockquote> <p>OutputData = pd.DataFrame(MatchedData, columns=['ColumnA', 'ColumnB', 'ColumnC']) And got the expected result.</p> </blockquote> <p>ps. If pandas is too complex, then fo...
python|excel|pandas|dataframe
0
364,641
72,580,665
Pandas: How to delete the rows that meet conditions by filter?
<pre><code>import pandas as pd data={&quot;product_name&quot;:[&quot;Keyboard&quot;,&quot;Mouse&quot;, &quot;Monitor&quot;, &quot;CPU&quot;,&quot;CPU&quot;, &quot;Speakers&quot;,pd.NaT], &quot;Price&quot;:[500,None, 5000.235, None, 10000.550, 250.50,None], &quot;Final_Price&quot;:[5,None, 10, None, 20, 8,N...
<p>here is one way to do it, using index</p> <pre><code>df.drop(df[(df['Price'].isnull()) &amp; (df['Final_Price'].isnull()) &amp; (df['Available_Quantity'] &gt; 5.0)].index) </code></pre> <pre><code> product_name Price Final_Price Available_Quantity Available_Since_Date 0 Keyboar...
python|pandas|dataframe|filter|delete-row
0
364,642
72,813,136
Converte json file to csv file with proper formatted rows and columns in excel
<p>Currently I'm working a script that can convert json file to csv format my script is working but I need to modify it to have proper data format like having rows and columns when the json file is converted to csv file, May I know what I need to add or modify on my script?</p> <pre><code>import pandas as pd df = pd.r...
<p>Taking reference from your code,you can try</p> <pre><code>df.to_csv(r'/home/admin/xml/myfileSample.csv', encoding='utf-8', header=header,index = None, sep=&quot;:&quot;) </code></pre>
python|pandas|linux|csv
0
364,643
72,639,857
X has 1 features, but LinearRegression is expecting 5 features as input
<pre><code>import matplotlib.pyplot as plt import numpy as np import pandas as pd import sklearn.linear_model dados = pd.read_csv(&quot;dados.csv&quot;, thousands=',', sep = &quot;;&quot;, header = 0, encoding='latin-1') dados.drop('pais', axis = 1, inplace=True) df = dados.to_numpy() g = [df[:,1]] h = [df[:,0]] #p...
<p><code>X</code> does not expect 5 features — it's fine with 1 feature or 100,000 features — but it does need to be a 2D array. You are passing a 1D array (well, a Pandas Series, but it amounts to the same thing).</p> <p>Here's how I would define <code>X</code> and <code>y</code> (which you call <code>g</code> and <co...
python|pandas|machine-learning|scikit-learn|linear-regression
0
364,644
72,538,343
How to reshape a (x, y) numpy array into a (x, y, 1) array?
<p>How do you reshape a (55, 11) numpy array to a (55, 11, 1) numpy array?</p> <p>Attempts:</p> <ul> <li>Simply doing <code>numpy_array.reshape(-1, 1)</code> without any loop produces a flat array that is not 3D.</li> <li>The following <code>for loop</code> produces a &quot;cannot broadcast error&quot;:</li> </ul> <pre...
<p>Maybe you are looking for <code>numpy.expand_dims</code>(<a href="https://numpy.org/doc/stable/reference/generated/numpy.expand_dims.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.expand_dims.html</a>)?</p> <pre><code>import numpy a = numpy.random.rand(55,11) print(a.shape) #...
python|arrays|numpy
3
364,645
72,593,067
Merge pandas dataframe rows based on column value
<p>I want to merge or replace my data-1 of some rows based on my 'TIMESTEP' values in data-2.</p> <p>I have tried both merge and replace options. On using replace, I am getting</p> <pre><code>&quot;AttributeError: 'Series' object has no attribute '_replace_columnwise'&quot; </code></pre> <p>And on using merge methods I...
<p>IIUC, merge df with df2 on timestep and take the 'y' from df2</p> <pre><code>df[['TIMESTEP','id', 'mass']].merge(df2[['y']], left_on=df['TIMESTEP'], right_on=df2['TIMESTEP'], how='left').drop(columns='key_0'...
python|pandas|dataframe|replace|merge
0
364,646
72,522,060
Python drop rows containing ending characters from any column
<p>Is there a way other than specifying each column, i.e. <code>df.drop(df[Col1]</code>..., where rows can be deleted based on a condition?</p> <p>For example, can I iterate through Col1, Col2, ...through Col15 and delete all rows ending with the letter &quot;A&quot;?</p> <p>I was able to delete columns using</p> <pre>...
<p>IIUC, you have a pandas DataFrame and want to drop all rows that contain at least one string that ends with the letter 'A'. One fast way to accomplish this is by creating a mask via <code>numpy</code>:</p> <pre><code>import pandas as pd import numpy as np </code></pre> <p>Suppose our <code>df</code> looks like this:...
python|pandas|conditional-statements|rows|drop
1
364,647
72,692,094
Drop row if column entry contains NaN
<p>I have a series <code>s</code> that has entries that are lists, for example <code>[1, 2, 3, NaN, NaN]</code> or <code>[4, 5]</code>. These lists may contain NaNs as the last few elements, and I want to drop all entires in this series that contain NaN. I have so far used <code>s.transform(lambda x: np.nan if np.isnan...
<p>You can identify all index positions that are equal to <code>NaN</code> for the exploded data frame and can then filter the data frame for those that are not in the index array:</p> <pre class="lang-py prettyprint-override"><code>ser = pd.DataFrame(data={&quot;col&quot;: [[1, 2, 3, np.nan, np.nan], [3, 4, 5], [3, 9]...
python|pandas|performance|series
2
364,648
72,527,642
How padding=zeros works in pytorch in functional.conv1d
<p>This following code below giving a output of shape <code>(1,1,3)</code> for the shape of <code>xodd</code> is <code>(1,1,2)</code>. The given kernel shape is<code>(112, 1, 1)</code>.</p> <pre><code>from torch.nn import functional as F output = F.conv1d(xodd, kernel, padding=zeros) </code></pre> <p>How the <code>padd...
<p><strong>What is <code>padding=zeros</code>?</strong> If we set <code>paddin=zeros</code>, we don't need to add numbers at the right and the left of the tensor.</p> <p><strong>Padding=0</strong>:</p> <pre><code>from torch.nn import functional as F import torch inputs = torch.randn(33, 16, 6) # (minibatch,in_channels,...
python|tensorflow|pytorch|padding|conv1d
1
364,649
72,508,505
is there a reason why this text cleaning function doesnt work properly?
<p>i have a df that contains tweets from a twitter account i wrote a function to remove every username from the tweets but when i tested it with a test data frame it worked right but when i tried it on the tweet dataframe it only removed some and left others</p> <pre><code>import pandas as pd import numpy as np #test d...
<pre><code> for item in items: if '@' in item: items.remove(item) </code></pre> <p>This is a classic error -- removing items from a list as you iterate over it will cause the iteration to skip items! In your tweet data you have multiple usernames back to back, and they're getting lef...
python|pandas|dataframe|data-cleaning|sentiment-analysis
2
364,650
72,671,141
How can I make a new column that does calculations but first selects them by my id column?
<p>I would like to do calculations on my x column and make a new column, for example lets try to determine the rolling standard deviation, I know how to calculate that for the full column:</p> <pre><code>df['std'] = df.x.rolling(2).std </code></pre> <p>Example of original dataframe:</p> <pre><code>id x 1 10 1 20 1 ...
<p>As you are filtering for each &quot;id&quot;, you can use GroupBy:</p> <pre><code>df.groupby(&quot;id&quot;)[&quot;x&quot;].rolling(2).std() #Out[7]: #id #1 0 NaN # 1 7.071068 # 2 10.606602 # 3 0.000000 #2 4 NaN # 5 14.142136 # 6 21.213203 # 7 ...
python|pandas|dataframe
1
364,651
72,813,471
Finding the local maxima and local minima in the data python
<p>Data:</p> <pre><code>+---------------------+------------------+--+ | date_add | fnv_wa | | +---------------------+------------------+--+ | 2022-06-24 06:00:16 | 46.216866 | | | 2022-06-24 07:00:16 | 46.216866 | | | 2022-06-24 08:00:16 | 45.685139 | | | 2022-06-24 09:00:...
<p>Which value to you use for <code>n</code>?</p> <p>Your code is working quite fine with <code>n=3</code>:</p> <pre><code>from scipy.signal import argrelextrema n = 3 df['min'] = df.iloc[argrelextrema(df['fnv_wa'].values, np.less_equal, order=n)[0]]['fnv_wa'] df['max'] = df.iloc[argrelextrema(df['f...
python|pandas|machine-learning|statistics
1
364,652
72,649,348
Returning a single row from a dataframe using .loc (pandas)
<p>I currently have a data frame with 5 columns.</p> <p><a href="https://i.stack.imgur.com/mqHbL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mqHbL.png" alt="enter image description here" /></a></p> <p>When I'm using <code>df.loc[&quot;Adam Henrique&quot;]</code> to pull up that single row, I am g...
<p>If you have a text based index you simply need to put a second par of brackets around your .loc to reference the text</p> <pre><code>df = pd.DataFrame({ 'Name' : ['Your Name', 'My Name', 'Other Name'], 'Number' : [1, 2, 3] }) df = df.set_index('Name') df.loc[['Your Name']] </code></pre>
python|pandas|dataframe
1
364,653
72,635,355
Json to CSV using Python and pandas dataframe
<p>I'm trying to convert this JSON to CSV. I have tried many ways but without success, I have converted other JSONs but no one with this structure. I'd like to extract only the headers and values.</p> <p>The best approach that I have was with this code but still did not get a tabular CSV file.</p> <pre><code>import jso...
<p>If you need to extract only headers and values, you can pass it to a dataframe:</p> <pre class="lang-py prettyprint-override"><code>import json import pandas as pd data = json.loads(open('your_file.json').read()) print(data['headers'])) &gt;&gt; ['Warehouse', 'Days in Date', &quot;SKU's&quot;, 'Stock mini...
python|json|pandas|csv
1
364,654
72,570,325
module 'tensorflow' has no attribute 'get_collection'
<p>I want to add regularization to my tf neural network:</p> <p>I have tried the first solution (Lukazs's solution) of:</p> <p><a href="https://stackoverflow.com/questions/37107223/how-to-add-regularizations-in-tensorflow">How to add regularizations in TensorFlow?</a></p> <p>But then the compiler yield at me:</p> <p>mo...
<pre><code>from tensorflow.keras import layers from tensorflow.keras import regularizers layer = layers.Dense( units=64, kernel_regularizer=regularizers.L1L2(l1=1e-5, l2=1e-4), bias_regularizer=regularizers.L2(1e-4), activity_regularizer=regularizers.L2(1e-5) ) </code></pre> <p><a href="https://keras.i...
python|tensorflow|neural-network
2
364,655
72,619,363
Is there a way to plot/identify a count over time using a list of date ranges?
<p>I have data similar to the following which shows members, what day they entered a facility, and what day the left the facility, which looks similar to the following</p> <pre><code>member_name entry_date exit_date John 2015-01-01 2020-01-01 Adam 2015-01-01 2019-01-01 Tyler 2016-01-01...
<p>To get a count of a specific value on a pandas column (such as a date), you can try:</p> <pre><code>(df['entry-date'] =='2015-01-01').sum() </code></pre> <p>For the line plot of the count you can do:</p> <pre><code>df.groupby('entry-date')['member_name'].count().plot(kind='line'); </code></pre>
python|pandas|dataframe|matplotlib
0
364,656
72,777,645
Separate the solutions of `integrate.quad`
<p>I'm now trying to obtain the apropriate solution for the integral with the array upper limit. Everything works fine, However, function contain two solutions, I need to get rid of the second one. Here is the code:</p> <pre><code>from scipy.integrate import quad from typing import List def integrand(z,alpha,beta,gamm...
<p>The exact thing you are looking for is an <a href="https://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers" rel="nofollow noreferrer">underscore.</a> It is the proper way to ignore or disregard the return values which you don't need.</p> <p>Let's say you have a function like this.</...
python|arrays|python-3.x|list|numpy
0
364,657
72,776,904
In lambda func slice a str does not work as intended
<p>I have the following code. The 1st block works as intended. The intended result is col4 will hold values from col 2 if the col3 value does not end with 7. Otherwise, col4 value will be col2 minus 1. But when I merge the line 2 with the 3 as the 2nd code block shows, it does not work. What is the problem?</p> <pre cl...
<p>Try this instead:</p> <pre class="lang-py prettyprint-override"><code>data=pd.DataFrame({'col1':[1,2,3,4],'col2':[2018, 2018, 2019, 2020], 'col3':[2347, 1327, 2355, 2111]}) data['col4']=data.apply(lambda x: x['col2']-1 if x['col3'].astype('str')[3]=='7' else x['col2'], axis=1) data ---------------------------------...
pandas|lambda
0
364,658
72,773,475
Rename multiindex level based on other level
<p>I have a dataframe with a multiindex column, more or less like so</p> <pre><code>import pandas as pd columns = pd.MultiIndex.from_product(((&quot;Length&quot;, &quot;Weight&quot;), (&quot;Max&quot;, &quot;Min&quot;), (&quot;asd&quot;,)), names=(&quot;Measure&quot;, &quot;Info&quot;, &quot;Unit&quot;)) df = pd.DataF...
<h3>Update</h3> <pre><code>measure_to_unit = {&quot;Length&quot;: &quot;m&quot;, &quot;Weight&quot;: &quot;kg&quot;} l1, l2, l3 = zip(*df.columns) newcol = pd.MultiIndex.from_arrays([l1, l2, [measure_to_unit[i] for i in l1]]) df.set_axis(newcol, axis=1) </code></pre> <p>Output:</p> <pre><code> Length Weight ...
python|pandas|multi-index
3
364,659
72,806,363
How to split a column into two or multiple columns columns in python using either str.split or regex?
<p>How to split this column into 2 or more columns. I've used <code>str.split('/',2)</code> to split but it just removed the '/' and did not split into 2 columns.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">X</th> </tr> </thead> <tbody> <tr> <td style="text-a...
<p>My approach would be to use <code>Series.str.extractall</code> with a specific pattern to get the direction and the amount, convert the amount to a suitable type (I've just gone for integer here), then pivot_table filling in with zeros where appropriate, eg:</p> <pre><code>out = ( df['X'].str.extractall(r'(?P&lt...
python|pandas|string|split
1
364,660
72,531,403
Pandas: Function not executing as expected
<pre><code>df: score_difference DNB selection selection_match 0 1.040000 0.65 DNB No Match 1 0.894543 0.65 DNB No Match 2 2.120546 2.11 DNB No Match 3 0.672945 0.65 DNB No ...
<p>Try using apply when doing row based calculations:</p> <p><code>df['DNB'] = df.apply(lambda x: x.score_difference + 0.02 if x.selection_match == &quot;No Match&quot; else x.DNB, axis=1)</code></p>
python|pandas|dataframe
1
364,661
72,744,884
How to merge two dataframes in pyspark with different columns inside struct or array?
<p>Lets say, there are two data-frames. <strong>Reference dataframe</strong> and <strong>Target dataframe</strong>.</p> <p>Reference DF is a reference schema.</p> <p><strong>Schema for reference DF (r_df)</strong></p> <blockquote> <pre><code>r_df.printSchema() </code></pre> </blockquote> <pre><code>root |-- _id: strin...
<p><em>below code is un-tested</em> but should prescribe how to do it. (written from memory without testing.) There may be a way to get fields from a struct but I'm not aware how so i'm interested to hear others ideas.</p> <ol> <li>Extract struct <a href="https://sparkbyexamples.com/pyspark/pyspark-find-datatype-column...
python|pandas|apache-spark|pyspark
0
364,662
72,592,360
beginner_question = 'When do we add arguments to functions?'
<p>I was recently practicing some Python and I came onto a roadblock where I couldn't make my agg() to work, I later found out that it was because I didn't have to call the functions.</p> <p>My question here is: I'd like somebody to please explain what are we exactly doing when we write () at the end of the function an...
<p>In</p> <pre><code>sales.groupby('type')['weekly_sales'].agg([np.min,...] </code></pre> <p><code>sales</code> is a Pandas dataframe, <code>groupby('type')</code> is a method call that returns <code>GroupBy</code> object, which in turn has a <code>agg</code> method.</p> <p>Looking up its docs:</p> <p><a href="https://...
python|function|numpy|calling-convention
0
364,663
59,743,522
Python: stratified sampling on unbalanced data with ratio
<p>Here is my data frame:</p> <pre><code>df = pd.DataFrame({'var1': [1,2,3,4,5,6,7,8,9,10,11,12,13,14], 'var2': ['a','a','a','a','b','b','b','b','b','b','b','c','d','d'], 'var3': ['y','y','y','y','r','r','r','r','r','r','r','q','q', 'r'], 'var4': [0,1,0,0,1,1,0,...
<p>Let's try this way. Sort <code>df</code> to push all <code>1</code> to top. <code>cumcount</code> on groupby of <code>var1</code> and <code>var2</code> to use as a counter. Getting sum of each group (since <code>var4</code> values are only <code>0</code> and <code>1</code>, sum of each group is the number of <code>1...
python|pandas|dataframe|sampling
0
364,664
59,583,340
pandas Data.frame assign issue
<p>I would like to add new column by using the <code>.assign</code> function.</p> <pre><code>df = pd.DataFrame({'A': range(1, 5), 'B': range(11, 15)}) def delta(df): df = df.assign(df_delta = df.A - df.B, df_multiply = df_delta*30 ) return df print(delta(df)) </code><...
<p>the <code>df_delta</code> column is not yet defined in the assign function, you can circumvent this error by temp variable:</p> <pre><code>df = pd.DataFrame({'A': range(1, 5), 'B': range(11, 15)}) def delta(df): a_b = df.A - df.B df = df.assign(df_delta = a_b, df_multiply = a_b*30) return df print(del...
python|pandas
1
364,665
59,491,088
tensorflow cudaGetDevice() failed. Status: cudaGetErrorString symbol not found
<pre class="lang-py prettyprint-override"><code>tensorflow.python.framework.errors_impl.InternalError: cudaGetDevice() failed. Status: cudaGetErrorString symbol not found. </code></pre> <p>OS: Windows 10</p> <p>CUDA version: 10.0</p> <p>Visual studio: 2017 + 2019</p> <p>Python version: 3.7.6</p>
<p>Figured it out:</p> <ol> <li>Uninstall tensorflow</li> <li>Uninstall CUDA</li> <li>Uninstall visual studio</li> <li>Install visual studio</li> <li>Install CUDA</li> <li>Install Tensorflow</li> </ol>
python-3.x|tensorflow|artificial-intelligence
1
364,666
59,483,469
Pandas Dataframe Replace Substring
<p>For instance I have data similar to this</p> <pre><code> name flag seen_week_end 0 Mick Am Johnson TRUE 03/05/2017 1 Brian Ma Yeager FALSE NaN 2 Maggie Alvarez FALSE NaN 3 Christine Ma Yin ...
<p>Here is <code>replace</code></p> <pre><code>df['name']=df['name'].replace({r'\bAm\b':'Yan',r'\bMa\b':'Mu'},regex=True) </code></pre>
pandas|dataframe|replace|substring
2
364,667
59,704,703
Can I extract or construct as a Pandas dataframe the table with coefficient values etc. provided by the summary() method in statsmodels?
<p>I have run an OLS model in statsmodels and I would like to have the table in the summary as a Pandas dataframe.</p> <p>This is what I mean:</p> <p><a href="https://i.stack.imgur.com/Fuz3J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fuz3J.png" alt="enter image description here"></a></p> <p>I...
<p>The <code>fitted_model</code> is in fact a <code>RegressionResults</code> object that stores all the regression results and you can access them via the corresponding <a href="https://www.statsmodels.org/devel/generated/statsmodels.regression.linear_model.RegressionResults.html#statsmodels.regression.linear_model.Reg...
pandas|linear-regression|python-3.7|statsmodels
1
364,668
59,764,192
Pandas replace using regex
<p>I have a column that has null/missing values written as strings such as 'There is no classification', 'unkown: there is no accurate classification', and other variants. I would like to replace all of these values with <code>None</code>.</p> <p>I have tried this but it isn't working:</p> <pre><code>df['Fourth level...
<p>You can try this:</p> <pre><code>df['Fourth level classification'] = (df['Fourth level classification'] .str .lower() .replace(r'(.*(there is no).*)', pd.isna, regex=True)) </code></pre>
python|regex|pandas
0
364,669
59,837,241
Combine first row and header with pandas
<p>I'm trying to replicate code I made in R in Python, but I ran into difficulties when I tried to fix my header. I want to merge the header and the first row, but I can't seem to make it work.</p> <p>My data currently looks like this:</p> <pre><code> Acronym Project Number Title Dates Unnamed: 4...
<p>Convert first 3 columns names and all data of first row after 3th value:</p> <pre><code>Projects_clean.columns = (Projects_clean.columns[:3].tolist() + Projects_clean.iloc[0, 3:].tolist()) </code></pre> <p>Or:</p> <pre><code>Projects_clean.columns = np.concatenate([Projects_clean.colum...
python|pandas
4
364,670
59,772,370
How to generate unique id and sub_id for each group
<p>My goal is to generate an <strong>id</strong> (id trajectory) and a <strong>sub id</strong> (under trajectory) for each group (u_uuid and p_uuid).</p> <p>I tried the <strong>ngroup</strong> function and it didn't work</p> <pre><code>data = [ {'u_uuid': 110, 'p_uuid': 'aaa', 'mode': 'walk', 'dest': 'work'}, {'u_uu...
<p>Use:</p> <pre><code>s1 = df.groupby(['u_uuid', 'p_uuid', 'dest'],sort=False).ngroup().add(1) s2 = df.groupby(['u_uuid','p_uuid', df['mode'].ne(df2['mode'].shift()).cumsum()],sort=False).ngroup() df['sub_id']=s2.sub(s2.where(s1.ne(s1.shift())).ffill()).add(1).astype(int) df['id']=s1 print(df) u_...
pandas|pandas-groupby
3
364,671
59,574,642
How to multiply all columns of a dataframe based on a condition?
<p>I want to multiply all values less than 1 in a dataframe by 1000. Below is an example of a dataframe; <a href="https://i.stack.imgur.com/Ye4ap.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ye4ap.png" alt="enter image description here"></a></p> <p>Appreciate your help.</p>
<pre><code>for col in df.columns.tolist() df[col] = df[col].apply(lambda x: x * 1000 if x &lt; 1, axis=1) </code></pre>
python|pandas
1
364,672
59,477,532
How to automate labelling
<p>I have a csv file(sentences.csv) that contains lists of sentences, and i wanted to automatically label sentences that have both verbs, especially/but not only; (will cause, getting, can lead to, increases the risk of, leading cause of, it caused, it causes, cause of, most likely to), and also diseases list from a cs...
<p>I wrote something like this and it worked. In this code i get words from <code>check_list</code> so in your case you can get <code>check_list</code> with <code>diseases['Lists'].values.tolist()</code> and other strings.</p> <pre><code>data['STORY'] = data['STORY'].str.replace('*', '#') # Need this because '*' is sp...
python|pandas|csv
1
364,673
59,877,756
What is the difference between the args 'index' and 'values' for the pandas interpolate function?
<p>What is the difference between the pandas DataFrame interpolate function called with args 'index' and 'values' respectively? It's ambiguous from the documentation:</p> <blockquote> <p>pandas.DataFrame.interpolate</p> <p>method : str, default ‘linear’</p> <p>Interpolation technique to use. One of:</p> <p>‘linear’: Ig...
<p>I think it's pretty clear, imagine you're going to interpolate points. The values ​​of your DataFrame represent the <strong>Y values</strong>, it is about filling in the missing values ​​in <strong>Y</strong> with <strong>some logic</strong>, for them an interpolation function is used, in this case for the variable ...
python|pandas|dataframe
2
364,674
59,707,615
pandas np.where based on mulitindex level
<p>I have a Dataframe with MultiIndex. The two Levels are 'Nr' and 'Price'. Is it possible to use np.where on Index Level 1 ('Price') to create a new column ('ZZ')? </p> <p>'ZZ' should be calculated by column 'first' multiplicated by 2, if Level 1 ('Price') is equal to 'x'.</p> <pre><code>import pandas as pd index = ...
<p>You should use <code>get_level_values</code></p> <pre><code>np.where(df.index.get_level_values(1)=='x', df['first']*2, np.nan) array([ 2., nan, 6., nan, 10., nan]) #df['ZZ'] = np.where(df.index.get_level_values(1)=='x', df['first']*2, np.nan) </code></pre>
pandas|indexing|multi-index
0
364,675
59,877,725
pandas - split one row into 2 or 3 (taking a % of the initial row value)
<p>I have seen quite some questions on this but I still can't put them together for this particular problem.</p> <p>I have a df like so;</p> <pre><code>idx value name1 %1 name2 %2 name3 %3 0 100 person1 0.3 person2 0.5 person3 0.2 1 100 person4 1.0 None NaN None None 2 100 person1 0....
<p>Here's a multi-stage solution, with annotations in the comments:</p> <pre><code>import pandas as pd df = pd.DataFrame(columns=['value', 'name1', '%1', 'name2', '%2', 'name3', '%3'], data=[[100, 'person1', 0.3, 'person2', 0.5, 'person3', '0.2'], [100, 'person4', 1], [100, '...
python|pandas|dataframe
1
364,676
59,579,110
How create a new column based on other rows in pandas dataframe?
<p>I have a data frame with 200k rows and i try to add columns based on other rows with some conditions. I tried to achieve it but take a lot of time(2 hours).</p> <p>Here is my code :</p> <pre><code>for index in dataset.index: A_id = dataset.loc[index, 'A_id'] B_id = dataset.loc[index, 'B_id'] C_date = d...
<p>We can use a combination of functions to achieve this, most notable the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html" rel="nofollow noreferrer"><code>pd.DataFrame.rolling</code></a> to calculate the moving average. </p> <pre><code>def custom_agg(group): cols ...
python|pandas
3
364,677
59,861,246
How can I create a Pandas column based on another column with a date?
<p>My <code>csv</code> has:</p> <pre><code>Date,Open,High,Low,Close,Adj Close,Volume,dOpen,dHigh,dLow,dClose,dVolume 1/29/93,43.96875,43.96875,43.75,43.9375,26.45393,1003200,0,0,0,0,0 2/1/93,43.96875,44.25,43.96875,44.25,26.642057,480500,0,0.006396588,0.005,0.007112376,0.007111495 2/2/93,44.21875,44.375,44.125,44.3437...
<p>You also need to specify <code>axis=1</code> when using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply()</code></a> function in order to indicate that it should be applied on row-level. </p> <blockquote> <p>axis : {0 or ‘index...
python|pandas|dataframe
2
364,678
59,724,821
Keras custom metric sum is wrong
<p>I tried implementing <code>precision</code> and <code>recall</code> as custom metrics as in <a href="https://datascience.stackexchange.com/questions/45165/how-to-get-accuracy-f1-precision-and-recall-for-a-keras-model/45166#45166?newreg=6190503b2be14e8aa2c0069d0a52749e">https://datascience.stackexchange.com/questions...
<p>Honestly, I have run into the same problem at a point and to me, the best solution was to use <code>Recall</code> and <code>Precision</code> from built-in metrics.</p> <p>Starting with TensorFlow 2.0, these two metrics are built-in <code>tensorflow.keras.metrics</code>, and they work well provided that you use <cod...
python|tensorflow|keras|tensorflow2.0
2
364,679
59,847,190
Removing rows that contain the same dates from another dataframe - python - pandas
<p>How do I remove all rows that contain the same dates as another dataframe? I want to keep unique rows with all columns between the two dataframes. Also, i cannot use a merge. </p> <pre><code>import pandas as pd from datetime import timedelta df1 = pd.DataFrame({ 'date': ['2001-02-01','2001-02-02','2001-02-0...
<p>Concatenate the two then drop the duplicate dates:</p> <pre><code>df3 = pd.concat([df1, df2]).drop_duplicates(subset='date', keep=False) </code></pre>
python|pandas
2
364,680
59,843,619
Seaborn how to add number of samples per HUE in sns.catplot
<p>I have a catplot drawing using:</p> <pre><code>s = sns.catplot(x="type", y="val", hue="Condition", kind='box', data=df) </code></pre> <p><a href="https://i.stack.imgur.com/3QlF8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3QlF8.png" alt="enter image description here"></a></p> <p>However, th...
<p>This is essentially the same solution as <a href="https://stackoverflow.com/a/59105320/1356000">an earlier answer of mine</a>, which I simplified a bit since:</p> <pre><code>df = sns.load_dataset('tips') x_col='day' y_col='total_bill' order=['Thur','Fri','Sat','Sun'] hue_col='smoker' hue_order=['Yes','No'] width=0....
python|pandas|data-visualization|seaborn|visualization
0
364,681
59,725,376
Trying to assign two polygon elements from a multipolygon to geopandas geometry column causes ValueError
<p>I'm using the geopandas built in world map. I'm trying to split out French Guiana from the France geometry and create a new entry for French Guiana (which I have done successfully). However, when reassinging the reduced European France and Corsica multi-polygon back to the France <code>geometry</code> cell I get an ...
<p>I've managed to find a workaround:</p> <pre><code>import pandas as pd import geopandas as gpd world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) # Remove French Guiana from France. shape = world[world['name'] == 'France']['geometry'].all() # Multipolygon ValueError Workaround. fr_df = pd.Series([...
geopandas
2
364,682
59,734,351
Is there a way to use a yyyy-mm-w format on datetime for plotting?
<p>I have some data that is observed and registered by week, and I'm trying to plot this data with matplotlib. I'm currently using the date format <code>yyyymmw</code>, where <code>w</code> stands for the week of the month (can assume any value from 1 to 5). Every week starts on Tuesday and ends on Monday unless the en...
<p>You can have a look at matplotlib's date <a href="https://matplotlib.org/api/dates_api.html#date-tickers" rel="nofollow noreferrer">tickers</a> and <a href="https://matplotlib.org/api/dates_api.html#date-formatters" rel="nofollow noreferrer">formatters</a>.</p> <p>In essence, given an <code>Axes</code> object, say ...
python|pandas|datetime|matplotlib|week-number
2
364,683
59,721,614
Keras LSTM: Getting TypeError : 'list' object cannot be interpreted as an integer on train_on_batch
<p>I am trying to write my first LSTM with Keras and i'm stucking. That are my training data structure: x_data = [1265, 12] y_data = [1265, 3]</p> <p>x_data example: <code>[102.7, 100.69, 103.39, 99.6, 319037.0, 365230.0, 1767412, 102.86, 13.98]</code> </p> <p>My Model looks like the following: </p> <pre><code> ...
<p>Look at the np.reshape function here: <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html</a></p> <p>It says: numpy.reshape(a, newshape, order='C')</p> <p>The second argument ('newshape')...
python|tensorflow|keras|typeerror|lstm
2
364,684
59,839,869
Attribute Error: list object has no attribute 'apply'
<pre><code>time_weight = list(100*np.exp(np.linspace(-1/divisor, -(num_steps-1)/divisor, num_steps))).apply(lambda x:int(x)) </code></pre> <p>When I try this, I get the following error in Python 3.7. </p> <blockquote> <p><strong>AttributeError: 'list' object has no attribute 'apply'</strong></p> </blockquote> <p>C...
<p>As the error said, <code>list</code> type has no <code>apply</code> attribute. This said, if you have a list <code>l</code> and you want to set to <code>int</code> type every element in it you may use:</p> <pre><code>l = [int(x) for x in l] </code></pre> <p>or </p> <pre><code>l = list(map(int,l)) </code></pre>
python|list|numpy|python-3.7|attributeerror
3
364,685
59,487,979
Mobilenet SSD input shape
<p>I have trained a mobile SSD V2 model on a custom dataset for a single object detection task, and I have converted it to tflite. When I load the .tflite model using the interpreter for testing, and geting the input details using : <code>input_details = model.get_input_details()</code>, it outputs </p> <pre><code>[{'...
<p>Shape: [Batch_size, height, width, channel]</p> <p>If you want to change that size, you need to set up it before converting into the pb file, for example using <a href="https://github.com/tensorflow/models/blob/7ae6bfdd0be6e2b7da569e7d03b827395ffddae6/research/object_detection/export_inference_graph.py#L117" rel="n...
numpy|deep-learning|object-detection|mobilenet|tensorflow-lite
0
364,686
59,811,781
@tf.function ValueError: Creating variables on a non-first call to a function decorated with tf.function, unable to understand behaviour
<p>I would like to know why this function:</p> <pre><code>@tf.function def train(self,TargetNet,epsilon): if len(self.experience['s']) &lt; self.min_experiences: return 0 ids=np.random.randint(low=0,high=len(self.replay_buffer['s']),size=self.batch_size) states=np.asarray([self.experience['s'][i] f...
<p>Using tf.function you're converting the content of the decorated function: this means that TensorFlow will try to compile your eager code into its graph representation.</p> <p>The variables, however, are special objects. In fact, when you were using TensorFlow 1.x (graph mode), you were defining the variables only ...
python|tensorflow|keras|tensorflow2.0
10
364,687
59,769,529
Pandas add single cell vertically
<p>I need to add a single cell to df but before column names(see image below/Example). Is it possible via pandas? Had two ideas, to merge/concat/append two df vertically, of which one would only be a single cell or to <code>df.loc</code> a single cell, but no luck.</p> <pre><code>df = pd.DataFrame({'Construction Type'...
<p>Close, what you need is <code>MultiIndex</code>:</p> <pre><code>mux = pd.MultiIndex.from_product([['Panel Schedule - Manufacturing'], ['Construction Type', 'Panel Type']]) df = (pd.DataFrame({'Construction Type': [combo2.get()], 'Panel Type': [int(upis_tickness)...
python|pandas|dataframe
2
364,688
59,690,553
How to train a neural network with a string output
<p>I'm very new to neural network but I'm doing a project where we have a given data set with some flowers petals dimensions and the species it is and I have to train a neural network using that but the all the previous neural network i have done were all with numbers and no strings to process, so now I don't know how ...
<p>Neural networks only work with numerical values, so every type of data needs to be converted to numerical values. Often, they are stored in tensors (hence the name TensorFlow).</p> <p>Assuming you are doing Iris classification, here is how you can convert the string labels to int labels:</p> <pre class="lang-py pr...
python|python-3.x|numpy|tensorflow|keras
0
364,689
59,748,391
Transpose column data from one dataframe to another
<p>I have a dataframe <code>df1</code> where the head looks like (the actual dataframe is bigger):</p> <pre><code> Quarter Body Total requests Requests Processed 0 Q3 2019 A 93 92 1 Q3 2019 B 228 210 2 Q3 2019 C ...
<p>You can <code>unstack</code> the df1 post setting <code>Body</code> and <code>Quarter</code> as index , then merge with df2 (if using df2 is important else it works without the merge to):</p> <pre><code>df2.merge(df1.set_index(['Body','Quarter'])['Total requests'].unstack(), left_on='Body',right_index=True,ho...
python|pandas
3
364,690
59,605,077
How to pick selected rows from a tensor, regardless of dimension?
<p>I have a tensor (<code>tensorflow.Tensor</code>) <code>A</code>, and I would like to form a new tensor containing certain rows from <code>A</code>, that is, <code>A[i,:,:,...,:]</code> for selected values of <code>i</code>.</p> <p>Problem is I don't know before-hand how many axes <code>A</code> has. So how can I wr...
<p>This is exactly what <code>tf.gather()</code> is for. See the example code below:</p> <pre class="lang-py prettyprint-override"><code>x = tf.reshape(tf.constant([1, 2, 3, 4, 5, 6, 7, 8]), [2, 2, 2]) # This is using tf.gather() on a 3D tensor. print(tf.gather(x, [1])) </code></pre> <p>The result is:</p> <pre><cod...
python|python-3.x|tensorflow2.0
1
364,691
59,898,827
Python - pivot DataFrame with multiple indexes on columns
<p>I have a simple df like below:</p> <pre><code> ID Provider Single_Cost Bundle_ID Bundle_Cost 0 L_0001 P_01 1075.0 NaN NaN 1 L_0002 P_02 590.0 NaN NaN 2 L_0003 P_02 6900.0 NaN NaN 3 ...
<p>Use modified <a href="https://stackoverflow.com/questions/59859989/change-column-to-multi-index-by-using-one-column-as-a-new-level?noredirect=1&amp;lq=1">another solution</a> with pass 2 columns to <code>set_index</code>, last reset <code>ID</code> column and <code>rename</code> it to correct <code>MultiIndex labels...
python|pandas|dataframe
3
364,692
59,502,333
Changing location of legend and size of bar plot
<p>Ive created grouped by data by Age groups and gender and plotted it But I can`t seem to find a way to change to location of the legend</p> <p><a href="https://i.stack.imgur.com/0H6d5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0H6d5.png" alt="enter image description here"></a> This is my code...
<p>You can use <code>plt.rcParams["legend.loc"] = 'center right'</code></p> <p>Other options:</p> <p>The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes/figure.</p> <p>The strings 'upper center', 'lower center', 'center left', 'center right' p...
pandas|bar-chart|legend
0
364,693
59,690,211
Python Pandas: merge returns Nan
<p>I have two dataframes i.e. df1 and df2. df1 is</p> <pre><code>df1 date time 0 2015-04-01 00:00:00 1 2015-04-01 00:30:00 2 2015-04-01 01:00:00 3 2015-04-01 01:30:00 4 2015-04-01 02:00:00 </code></pre> <p>Datatype of df1 is:</p> <pre><code>date object time timedelta64[ns] d...
<p>i think you need to convert to datetime:</p> <pre><code>import pandas as _pd df1['date'] = _pd.to_datetime(df1['date']) print(df1.dtypes) df2['INCIDENT_TIME'] = _pd.to_datetime(df2['INCIDENT_TIME']) print(df2.dtypes) final_df= _pd.merge(df1,df2,left_on=['date','time'],right_on=['INCIDENT_TIME','INTERRUPTION_TI...
python|python-3.x|pandas
2
364,694
59,638,041
Python/Pandas: Divide numeric columns from different dataframes based on a common row identifier and unique row-col combination
<p>I would like to calculate the rate of change between the numeric columns of two dataframes based on a common unique row identifier and unique row-column combination. </p> <p>Here is an example. I opted to present the tables as images in order to use colors to highlight the peculiarities of the two datasets. That is...
<p>If your problem is essentially with the columns and rows not being in the right order, that can be solved by essentially reordering the columns and rows.</p> <pre><code>#Identifying the columns for which the difference is to be computed. Since #'Time' is the 4th column, we take all columns after that valCols = list...
python|pandas|dataframe
0
364,695
59,505,025
splitting a string on multiple delimiters
<p>I have a list of chemical reactions in a pandas dataframe that I would like to split into their constituents. The equations are not that complicated, here are a couple of example:</p> <pre><code>N2 + CH4 → HCN + NH3 H2+F2→2HF </code></pre> <p>The goal is to split the string on + and → and get the following</p> ...
<p>Since you work with a dataframe, there's the pandas method <code>Series.str.split</code>. And we can split on multiple characters. Only in this case we have whitespaces in some cases, so we have take that into account as well.</p> <pre><code>df['Reaction_new'] = df['Reaction'].str.split('\s?[+→]\s?') </code></pre> ...
regex|python-3.x|pandas
3
364,696
59,480,292
Dataframe customisation using the values
<p>I have a dataframe that looks like below</p> <p><a href="https://i.stack.imgur.com/8xyY5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8xyY5.png" alt="enter image description here"></a></p> <p>I would like to convert this to following dataframe by adding headers and also put the value on last ...
<p>You can use <code>pandas.pivot_table</code></p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd # ... your data in df df = pd.read_csv(pd.compat.StringIO('''date value data 01/01/2019 30 data1 01/01/2019 40 data2 02/01/2019 20 data1 02/01/2019 10 data2'''), sep=' ') result...
python|python-3.x|pandas
4
364,697
59,738,337
How to draw a matching Bell curve over a histogram?
<p>My code so far, I'm very new to programming and have been trying for a while.</p> <p>Here I apply the <a href="https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform" rel="nofollow noreferrer">Box-Muller transform</a> to approximate two <a href="https://en.wikipedia.org/wiki/Normal_distribution" rel="nofollow n...
<p>To obtain the 'kernel density estimation', <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html" rel="nofollow noreferrer"><code>scipy.stats.gaussian_kde</code></a> calculates a function to fit the data.</p> <p>To just draw a Gaussian normal curve, there is [<code>scipy.stats....
python|numpy|matplotlib
2
364,698
59,779,292
Linear Interpolation with known values (not filling Nan)
<p>I have some GPS data that I am trying to clean and interpolate some columns. I have a Seconds column (derived from GPS that is not clean), Velocity column and a new, clean Time column. I want to create a VelInt column that has Velocity corresponding to the new Time column. I have posted a snapshot.</p> <pre><code>T...
<p>I believe I solved it with the following</p> <pre><code>x = df_new4['Seconds'] xp = df_new4['Time'] fp = df_new4['Velocity'] df_new4['VelInt']=np.interp(x, xp, fp) </code></pre>
python|python-3.x|pandas
0
364,699
59,565,499
python pandas read HTML table
<p><code>pd.read_html</code> is reading only first 5 rows from (zeroth) table. How to read whole table using <code>pd.read_html</code>?</p> <p>I have tried below code:</p> <pre><code>import pandas as pd import requests from urllib.error import HTTPError try: url = "https://clinicaltrials.gov/ct2/history/NCT02954...
<p>You are assigning <code>data</code> as <code>df.head()</code> which returns the first 5 rows of a dataframe. Instead you can do:</p> <pre><code>url = &quot;https://clinicaltrials.gov/ct2/history/NCT02954874&quot; html_data2 = requests.get(url) df = pd.read_html(html_data2.text)[0] data = df #not df.head() </code></p...
python|pandas
2