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 |
|---|---|---|---|---|---|---|
369,700 | 55,270,578 | Check for Header/Column name in Excel file | <p>I am iterating over many CSV files having header/ Column name in each and every CSV file, and then putting data into a single Excel file . But every time the header / Column name gets copied in to Excel file although it gets copied in new line only, but the thing is, I only need header / Column Name only once into ... | <p>The information is somewhat limited, but the below would do the trick. Instead of manually setting up the <code>csv1</code>, <code>csv2</code> dataframes, you would obviously read them e.g. with <code>read_csv</code>. </p>
<p>If this is not what you are looking for, pls post your current code for more info.</p>
<... | python|excel|python-3.x|pandas | 0 |
369,701 | 55,201,490 | Repeat rows of an array N times depending on the length of my df in a for loop is not working. Error 'numpy.ndarray' object is not callable" (Python) | <p>Ok so, I have looked for other similar questions but I just can't get it to work.
1) I have a for-loop that reads multiple files
2) For each file I need its lenght (T)
3) Then I need the values of the df repeated (T) times.</p>
<p>This works fine if I'm not using a for loop, however by using the same script in a ... | <pre><code> File "/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py", line 974, in from_dict
if isinstance(list(data.values())[0], (Series, dict)):
TypeError: 'numpy.ndarray' object is not callable
</code></pre>
<p>If <code>data</code> is a dataframe, it would produce this error, because <code>value</co... | python|loops|numpy | 1 |
369,702 | 55,313,965 | How to fill gaps in data based on previous values | <p>Table 1 represents the format of my raw data. The dataset was prepared in such a way that the name of a variable 1 is only mentioned for the first observation. I am exploring the dataset and would like to report the count of certain features grouped by the first variable. to achieve this I would have to transform my... | <p>The solution can be found in the pandas documentation under <strong><a href="https://pandas.pydata.org/pandas-docs/version/0.23/api.html#upsampling" rel="nofollow noreferrer">Upsampling</a></strong>. The method used is called <em>ffill()</em> and is used as such:
df.ffill()</p> | python|pandas | 0 |
369,703 | 55,476,310 | How to chain pandas pipe operation involving 'index' manipulation? | <p>I was doing plotting in pandas and encountered following issue with pandas chain operation</p>
<pre><code>import numpy as np
import pandas as pd
import seaborn as sns
n = 365
df = pd.DataFrame(data = {"A":np.random.randn(n), "B":np.random.randn(n)+1},
index=pd.date_range(start="2017-01-01", perio... | <p>Did you want something like this, using lambda function to pass dataframe to sns.boxplot:</p>
<pre><code>(df.stack().reset_index().set_axis(['month','vars','vals'],axis=1,inplace=False)
.set_index('month',drop=False)
.pipe(lambda x: sns.boxplot(x=x.index.month, y="vals", hue="vars", data=x)))
</code></pre>
<... | python|pandas|plot|seaborn | 2 |
369,704 | 55,169,139 | How to Search a Number in a Numpy Array in Python | <p>in my program I want to have 1D array, convert it to a 2D array, convert it back to a 1D array again and I want to search for a value in the final array. In order to change 1D array to 2D, I used numpy. I used where() function in order to search through the array and in the end I get this output:</p>
<p>(array([4],... | <p>No numpy version:</p>
<pre><code>from itertools import chain
a = list(range(1, 10))
b = list(zip(*3*(iter(a),)))
c = list(chain.from_iterable(b))
d = c.index(5)
</code></pre> | python|arrays|numpy|multidimensional-array | 2 |
369,705 | 55,203,292 | Calculating momentum signal in python using 1 month and 12 month lag | <p>I am wanting to calculate a simple momentum signal. The method I am following is 1 month lagged <code>cumret</code> divided by 12 month lagged <code>cumret</code> minus 1. </p>
<p><code>date</code> starts at <code>1/5/14</code> and ends at <code>1/5/16</code>. As a 12 month lag is required, the first <code>mom</cod... | <p>As far as I know, momentum is simply rate of change. Pandas has a built-in method for this:</p>
<pre><code>df['mom'] = df['ret'].pct_change(12) # 12 month change
</code></pre>
<p>Also, I am not sure why you are using cumret instead of ret to calculate momentum.</p>
<p>Update: If you have multiple IDs that you nee... | python|pandas|finance | 2 |
369,706 | 55,438,154 | string split on multiple delimeters | <p>I have a dataset in which a column <strong>info</strong> consists of strings like this:</p>
<pre><code>data['info'][0] = 'Banshidhar Roadlines - Ahmedabad Address Opp. Mahadev Avenue, Nr. Sardar Patel Ring Road, Ahmedabad Email : WebSite : City : Ahmedabad, Ahmedabad Pin Code : 382415 State : Gujarat, India Contact... | <p>So what I did is this:</p>
<pre><code>new = data["info"].str.split("Email :|Address |WebSite :|City :|Pin Code :|State :|Contact No. :|GST No. :|Company Registration No. :|Contact Person :|Mobile No. :|Truck Available :|Services :|Service :", expand=True)
</code></pre>
<p>and then assign elements of new to data</p... | python|regex|python-3.x|string|pandas | 1 |
369,707 | 55,518,198 | np.quantile with wrong calculation? | <p>Under certain settings, np.quantile makes mistakes in determining the correct quantile. Is this a bug?</p>
<pre><code>x = np.array([374, 358, 341, 355, 342, 334, 353, 346, 355, 344,
349, 330, 352, 328, 336, 359, 361, 345, 324, 386,
334, 370, 349, 327, 342, 354, 361, 354, 377, 324])
q = ... | <p><a href="https://github.com/numpy/numpy/blob/v1.15.1/numpy/lib/function_base.py#L3543-L3644" rel="nofollow noreferrer">https://github.com/numpy/numpy/blob/v1.15.1/numpy/lib/function_base.py#L3543-L3644</a></p>
<pre><code>default value is linear
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'... | python|numpy | 1 |
369,708 | 55,219,951 | Looping through data from a function to create a table in templates using Django | <p>I have a function called <code>def get_scraped_data():</code>that is essentially a web <strong>scraper</strong> . It returns a DataFrame called newlaw with all my desired data. The entire code is below.</p>
<pre><code>def get_scraped_data():
from bs4 import BeautifulSoup
import requests
import pandas as ... | <p>You should wrap all the code in <em>tls.py</em> in a function, which returns <code>newlaw</code> (assuming that's the output you want). So:</p>
<pre><code>def get_scraped_data():
# all your code here
return newlaw
</code></pre>
<p>Then in your view you can do this:</p>
<pre><code>from tls import get_scrap... | python|django|pandas | 0 |
369,709 | 10,050,741 | Accessing properties of objects in a numpy array | <p>I've got a numpy array of custom objects. How can I get a new array containing the values of specific attributes of those objects?</p>
<p>Example:</p>
<pre><code>import numpy as np
class Pos():
def __init__(self, x, y):
self.x = x
self.y = y
arr = np.array( [ Pos(0,1), Pos(2,3), Pos(4,5) ] )
# Ma... | <p>Usually, when I have multiple quantities that belong together and I want to benefit from numpys indexing power I use record arrays. Beware, if you do a lot of append/remove operations, numpy might be rather ineffective in terms of speed.</p>
<p>If I understood your comment correctly, this is an example where two va... | arrays|numpy | 2 |
369,710 | 9,794,697 | Best way to construct a pandas.DataFrame composed of different chunks | <p>I'm running daily simulations in a batch: I do 365 simluations to get results for a full year. After every run, I want to extract some arrays from the results and add them to a pandas.DataFrame for analysis later. </p>
<p>I have a rough model (doing an optimisation) and a more precise model for a post-simulation, ... | <p>I think that using <code>DataFrame.combine_first</code> could be the way to go, but depending on the scale of the data, it might be more useful to have a method like "update" that just modified particular rows in an existing DataFrame. <code>combine_first</code> is more general and can cause the result to be of a di... | python|pandas | 1 |
369,711 | 9,860,412 | 'ValueError: Nothing can be done for the type <class 'numpy.core.records.recarray'> at the moment' error | <p>I am trying to run a simple linear regression (using rpy2 from Python) and encountered a strangely worded error when running the script below:</p>
<pre><code>from numpy import array, rec
from numpy.random import normal as nprandom
from rpy2.robjects import numpy2ri, r
foo = array(range(10))
bar = foo + nprandom(0,... | <p>You need to add:</p>
<pre><code>rpy2.robjects.activate()
</code></pre>
<p>after importing <code>numpy2ri</code>. <a href="https://stackoverflow.com/questions/2447454/converting-python-objects-for-rpy2">This SO post</a> references the rpy2 documentation:</p>
<blockquote>
<p>That import alone is sufficient to swi... | python|r|numpy|rpy2 | 1 |
369,712 | 10,129,717 | How access to a single NumPy array in a DICOMDIR file with pydicom? | <p>I am using DICOM with Python and Pydicom library, when I have used .dcm files I hadn't problems. But I am using DICOMDIR data sets now. </p>
<p>My code is the next:</p>
<pre><code>ds = dicom.read_file("dicomdir")
</code></pre>
<p>I tried to access to the <code>pixel_array</code> elements as follows:</p>
<pre><co... | <p>I received an answer in Pydicom User Forum by Suever:</p>
<p>DICOMDIR files do not contain any pixel information but rather basic header information along with the path to each file in the dataset. In order to get the pixel data from each of the images, you'll have to traverse the dicomdir dataset to get the filepa... | python|numpy|dicom|pydicom | 6 |
369,713 | 10,020,138 | Cross correlation of medium sized arrays | <p>I have 16 1D arrays with approximately 10-11 million double-precision elements each. I need to execute a cross-correlation across them, i.e., 1 with 2, 1 with 3, ..., 1 with 16, 2 with 3, 2 with 4, ..., 2 with 16, and so on. This cannot be done efficiently on my MacBook Intel Core 2 duo 2.4 GHz, with 4GB of RAM. My ... | <p>If you calculate the Fourier transform of each of your arrays, you should be
able to use the transformed arrays to efficiently calculate the <a href="http://en.wikipedia.org/wiki/Cross-correlation" rel="nofollow">cross-correlation</a> between each pair of the original input arrays. See the "Properties" section of
... | performance|numpy|cross-correlation | 2 |
369,714 | 10,016,352 | Convert numpy array to tuple | <p><strong>Note:</strong> This is asking for the reverse of the usual tuple-to-array conversion.</p>
<p>I have to pass an argument to a (wrapped c++) function as a nested tuple. For example, the following works</p>
<pre><code>X = MyFunction( ((2,2),(2,-2)) )
</code></pre>
<p>whereas the following <em>do not</em></p... | <pre><code>>>> arr = numpy.array(((2,2),(2,-2)))
>>> tuple(map(tuple, arr))
((2, 2), (2, -2))
</code></pre> | python|numpy | 217 |
369,715 | 7,575,471 | Assigning issue with numpy structured arrays | <p>I was trying this simple line of assigning codes to a structured array in numpy, I am not quiet sure, but something wrong happens when I assign a matrix to a sub_array in a structured array I created as follows:</p>
<pre><code>new_type = np.dtype('a3,(2,2)u2')
x = np.zeros(5,dtype=new_type)
x[1]['f1'] = np.array([[... | <p>I think you want to set things slightly differently. Try:</p>
<pre><code>x['f1'][1] = np.array([[1,1],[1,1]])
</code></pre>
<p>which results in:</p>
<pre><code>In [43]: x = np.zeros(5,dtype=new_type)
In [44]: x['f1'][1] = np.array([[1,1],[1,1]])
In [45]: x
Out[45]:
array([('', [[0, 0], [0, 0]]), ('', [[1, 1], ... | arrays|numpy|structured-array | 2 |
369,716 | 7,186,958 | calculating mean of several numpy masked arrays (masked_all) | <p>first of all I'm new to python and programming but you guys already helped me a lot, so thanks a lot! But I've come to a problem I haven't found an answer so far:</p>
<p>I have the data of several plates where the data represents the pressure on each plate at a large number of different spots. The thing is, these p... | <p>EDIT: Sorry, I misinterpreted the question. Try this:</p>
<pre><code>allplates = ma.masked_all((160, 65, numplates))
# fill in allplates
meanplate = allplates.mean(axis=2)
</code></pre>
<p>This will compute the mean over the last dimension of the array, i.e., average the plates together. Missing values are ignored... | python|numpy | 1 |
369,717 | 7,592,565 | When embedding CPython in Java, why does this hang? | <p>I'm embedding CPython into a JVM using <a href="https://github.com/mrj0/jep" rel="nofollow">Jepp</a>, but when I run</p>
<pre><code>import numpy; numpy.finfo(float)
</code></pre>
<p>the process hangs. gdb says something's blocking a semaphore/lock acquisition, and the stack trace suggests something floating point... | <p>See this post by John Wright who ran into the same problem: <a href="http://mail.scipy.org/pipermail/numpy-discussion/2009-July/044046.html" rel="nofollow">http://mail.scipy.org/pipermail/numpy-discussion/2009-July/044046.html</a></p>
<p>Basically, numpy is using the Python C api in a way that's incompatible with J... | java|python|jvm|numpy|cpython | 1 |
369,718 | 7,670,112 | Finding a subimage inside a Numpy image | <p>I have two Numpy arrays (3-dimensional uint8) converted from PIL images.</p>
<p>I want to find if the first image contains the second image, and if so, find out the coordinates of the top-left pixel inside the first image where the match is.</p>
<p>Is there a way to do that purely in Numpy, in a fast enough way, r... | <p>I'm doing this with <a href="http://opencv.itseez.com/index.html">OpenCV</a>'s <a href="http://opencv.itseez.com/modules/imgproc/doc/object_detection.html?highlight=matchtemplate#cv2.matchTemplate"><code>matchTemplate</code> </a>function. There is an excellent python binding to OpenCV which uses numpy internally, so... | python|image|numpy|python-imaging-library | 36 |
369,719 | 56,818,865 | How to document a 'whatsnew`-rst bugfix before I submit a pandas pull request | <p>I fixed a minor bug in Pandas.</p>
<p>I followed the instructions in the <a href="https://dev.pandas.io/development/contributing.html" rel="nofollow noreferrer">pandas contribution guidelines</a>. I created a new environment, built the pandas source, fixed the bug, ran the testsuite. </p>
<p>All is ready excep... | <p>If you are developing for version <code>vx.y.z</code>, then you will be logging your changes in the <code>vx.y.z.rst</code> file. In your case, <a href="https://github.com/pandas-dev/pandas/blob/master/doc/source/whatsnew/v0.25.0.rst" rel="nofollow noreferrer">0.25.0.rst</a>.</p>
<p>Your pandas version also reflect... | pandas|github | 1 |
369,720 | 56,463,478 | Create conditional column using GroupBy | <p>I want to create a new column in my data frame based on grouping variable in a column in the data frame and then check for condition in another column in the data frame.</p>
<p>I have tried to use np.where with pandas pd.groupby to create a Status column in the data frame where I am checking if the next value in th... | <p>You'll need to apply the condition <em>after</em> the grouping IOW, use the result of <code>groupby</code> with <code>np.where</code>). </p>
<p>I would use <code>groupby</code> and <code>diff</code>, it's the same as comparing the shifted-by-1 value. It's as simple as,</p>
<pre><code>np.where(
df.groupby('Sens... | python|pandas|dataframe|pandas-groupby | 1 |
369,721 | 56,571,706 | Is there a way to do a merge using pandas where one column is a list and another column might contain an element in that list? | <p>Right now I have a two pandas dataframes:</p>
<p>The first one looks like this:</p>
<pre><code>id1 features
0 ['a', 'b']
1 ['c', 'd', 'e']
2 ['f']
</code></pre>
<p>and the second looks like this:</p>
<pre><code>id2 features other
224 'a' 3
264 'z' 3
277 'f' 3
</code></pre>
<p>and I wa... | <p>I think you actually described the most efficient way to do this: <code>expanding the first dataframe into multiple rows per value then doing the join</code>.</p>
<p>The other option I could see is iterating through the second one. Say</p>
<pre><code>df1 =\
id features
0 ['a', 'b']
1 ['c', 'd', 'e']
2 ['f']
... | python|pandas|dataframe|merge | 2 |
369,722 | 56,453,777 | Error tokenizing data. C error: Expected n fields in line j, saw k fix by ignoring extra columns? | <p>I have a (bad) csv file that looks something like this:</p>
<pre><code>model, height, strength
1, 124.5, 63
2, 160.4, 85
3, 144.6, 94, 88
4, 122.5, 36, 29
5, 132, 22
6, 140.6, 46, 200, 0.8
</code></pre>
<p>I would like to create a dataframe that takes all lines, but ignores any "extra" column values, so it would t... | <p>Here is one way:</p>
<p>Read the file with any other seperator:</p>
<pre><code>df = pd.read_csv(pd.compat.StringIO("""model, height, strength
1, 124.5, 63
2, 160.4, 85
3, 144.6, 94, 88
4, 122.5, 36, 29
5, 132, 22
6, 140.6,46, 200, 0.8"""),sep='|')
</code></pre>
<p><strong>Method1</strong>:
Split the values based ... | python|pandas|dataframe | 2 |
369,723 | 56,529,198 | how can i improve number predictions? | <p>I've got some number classification model, on test data it works OK, but when I want to classifier other images, I faced with problems that my model can't exactly predict what number is it. Pls, help me improve the model.predict() performance.</p>
<p>I've tried to train my model in many ways, in the code below ther... | <p>what do you mean "on test data it works OK"? if you mean its works good for train data but do not has a good prediction on test data, maybe your model was over-fit in training phase. i suggest to use train/validation/test approach to train your network.</p> | python-3.x|tensorflow|keras|predict|cv2 | 0 |
369,724 | 56,468,810 | How to approximate the root(s) of a discrete numpy array? | <p>I'm trying to find the point where my data passes through some critical value (e.g. passes through zero), and I want to numerically approximate where that critical value occurs. I can do it 'by hand' for one case but need to generalize so that I can quickly repeat the process a few dozen times across all of my data.... | <p>The simplest method - you could <a href="https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html" rel="nofollow noreferrer">interpolate</a> your data in x and y to make it "more" continuous. Then see where the minimum between 0 and y occurs.</p> | python|numpy|matplotlib | 1 |
369,725 | 56,635,186 | pandas how to calculate delta only given month and day | <p>I have the following <code>df</code>,</p>
<pre><code>doc_date date_string
2019-06-03 WW0306
2019-06-07 EH0706
</code></pre>
<p><code>doc_date</code> is of <code>datetime64</code> with <code>year-month-day</code> format; <code>date_string</code> is of string <code>dtype</code> with <code>day/month</code> or <c... | <p>IIUC, you convert the <code>date_string</code> column to datetime after <code>replace</code> and use<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.dayofyear.html" rel="nofollow noreferrer"><code>series.dt.dayofyear</code></a> to access the day of year for both the columns and co... | python|python-3.x|pandas|dataframe|datetime | 2 |
369,726 | 56,544,250 | Calculate ratio (starting value of year/ending value of previous year) in multi-index dataframe | <p>As a plausibility check for yearly reports which are send in, I want to make sure that the stating value of a year is correct based on the ending value as submitted in the previous year. With this Multi-index dataframe I try to explain my problem:</p>
<pre><code>import random
col3=[0,0,0,0,2,4,6,0,0,0,100,200,300,4... | <p>IIUC, you can apply a function on groupby:</p>
<pre><code>new_df = df.groupby(['Unit', 'Year']).sum()
new_df['mask'] = (new_df.groupby(level=0, group_keys=False)
.apply(lambda x: x.col3/x.col4.shift())
)
</code></pre>
<p>Then your <code>new_df</code> looks like this:</p>
<pre><... | python|pandas|dataframe|multi-index | 1 |
369,727 | 56,807,287 | Panda.run_sql_query for where .. in .. structure? | <p>I have a sql query with structure of where a in b kind. I am trying to run it through pandas with run_sql_query to get dataframe back. But no data structure seems to work with panda query. What should i have there to make it work?</p>
<p>sql:</p>
<pre><code>Select * from Table where a in (:input)
</code></pre>
<p... | <p>Try this:</p>
<pre><code>myinput = ('a','b','c')
myinput = str(myinput)
#Now your query will end up like
# select * from tablename where value in ('a','b','c')
df = pd.run_sql_query(sql,conn, params= {'input':myinput})
</code></pre> | python|sql|pandas|cx-oracle | 0 |
369,728 | 56,758,078 | Is there an easy way to convert zeep response to json,pandas,xml? | <p>I am using python 3.6 and zeep 3.4.0</p>
<p>Zeep returns raw data and i cannot convert it to xml/json/pandas object.</p>
<p>I've tried to use bs4 to get table from the text1, no luck.
Serialize text1 to get json, no luck too.</p>
<pre class="lang-py prettyprint-override"><code>from zeep import Client, Settings
s... | <p>If you're just trying to get a python dict type out of <a href="https://docs.python-zeep.org/en/master/helpers.html#zeep.helpers.serialize_object" rel="nofollow noreferrer"><code>serialize_object</code></a> helper, you can specify the type you want.</p>
<pre class="lang-py prettyprint-override"><code>from zeep impor... | python|json|pandas|wsdl|zeep | 10 |
369,729 | 56,543,190 | Phase spectrum with python and FFT | <p>I'm trying to calculate a phase spectrum of sinusoid.
The following code generates 1Hz sinusoid with zero initial phase.</p>
<pre><code>import numpy
from numpy import pi, sin, arange
from pylab import plot, show, xlabel, ylabel, xlim, grid
sampling_rate = 500
sampling_time = 1 / sampling_rate
length = 1 # in secon... | <p>When the magnitude is zero, then the phase is given by numerical imprecision.</p>
<p>If you display the values computed by <code>fft</code> you’ll see that the values you expect to be 0 are actually in the order of 1e-16 or something like that. This is numerical imprecision caused by rounding in the floating-point ... | python|numpy|signal-processing|fft | 1 |
369,730 | 56,565,805 | Cluster Rows in Data Subgroups | <p>I have a dataset <code>df</code> of object components in 3-d space - each <code>ID</code> represents an object which has various components:</p>
<pre><code>ID Comp x y z
A 1 2 2 1
A 2 2 1 -1
A 3 -10 1 -10
A 4 -1 3 ... | <p>IIUC, I think you could try something like this:</p>
<pre><code>def ap_fit_pred(x):
ap = AffinityPropagation()
return pd.Series(ap.fit_predict(x.loc[:,['x','y','z']]))
df['cluster'] = df.groupby('ID').apply(ap_fit_pred).reset_index(drop=True)
</code></pre> | python|pandas|scikit-learn|pandas-groupby|pandas-apply | 2 |
369,731 | 56,761,540 | Tensorflow - setting EvalSpec | <p>I am new to tensorflow and do not have a good understanding of the <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/EvalSpec" rel="nofollow noreferrer"><code>EvalSpec</code></a>. I don't understand the concept of evaluation steps. I thought once we have learned (or partially learned) the model, we ev... | <p>Unfortunately the API documentation for that class is very poor. There is more information in the <a href="https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/training.py#L208" rel="nofollow noreferrer">code comments</a>, saying:</p>
<blockquote>
<p><code>steps</code>: <code>... | python|tensorflow|evaluation | 1 |
369,732 | 56,557,515 | Can't convert object datatype to datetime format | <p>I want to convert a column into DateTime format and separate the date and time. I have already got the solution for datetime conversion as given
<a href="https://stackoverflow.com/questions/56554428/typeerror-an-integer-is-required-in-pandas-column">from the link below:</a> and code:</p>
<pre><code>df2['date']=pd.... | <p>There is <code>MultiIndex</code> in columns, so for select columns need tuples:</p>
<pre><code>df2[('date', 'GMT')] = df2[('date', 'GMT')].dt.normalize()
df2[('Time', 'GMT')] = df2[('date', 'GMT')].dt.time
</code></pre> | python|pandas|datetime | 1 |
369,733 | 56,719,240 | Why Tensor must be Integer in Pytorch? | <p>I want to get my accuracy. So I divide the correct number(tensor) by the total number(tensor). Then I get a integrate instead of a float. I wonder why. The code is as follows. Also, if I transfer tensor to numpy, why I cannot get an exact number? I get description like <code>"built-in method numpy of Tensor object a... | <p>You can convert to a floating type using <code>.float()</code> for <code>correct</code> or <code>total</code>. Like so:</p>
<pre><code>correct.float()/total
</code></pre>
<blockquote>
<p>Also, if I transfer tensor to numpy, why I cannot get an exact number?</p>
</blockquote>
<p>The correct way to convert to num... | python|pytorch | 0 |
369,734 | 56,510,756 | Pandas df iteration looking for duplicates | <p>I need some help with some pandas code to iterate a pandas data frame looking back 3 days and forward 3 days relevant to a date in the particular row. </p>
<p>I've tried a number of ways to attack this problem and believe I'm close.</p>
<p>When I run the line of code outside the loop, I get True or false, which is... | <p>I cannot test it without a sample of your data, but I think the following should do the job.</p>
<p>Define a custom function which does the 3-days selection and checks for duplicates. It should return a single boolean value.<br>
Then you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pa... | python|pandas|iteration | 0 |
369,735 | 56,711,640 | Tensorflow Eager Execution - Compute gradient between two layers of a sequential model | <p>I am trying to follow along with the guide at <a href="http://www.hackevolve.com/where-cnn-is-looking-grad-cam/" rel="noreferrer">http://www.hackevolve.com/where-cnn-is-looking-grad-cam/</a>, using Tensorflow's new eager execution mode. One line in particular has me stumped:</p>
<pre class="lang-py prettyprint-over... | <p>Have you tried putting code from <code>predictions = model.predict(img)</code> onwards into the <code>GradientTape</code> context manager?</p>
<p>The thing is, if you did not record the gradients going from <code>last_conv_layer.output</code> to <code>model.output</code>, the backprop chain is effectively broken. <... | python|tensorflow|eager-execution | 0 |
369,736 | 56,678,736 | Passing a .loc[date] slice into altair chart has odd results depending on slice date | <p>Was <a href="https://stackoverflow.com/questions/56661289/bumbling-around-plotting-two-sets-of-seasonal-data-on-the-same-chart">struggling with plotting a few layers of a chart</a> before I realized the layer specification wasn't the problem, but that somehow the slice I pass the chart is acting (to me) oddly. If ... | <p>If you change <code>mark_line()</code> to <code>mark_point()</code>, you'll see that the data is actually there, but it's not showing in the line chart. Why? Because a line is only drawn between adjacent non-null points.</p>
<p>Look at the output of <code>df.loc[idx['20180101':],:]</code>: you'll see that it contai... | pandas|altair | 2 |
369,737 | 56,665,623 | How to convert panda column to int while it has NULL values? | <p>so I'm working on my CSV file, it has a blank like cell " " after every sentence as shown in the picture below. </p>
<p>when I print the columns type using:</p>
<pre><code>print(data.dtypes)
</code></pre>
<p>I get that they are all objects, however I want the columns word_id, head_pred_id, sent_id and run_id to ... | <p>First convert nonnumeric values (like empty strings) to <code>NaN</code>s and then if use pandas 0.24+ is possible convert column to <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html" rel="noreferrer">integers</a>:</p>
<pre><code>data.word_id = pd.to_numeric(data.word_id, errors='coerc... | python|excel|pandas|csv | 8 |
369,738 | 56,666,517 | pandas groupby sums differences between two columns and get the average for each group | <p>I have the following <code>df</code>,</p>
<pre><code>year code col1 col2
2019 1 2 3
2019 1 3 5
2019 1 2 4
2018 2 1 4
2018 2 2 6
</code></pre>
<p>I want to <code>groupby</code> <code>df</code> by <code>year</code> and <code>code</code>, t... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> for new column filled by aggregate values:</p>
<pre><code>df['avg_num'] = (df.assign(avg_num=df.col2 - df.col1)
.groupby(... | python|python-3.x|pandas|dataframe|group-by | 3 |
369,739 | 56,575,293 | Validation loss is lower than training loss training LSTM | <p>I am training a LSTM using tf.learn in tensorflow. I have split the data into training (90%) and validation (10%) for this purpose. As I understand, a model usually fits better training data than validation data but I am getting the opposite results. Loss is lower and accuracy is higher for validation set.</p>
<p>A... | <p><strong>This is not necessarily a problematic phenomenon</strong> in essence.</p>
<p>It can take place due to many reasons, as stated below.</p>
<ol>
<li>It may happen usually when your training data is harder to train on/learn patters on it, while the validation set boasts 'easy' images/data to classify on. The sam... | python|tensorflow|lstm|tflearn | 4 |
369,740 | 56,493,253 | Extract patch and reconstruct image | <p>i am trying my hands on a segmentation task, the images are 3d volumes since i cannot process them at once because of gpu memory constraints, i am extracting patches of the image and performing operations on them.</p>
<p>for extracting the patches i am </p>
<pre><code> def cutup(data, blck, strd):
sh = ... | <p>If things are reasonably simple (not sliding window) then you could possibly use <a href="https://scikit-image.org/docs/stable/api/skimage.util.html#view-as-blocks" rel="nofollow noreferrer">skimage.util.shape.view_as_blocks</a>. For example:</p>
<pre><code>import numpy as np
import skimage
# Create example
data ... | python|numpy|deep-learning|medical | 1 |
369,741 | 56,520,140 | Does Keras's LSTM really take into account the cell state and previous output? | <p>I learned about <code>LSTM</code>'s over the past day, and then i decided to look at a tutorial which uses <code>Keras</code> to create it. I looked at several tutorials and they all had a derivative of </p>
<pre class="lang-py prettyprint-override"><code>model = Sequential()
model.add(LSTM(10, input_shape=(1,1)))
... | <p>You have to give the previous prediction to the LSTM state. If you call predict the LSTM will be initialized every time, it will not remember the state from previous predictions. </p>
<p>Typically (e.g if you generate text with an lstm) you have a loop where you do something like this:</p>
<pre><code># pick a rand... | python|tensorflow|keras|lstm | 2 |
369,742 | 56,626,765 | Why is the correlation coefficient of these two list equal to 1? | <p>I have two list <code>a</code> and <code>b</code> as follows:</p>
<pre><code>a = [4,4,4,1.1]
b = [4,4,4,1.2]
</code></pre>
<p>It is clear that the last value in both the list is different, still why do I get the correlation co-eff (from numpy) to be equal to <code>1</code> in the below code:</p>
<pre><code>prin... | <p>You assume just because the last value is different, the correlation coefficient should not be 1. This assumption however, can be flawed.</p>
<p>The important thing to realize is that correlation is calculated only after adjusting for the scales of each list/feature. With that in mind, you only have two unique pair... | python|numpy|correlation | 4 |
369,743 | 56,603,786 | How group by with Grouper but i want use the most recent date as reference in freq | <p>I want use the last date as reference, not the firts date as the code do, in pandas Grouper.</p>
<p>the idea is the next.</p>
<p>My df is</p>
<pre><code>date value c1 c2
2019-03-06 500000.0 1 1
2019-03-16 500000.0 2 2
2019-04-06 300000.0 1 1
</code></pre>
<p>when I use:</p>
<pre class... | <p>I think that should be 31 days </p>
<pre><code>df.groupby(pd.Grouper(key='date',freq='31D',closed='right', label='right')).sum()
Out[325]:
value c1 c2
date
2019-03-06 500000.0 1 1
2019-04-06 800000.0 3 3
</code></pre> | python|pandas | 2 |
369,744 | 56,491,974 | Building pandas dataframe from JSON | <p>I am trying to create a dataframe from a mongoDB collection dump. </p>
<p>I have referred to this <a href="https://stackoverflow.com/questions/51236433/json-normalize-json-file-with-list-containing-dictionary-sample-included">question</a> to normalize my data but it doesn<code>t help. The output doesn</code>t conta... | <p>Please let me know if you are willing to have the output as: </p>
<pre><code>>>> import pandas as pd
>>> import json
>>> j = [
... {'FileName': '32252652D.article.0018038745057751440210.tmp',
... '_id': {'$oid': '5ced0669acd01707cbf2ew33'},
... 'section_details': [{'content... | python|json|mongodb|pandas | 0 |
369,745 | 56,706,119 | pandas to_datetime from two text columns | <p>I have the following time-series of the format below.</p>
<p>What's the easiest way to convert/combine columns 'date' and 'time' into a pandas datetime format?</p>
<p>I know it should be pandas.to_datetime(date...). But I can't figure out the format to combine them.</p>
<pre><code> ccy date time open ... | <p>This is how you would do the conversion, but you need to make sure the time column makes sense - your table is ambiguous right now when displaying 3 digits for time. Also, make sure your date and time columns are strings, else convert them to strings because joining them sensibly will require it.</p>
<pre><code>imp... | python|pandas|datetime | 0 |
369,746 | 56,683,286 | Any fix for UserWarning: pyarrow.open_stream is deprecated, please use pyarrow.ipc.open_stream? | <p>On converting spark df to pandas df using pyarrow function i am getting following warning:</p>
<blockquote>
<p>UserWarning: pyarrow.open_stream is deprecated, please use
pyarrow.ipc.open_stream</p>
</blockquote>
<p>I am using python 3.7 version and Pyspark 2.4.3
pyspark df size is 170000 rows and 40 columns
On... | <p>Finally I found a solution for the above query. It was a datatype issue. I n one of my column I was generating probability while processing in spark which was giving output as 4.333333 Incase probability is 4.3 and post rounding it off was also not working because while converting itself it was not storing all the r... | pandas|apache-spark|pyspark|pyarrow | 2 |
369,747 | 56,636,341 | How to compute outline of geometry from union of geometries | <p>How can I compute the outline corresponding to the union of a set of geometries? Specifically, given geometry of 50 states, I want the outline of the contiguous continental US.</p>
<p>Using gz_2010_us_040_00_5m.json from
<a href="https://github.com/kjhealy/us-county/tree/master/data/geojson" rel="nofollow noreferr... | <p>Here's what I ended up doing. First, I added a column 'country' to all the states, then used 'dissolve (by='country'):</p>
<pre><code>conus.loc[:,'country'] = 'usa' # produces warning, don't know how to avoid
us = conus.dissolve(by='country', aggfunc = 'sum')
</code></pre> | python|geopandas|shapely | 0 |
369,748 | 56,711,722 | Index numpy array by multiple boolean masks | <p>I have an array x and a list of filters (array of booleans same length as x):</p>
<pre><code>x = np.random.rand(10)
filt1 = x > .2
filt2 = x < .5
filt3 = x % 2 > .02
filters_list = [filt1, filt2, filt3]
</code></pre>
<p>I want to create a filter that is the logical AND of all filters in <code>filters_list... | <p>You can use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.all.html#numpy.all" rel="nofollow noreferrer"><code>numpy.all()</code></a> with the axis and the list of filters. </p>
<pre><code>x = np.arange(10)
filt1 = x > 2
filt2 = x < 9
filt3 = (x % 2) == 1
filters_list = np.all([fil... | python|arrays|numpy|boolean-logic | 0 |
369,749 | 56,466,560 | pandas `value_counts` on a rolling time window | <p>I have a pandas dataframe containing string values and a datetime index, like so: </p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime as dt
import pandas as pd
df = pd.DataFrame(['a', 'b', 'b', 'c', 'b', 'b', 'b'],
[dt(2019, 1, 1), dt(2019, 1, 2),
... | <p>I guess what you are looking for is:</p>
<pre><code>pd.get_dummies(df[0]).rolling('2D').sum()
</code></pre>
<p>Output:</p>
<pre><code> a b c
2019-01-01 1.0 0.0 0.0
2019-01-02 1.0 1.0 0.0
2019-01-03 0.0 2.0 0.0
2019-01-04 0.0 1.0 1.0
2019-01-05 0.0 1.0 1.0
2019-01-06 0.0 2.0 0.0
2019-01-07 0.... | python|pandas|rolling-computation | 8 |
369,750 | 56,647,897 | How to fix pytorch multi processing issue on cpu? | <p>I'm doing inference of pytorch on CPU. I found pytorch is not utilizing all the cores of CPU for prediction. How to use all cores in pytorch?</p> | <h3>Skeleton</h3>
<p>Using the skeleton below I see 4 processes running. You should tweak <code>n_train_processes</code>. I set it to 10 which was 2-much as I have 8 cores. Setting it to 6 work fine.</p>
<pre class="lang-py prettyprint-override"><code>...
import torch.multiprocessing as mp
class MyModel(nn.Module):
... | pytorch | 3 |
369,751 | 56,632,212 | How to get irregular shapes of parameters in TensorFlow | <p>I want to multiply (Hadamard product) a matrix with a trainable tensor of the same size in TensorFlow. I.e. every non-zero element of the matrix is supposed to have a trainable multiplier.
How do I do this?</p>
<p>The following also 'trains' 0-elements of the matrix.</p>
<pre><code>weights = tf.get_variable('weig... | <p>There is a module named <code>tf.sparse</code> which has optimized operations on sparse matrices, however, from what I found, it does not have a sparse variable implementation.</p>
<p>The only way that comes to my mind is to essentially flatten the sparse matrix without the zeros, then you can use a simple 1D varia... | python|tensorflow|variables|parameters | 0 |
369,752 | 56,803,959 | Merge Pandas Multiindexed DataFrame with Singleindexed Pandas DataFrame | <p>I would like to join two DataFrames. The first one is a multi indexed DataFrame and the second is a simple DataFrame. </p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy
a = pd.DataFrame({'a': {('x', 0) : 1, ('x', 1) : 2, ('y', 0): 3, ('y', 1): 5}, 'b': {('x', 0) : 2, ('x', 1) : 4,... | <p>You need <code>stack</code> and <code>reset_index</code> on the multiindex <code>df</code> (which is <code>a</code> in your case). Next, <code>merge</code> and <code>set_index</code> back. Finally, use <code>rename_axis</code> to pretty the multiindex names and <code>unstack</code> to put back multiindex columns:</p... | python|pandas|dataframe|merge|multi-index | 3 |
369,753 | 56,609,000 | I need help creating a graph in python with matplotlib. Data must be read from JSON | <p>I have a JSON file like this:</p>
<pre><code>{"rpm": [
{"Clock": "09:55:44", "Value": 767.0},
{"Clock": "09:55:45", "Value": 759.0},
{"Clock": "09:55:47", "Value": 2302.0},
{"Clock": "09:55:48", "Value": 1973.0},
{"Clock": "09:55:49", "Value": 2199.0},
{"Clock": "09:55:51", "Value": 1040.0},
{"Clock": "09:55:... | <p>Replace part of you code beginning from figura1 with this;</p>
<pre><code>root = tk.Tk()
fig, ax = plt.subplots()
bar=FigureCanvasTkAgg(fig, master=root)
bar.get_tk_widget().pack(side=tk.LEFT,fill=tk.BOTH)
df.plot(kind='bar', x='dates', y='values', ax=ax, legend=True)
ax.set_title('TITLE')
tk.mainloop()
</code></pr... | python|json|pandas|numpy|matplotlib | 0 |
369,754 | 56,856,679 | How to export associated adjacent pandas dataframe data into a dictionary? | <p>I'm wanting to take the following style of dataframe into a dictionary.</p>
<p>Input: </p>
<pre><code>>>>import pandas as pd
>>>df = pd.read_csv('file.csv')
>>>print(df)
Market Rep Name Date Amount
0 A1 B1 C1 D1 1
1 A1 B1 C1 D1 2
2 A1 B1 C1 ... | <p>There are similar questions posted, see <a href="https://stackoverflow.com/questions/19798112/convert-pandas-dataframe-to-a-nested-dict">here</a> for e.g., But this solution below will work.</p>
<ol>
<li>Set indices for all "categories" in your data, these are the keys in your output dict.</li>
<li>Aggregate on the... | python|pandas|dictionary|nested|data-science | 2 |
369,755 | 56,600,918 | How do 'numpy.ndarray' object do not 'numpy.ndarray' object? | <p>When you call DataFrame.to_numpy(), pandas will find the NumPy dtype that can hold all of the dtypes in the DataFrame. But how to perform the reverse operation?</p>
<p>I have an 'numpy.ndarray' object 'pred'. It looks like this:</p>
<blockquote>
<p>[[0.00599913 0.00506044 0.00508315 ... 0.00540191 0.00542058 0.0... | <p>You can solve the issue with one line of code to convert ndarray to pandas df and then to csv file.</p>
<pre><code>pd.DataFrame(X_train_res).to_csv("x_train_smote_oversample.csv")
</code></pre> | python|pandas|numpy|export-to-csv|numpy-ndarray | 12 |
369,756 | 56,558,990 | Why does df['text'].str.contains('.') always return True? | <p>I am writing some python code to replace punctuation in a column of strings in a pandas DataFrame. After replacement, I notice that testing existence of '.' within the resulting string always returns True.</p>
<p>I am using Python 3.7 and spotted this detail while using PyCharm. I have however, been able to reprodu... | <pre><code>print(df['Text'].str.contains('.',regex=False))
>>> 0 False
</code></pre>
<p><code>'.'</code>is any character except line break in regex expresion , you need to tell to pandas if you want to use regex or not</p> | python|pandas | 1 |
369,757 | 56,444,699 | Remove last n days from dataframe | <p>I have a pandas dataframe with datetime index (30 min frequency). And I want do remove "n" last days from it. My dataframe do not include weekends, so if the last day of it is Monday, I want to remove Monday, Friday and Thursday (from the end). So, I mean observed days, not calendar. What is the most pythonic way to... | <p>Pandas knows about Monday to Friday as business days.</p>
<p>So if you want to remove the last n business days from your dataframe, you can just do:</p>
<pre><code>df.drop(df[df.index >= df.index.max().date()-pd.offsets.BDay(n-1)].index, inplace=True)
</code></pre>
<hr>
<p>If you really need to remove <em>obs... | python|pandas|dataframe | 2 |
369,758 | 56,601,019 | Insert into a pandas dataframe slice of another slice from the same dataframe | <p>I have a <code>pandas.DataFrame</code> like this one:</p>
<pre><code>df = pd.DataFrame({'val_1': [np.nan, np.nan, np.nan, 2.34, 2.21, 2.45],
'val_2': [3.1, 3.02, 3.67, np.nan , np.nan, np.nan],
'group': [1, 1, 1, 2, 2, 2]})
df
val_1 val_2 group
0 NaN 3.10 1
... | <p>Fix your code adding the <code>.values</code> </p>
<pre><code>df.loc[df['group']==1, 'val_1'] = df.loc[df['group']==2, 'val_1'].values
df
Out[300]:
val_1 val_2 group
0 2.34 3.10 1
1 2.21 3.02 1
2 2.45 3.67 1
3 2.34 NaN 2
4 2.21 NaN 2
5 2.45 NaN 2
</code... | python|pandas|dataframe | 3 |
369,759 | 56,659,428 | Keras: training performance are different with exact same data and architecture. The only difference is using .Sequential() or .Model() | <p>the model below is from <code>Keras</code> <a href="https://www.tensorflow.org/tutorials/keras/basic_regression" rel="nofollow noreferrer">website</a> and it behaves exactly as expected. It is defined with <code>keras.models.Sequential()</code>. I want to convert it to be defined with <code>keras.models.Model()</cod... | <p>'Linear' activation function is used by default in the dense layer of keras, as well as the output layer of the sequential model you built. </p>
<p>But you specify the activation function as 'sigmoid' in your conversion, which may make a difference.</p>
<p>Here is the description about the default activation funct... | python|tensorflow|machine-learning|keras|deep-learning | 4 |
369,760 | 56,481,762 | Groupby with lambda function and multiple columns | <p>I have a dataframe containing sales data for real estate parcels. I am trying to groupby parcel number then for each parcel number see the most recent sale and the second most recent sale by date along with the corresponding sales price for those two dates.</p>
<pre><code>df =
parcel date amount
101469... | <p>Using these these steps:</p>
<ul>
<li>create a <code>df1</code> using <code>sort_values</code>, <code>groupby</code> and pick top 2 rows of each group </li>
<li>add <code>key</code> columns to <code>df1</code> using <code>cumcount</code> (convert it to <code>str</code>) </li>
<li><code>set_index</code> and <co... | python|pandas|group-by | 0 |
369,761 | 56,661,501 | Why does a pandas dataframe consumes much more RAM than the size of the original text file? | <p>I'm trying to import a large tab/txt (size = 3 gb) file into Python using pandas <code>pd.read_csv("file.txt",sep="\t")</code>. The file I load was a ".tab" file of which I changed the extension to ".txt" to import it with <code>read_csv()</code>. It is a file with 305 columns and +/- 1 000 000 rows.</p>
<p>When I ... | <p>Pandas is cutting up the file, and storing the data individually. I don't know the data types, so I'll assume the worst: strings.</p>
<p>In Python (on my machine), an empty string needs 49 bytes, with an additional byte for each character if ASCII (or 74 bytes with extra 2 bytes for each character if Unicode). That... | python|pandas | 12 |
369,762 | 56,715,797 | Keyerror problem when merging a single column from a dataframe | <p>I have two dataframes where i want to add a single column from dataframe2 to dataframe1. When I merge them using <code>dataframe1.merge(dataframe2, on = 'Name')</code> it works but doesn't add any columns. When I use <code>dataframe1.merge(dataframe2['AvgUnitPrice'], on = 'Name'</code>) it gives me <code>KeyError pr... | <p>In your code sample you wrote <em>#Renaming no name columns</em>.</p>
<p>This is in contradiction with the way you used <em>read_csv</em>.
Since you passed neither <em>header</em> nor <em>names</em> parameters,
<em>read_csv</em> executes the default variant concerning column name
setting, namely <em>names-'infer'</... | python|pandas | 0 |
369,763 | 56,719,656 | Cross column search in pandas dataframe | <p>I have dataframe with columns <code>source_image_name</code>, <code>dest_image_name</code>, <code>score</code>. The rows have duplicates where the <code>source_image_name</code> is in the <code>dest_image_name</code> and vice-versa. I am trying to remove this occurrence.</p>
<p>I've tried iterating using iterrows()... | <p>The idea of hashes is the good direction, but you don't need to go to the lenght to hashing.<br>
It's enough to concatenate the <code>source_image</code> name and <code>dest_image</code> name in lexicographical order. So, if the two names are switched, you end with the same control string. Then you can search for du... | python|pandas|search | 0 |
369,764 | 56,628,716 | Merging CSV files in python | <p>I have been trying to merge several csv files into one but its showing me some error. I am new to python, your help will be highly appreciated.</p>
<p>Following is my code:</p>
<pre><code>import pandas as pd
import numpy as np
import glob
all_data_csv = pd.read_csv("C:/Users/Am/Documents/A.csv", encoding='utf-8')... | <pre><code>#run the same code with little addon
pd.read_csv("C:/Users/Am/Documents/A.csv",header=0,encoding = "ISO-8859-1")
</code></pre> | python|pandas|csv|merge | 0 |
369,765 | 56,700,158 | Pandas drop rows where the difference hasn't reached a threshold | <p>So let's say we have a table like this, (time, distance, velocity, change in distance, in meters and seconds):</p>
<pre><code> t d v delta_d
0 0 1.0 0.5 NaN
1 1 1.5 0.1 0.5
2 2 1.6 0.1 0.1
3 3 1.7 0.0 0.1
4 4 1.7 0.1 0.0
5 5 1.8 0.1 0.1
6 6 1.9 0.6 0.... | <p>I hope i understand your question correctly,
to find out different value per row you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.diff.html" rel="nofollow noreferrer">pandas.DataFrame.diff</a></p>
<pre><code>df = pd.DataFrame({'a': [1, 2, 4, 6, 5, 10]})
df['diff']=df.... | python|pandas | 1 |
369,766 | 56,703,517 | Pandas dataframe: How to set values after an index to 0 | <p>I have a Pandas dataframe, each row contains a name followed by many numbers in the columns. After a specific index for each row (calculated uniquely in every row), I want to set all the remaining values in that row to 0. </p>
<p>So, I tried out a few things and have the below working code:</p>
<pre><code>for i in... | <p>you could do :</p>
<pre class="lang-py prettyprint-override"><code>
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(4, 4), columns=list('ABCD'))
# A B C D
# 0 0.750017 0.582230 1.411253 -0.379428
# 1 -0.747129 1.800677 -1.243459 -0.098760
# 2 -0.742997... | python|pandas|dataframe | 1 |
369,767 | 56,681,976 | Pandas, reverse one hot encoding | <p>I one hot encoded some variable and after some computation I would like to retrieve the original one.</p>
<p>What I am doing is the following:</p>
<p>I filter the one hot encoded column names (they all start with the name of the original variable, let say <code>'mycol'</code>)</p>
<pre><code>filter_col = [col for... | <p>If need sum values per rows:</p>
<pre><code>(X_test[filter_col]*filter_col).sum(axis=1)
</code></pre>
<p>Solution if possible only <code>0</code> per rows or multiple <code>1</code> per rows:</p>
<pre><code>X_test = pd.DataFrame({
'mycolB':[0,1,1,0],
'mycolC':[0,0,1,0],
'mycolD':[1,0,0,... | python|pandas|one-hot-encoding | 2 |
369,768 | 25,779,297 | SymPy lambdify raises OverflowError: math range error | <p>So, I have this code</p>
<pre><code>from __future__ import division, print_function
import sympy as sp
import numpy as np
from sympy.utilities.lambdify import *
u = np.random.uniform(4, 6, 500)
w, k = sp.symbols('w k')
f = sp.log((k - w) * sp.exp((k - w)**5))
l = sum(f.subs(dict(k=k)) for k in u)
</code></pre>
<p... | <h2>Answering your question:</h2>
<p>The problem is that:</p>
<pre><code>z_lambdify = lambdify(w, l)
</code></pre>
<p>tells the new function to perform the calculations using the built-in <code>math</code> functions, which you can check running with <code>cProfile.run('z_lambdify(1)')</code>; while doing <code>z_sub... | python|numpy|lambda|overflow|sympy | 1 |
369,769 | 25,736,127 | Pandas groupby with dict | <p>Is it possible to use a dict to group on elements of a column? </p>
<p>For example:</p>
<pre><code>In [3]: df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'],
...: 'B' : np.random.randn(8)})
In [4]: df
Out[4]:
A B
0 one 0.751612
1 one 0.333008
2... | <p>From <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#splitting-an-object-into-groups" rel="nofollow">the docs</a>, the dict has to map from <em>labels</em> to group names, so this will work if you put <code>'A'</code> into the index:</p>
<pre><code>grouped2 = df.set_index('A').groupby(d)
for group... | python|pandas | 4 |
369,770 | 25,882,030 | GNU Radio filter design tool (gr_filter_design) | <p>I am having some trouble getting the filter design tool to even start. When starting the application I get </p>
<pre><code>"This example requires a Numerical Python Extension, but
failed to import either NumPy, or numarray, or Numeric.
NumPy is available at http://sourceforge.net/projects/numpy".
</code></pre>
... | <p>You are getting this error as </p>
<pre><code>from PyQt4.Qwt5.anynumpy import *
</code></pre>
<p>in polezero_plot.py (/usr/lib/python2.7/site-packages/gnuradio/filter) is failing.</p>
<p>Just try replacing</p>
<pre><code>from PyQt4.Qwt5.anynumpy import * ( line no 25)
</code></pre>
<p>with </p>
<pre><code>fr... | python|numpy|gnuradio | 1 |
369,771 | 25,526,433 | Manipulating array elements in NumPy | <p>I have a given array 'a' as follows:</p>
<pre><code>import numpy as np
a = np.arange(-100.0, 110.0, 20.0, dtype=float) #increase 20
a = np.tile(a, 4)
a = a.reshape(4,11)
[[-100. -80. -60. -40. -20. 0. 20. 40. 60. 80. 100.]
[-100. -80. -60. -40. -20. 0. 20. 40. 60. 80. 100.]
[-100... | <p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fliplr.html" rel="nofollow"><code>np.fliplr</code></a>:</p>
<pre><code>b = np.fliplr(a)
print b
[[ 100. 80. 60. 40. 20. 0. -20. -40. -60. -80. -100.]
[ 100. 80. 60. 40. 20. 0. -20. -40. -60. -80. -100.]
... | python|arrays|numpy | 2 |
369,772 | 25,915,225 | Pandas dataframe groupby to calculate population standard deviation | <p>I am trying to use groupby and np.std to calculate a standard deviation, but it seems to be calculating a sample standard deviation (with a degrees of freedom equal to 1).</p>
<p>Here is a sample.</p>
<pre><code>#create dataframe
>>> df = pd.DataFrame({'A':[1,1,2,2],'B':[1,2,1,2],'values':np.arange(10,30,... | <p>You can pass additional args to <code>np.std</code> in the <code>agg</code> function:</p>
<pre><code>In [202]:
df.groupby('A').agg(np.std, ddof=0)
Out[202]:
B values
A
1 0.5 2.5
2 0.5 2.5
In [203]:
df.groupby('A').agg(np.std, ddof=1)
Out[203]:
B values
A ... | python|numpy|pandas|statistics | 25 |
369,773 | 25,796,744 | Access the value of a pandas datetime Timestamp in multiple rows - syntax? | <p>I have a columns of dates that I need to be able to access the value of in a logical operation. I can do this easily for 1 row, but I can't figure out the syntax to let me look at all rows.</p>
<p>I am trying to find all values withing a time range and in a certain location</p>
<pre><code>Y=x.loc[xx.timestamp[:].... | <p>Series doesn't have an attribute month (even if it's a datetime Series):</p>
<pre><code>In [11]: s = pd.Series(pd.to_datetime('2014-01-01'))
In [12]: s
Out[12]:
0 2014-01-01
dtype: datetime64[ns]
</code></pre>
<p>You can wrap the Series as DatetimeIndex which does have a month attribute:</p>
<pre><code>In [13]... | python|pandas | 3 |
369,774 | 25,453,173 | numpy array concatenation error: 0-d arrays can't be concatenated | <p>I am trying to concatenate two numpy arrays, but I got this error. Could some one give me a bit clue about what this actually means?</p>
<pre><code> Import numpy as np
allValues = np.arange(-1, 1, 0.5)
tmp = np.concatenate(allValues, np.array([30], float))
</code></pre>
<p>Then I got </p>
<pre><code>Va... | <p>You need to put the arrays you want to concatenate into a sequence (usually a tuple or list) in the argument.</p>
<pre><code>tmp = np.concatenate((allValues, np.array([30], float)))
tmp = np.concatenate([allValues, np.array([30], float)])
</code></pre>
<p>Check the <a href="http://docs.scipy.org/doc/numpy/referenc... | python|arrays|numpy|concatenation | 16 |
369,775 | 25,444,932 | Merge multiple data frames with different dimensions using Pandas | <p>I have the following data frames (in reality they are more than 3).</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'head1': ['foo', 'bix', 'bar'],'val': [11, 22, 32]})
df2 = pd.DataFrame({'head2': ['foo', 'xoo', 'bar','qux'],'val': [1, 2, 3,10]})
df3 = pd.DataFrame({'head3': ['xoo', 'bar',],'val': [20, 100]... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-objects"><code>pandas.concat</code></a> selecting the <code>axis=1</code> to concatenate your multiple DataFrames. </p>
<p>Note however that I've first set the index of the <code>df1, df2, df3</code> to use the variables (fo... | python|pandas | 10 |
369,776 | 25,815,491 | Python Pandas Groupby Behavior | <p>I am trying to understand/use the groupby in Pandas to obtain the maximum count within each group and then return the row with the max count</p>
<pre><code>df = pd.DataFrame({'name':['alpha','beta','gamma','delta','epsilon'], 'year':[2000,2001,2000,2001,2000], 'count':[1,25,11,20,8]})
df
count name year
... | <p>You can use <code>idxmax</code> to collect the index of the maximum row, and then use <code>df.iloc</code> to select the row:</p>
<pre><code>In [73]: df.iloc[df.groupby('year')['count'].idxmax()].set_index('year')
Out[73]:
count name
year
2000 11 gamma
2001 25 beta
</code></pre>
<... | python|pandas|group-by|ipython | 1 |
369,777 | 25,601,346 | A faster way to do these dataframe operations? | <p>I am loading a dataframe from csv, and then performing the operations below. Loading the dataframe takes about 2 seconds. The other operations ( mainly the date conversions ) take 30 seconds. Is there a way to speed up the other operations?</p>
<pre><code>df = pd.DataFrame.from_csv( fn, index_col=None )
df['SCHEDU... | <p>Not really a solution, but a way to do this faster is having the dates in standard ISO format ...</p>
<p>To illustrate this can make a big difference, some timings (with a column of 10000 date strings):</p>
<pre><code># with standard ISO formatted strings (%Y-%m-%d %H:%M:%S)
In [52]: %timeit pd.to_datetime(df['dat... | python|numpy|pandas|anaconda | 2 |
369,778 | 26,282,434 | Pandas Python: take a subset of df by row labels while using re.IGNORECASE | <p>I have df which looks like this:</p>
<pre><code>print df_raw
Name exp1
Name
UnweightedBase 1364
Base 1349
BFC_q5a1 34.18%
BFC_q5a2 2.93%
BFC_q5a3 1.86%
BFC_q5a4 1.93%
BFC_q5a5 0.84%
</code></pre>
<p>I want to build subset from t... | <p>I don't know of any neat way to search index labels in a case-insensitive way (<code>df.filter</code> is useful but doesn't appear to be able to ignore case unfortunately).</p>
<p>To get around this, you could make use of the series method <code>pd.Series.str.contains</code> which <em>can</em> ignore case:</p>
<pr... | python|regex|pandas|dataframe|ignore-case | 1 |
369,779 | 25,956,916 | Indirect-ish sort with Numpy | <p>With numpy, you can do an indirect sort. That is, from an array like </p>
<pre><code>>> a = array([ 8, 10, 5, 2, 3, 1, 6])
</code></pre>
<p>And then do an indirect sort like this:</p>
<pre><code>>> np.argsort(a)
>> array([5, 3, 4, 2, 6, 0, 1])
</code></pre>
<p>This array says something lik... | <p>You just need to argsort the argsort again:</p>
<pre><code>>>> a.argsort().argsort()
array([5, 6, 3, 1, 2, 0, 4], dtype=int64)
</code></pre> | python|sorting|numpy | 6 |
369,780 | 26,243,993 | Operations on every row in pandas DataFrame | <p>I want to iterate through every row in a pandas DataFrame, and do something with the elements in each row. </p>
<p>Right now I have</p>
<pre><code>for row in df.iterrows():
if row['col'] > 1.5:
doSomething
</code></pre>
<p>but it tells me that the 'tuple indices must be integers, not str' . How do... | <p>Probably the simplest solution is to use the <strong>APPLYMAP</strong> or <strong>APPLY</strong> fucntions which applies the function to every data value in the entire data set.</p>
<p>You can execute this in a few ways: </p>
<pre><code>df.applymap(someFunction)
</code></pre>
<p>or</p>
<pre><code>df[["YourColumn... | python|pandas|dataframe | 6 |
369,781 | 67,074,115 | Torch: how to concatenate tensors of different sizes? | <p>I have two tensors:</p>
<pre class="lang-py prettyprint-override"><code>rc of size: torch.Size([128, 16, 1])
xt of size: torch.Size([128, 40, 1])
</code></pre>
<p>I would like to concatenate xt to rc along dimension 2 so that the final size of rc_xt is:</p>
<pre class="lang-py prettyprint-override"><code>rc_xt = tor... | <p>"Increasing" the size of <code>rc</code> can be done simply by <a href="https://pytorch.org/docs/stable/nn.functional.html#pad" rel="nofollow noreferrer">padding</a>.<br />
For instance, you can pad it by zeros:</p>
<pre class="lang-py prettyprint-override"><code>p_rc = nnf.pad(rc, (0, 0, 0, xt.shape[1]-rc... | python|pytorch | 1 |
369,782 | 67,016,483 | Python Check String in Column to perform an equation | <p>I have a df that looks like below and I am trying to create a new column called <code>df['Seat_AVAIL']</code> based on the <code>plan</code> column and the <code>Mem_Count</code> column.</p>
<p>Essentially:</p>
<p>IF <code>df['Plan']</code> = (<code>'LUX'</code> or <code>'Premium'</code>) then, calculate <code>df['S... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a> with specified masks and outputs, if no match any mask values is return same column:</p>
<pre><code>m1 = df['Plan'].isin(['LUX', 'Premium'])
m2 = df['Plan'] == 'Limited'
m3 = df['P... | python|pandas|numpy | 1 |
369,783 | 66,940,526 | Numpy setting every column in a matrix to a certain value matching a condition | <p>I have a matrix D and sort every row with the indicies (argsort). I'm trying to set values of some_matrix at indicies 1-5 in np.argsort(D) to 1. What I have below does what I need, but is there a way to do this in one line with numpy arrays?</p>
<pre><code>some_matrix = np.zeros((n,n))
for i in range(n):
some_m... | <p>Firstly, note that you don't need a full sort, only a partition of elements 1-4 (I assume you need elements 1,2,3,4, because that's what your code does). So let's use that:</p>
<pre><code>#assuming you want indices 1,2,3,4 of the sorted array, in any order
indices = np.argpartition(D, (1, 4), axis=1)[:, 1:5]
</code>... | python|numpy | 0 |
369,784 | 67,132,252 | What better ways are there to add a column to a pandas.Series? | <pre class="lang-py prettyprint-override"><code>import pandas
series1 = pandas.Series({
'a':1,
'b':2,
})
dict = series1.to_dict()
dict['c'] = 3
series2 = pandas.Series(dict)
</code></pre>
<p>I need to add a column/index onto <code>series1</code>. Current, as shown above, I'm creating <code>series2</code> by maki... | <p>You can do it via the append function.</p>
<pre><code>series2 = series1.append(pd.Series({'c':2}))
</code></pre>
<p>If you wanna use all the dataframe methods then you can convert series object to dataframe objects via -</p>
<pre><code>series1.to_frame()
</code></pre> | python|pandas|data-science | 1 |
369,785 | 66,952,387 | find most recent date when value was higher/lower than current in group | <p>I have a dataframe with grouping column (<code>gr</code>), date (<code>c</code>) (d1 - means current day, d6 - six days ago) and value column (<code>v</code>). For every group, I want to find the most recent date when value was lower (or higher) than current value in expanding way.</p>
<p>Here is toy-example with so... | <p>You can do cartesian product within each group, then filter out those rows where <code>c</code> values on the right are not higher than those on the left (<code>c < c_</code>: e.g. we only want to compare <code>d3</code> to <code>[d4, d5, d6]</code>)</p>
<p>What remains is to find the lowest <code>c_</code> where... | pandas|pandas-groupby | 1 |
369,786 | 67,065,117 | how to subtract rows and make new rows? | <p>How I can subtract rows of my data set and make a new row for each?</p>
<p>data:</p>
<pre><code>date A B C
2020-01-1 2 3 4
2020-01-1 2 4 1
2020-01-1 3 2 1
</code></pre>
<p>output:</p>
<pre><code>date A B C
2020-01-1 2 3 4
2020-02-1 ... | <p>Try:</p>
<pre><code>df.append(df.iloc[:,1:].diff().iloc[1:] # differences
.assign(date=df.iloc[1:,0]+' - '+df.iloc[:-1,0].values) # append dates
)
</code></pre>
<p>Output:</p>
<pre><code> date A B C
0 2020-01-1 2.0 3.0 4.0
1 2020-01-1 2.... | pandas|dataframe | 1 |
369,787 | 66,844,973 | How to use pandas dataframe to add a column to a dataframe that labels data as 1 or 0 based on matching columns in another df | <p>I'm working on labeling some Medicare datasets for machine learning algorithm as fraudulent or non-fraudulent using the Pandas dataframes. The labeling involves matching the NPI numbers in the DMPOES dataset to the NPI number in the LEIE dataset. Each dataset includes a column named "NPI". I need to be abl... | <p>You can use merge. It's actually cleaner IMO if you don't rename the cols because you'll have to deal with suffixes after the merge. Once you merge you can use np.where to update the Fraudulent col based upon the presence of NaN values where there two merge cols didn't have a match. Not totally sure that is the logi... | python|pandas|dataframe | 0 |
369,788 | 66,868,112 | pandas & split() makes the blank row in excel | <p>I made columns string as below</p>
<pre><code>columns = ['a b c d e'.split(' ')]
</code></pre>
<p>This is for my convenient instead 'a', 'b', .........</p>
<p>then, set the df as below</p>
<pre><code>df = pd.DataFrame(top, columns=columns)
</code></pre>
<p>finally, I sent it to excel. There it is.</p>
<pre><code> ... | <p>Problem is you pass nested lists, so get <code>MultiIndex</code> with one level, for avoid it use:</p>
<pre><code>top = pd.DataFrame({
'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2,4]
})
columns = 'a b c d e'.split()
#assign ... | python|pandas | 0 |
369,789 | 66,873,968 | FileNotFoundError: [Errno 2] No such file or directory: 'corpus_or_AB_FMC.xlsx' | <p>I have a directory which contains a lot of excel files. My aim is to read all those excel files and extract some information in them. I used the script below to read the directory but I am still getting an error. The files are identified but the code tell it is not founding them which is strange because there is a l... | <p><code>file</code> is a file's name and does not include the path to it. Use <code>os.path.join</code>:</p>
<pre><code>sentences = pd.read_excel(os.path.join(root, file), sheet_name=0)
</code></pre>
<p>to join the file name and its absolute path.</p> | python|python-3.x|django|excel|pandas | 1 |
369,790 | 66,774,293 | Wall damage detection | <p>I'm lanning to create a real-time wall damages detector [scratches, Cracks] using <a href="https://pytorch.org/hub/ultralytics_yolov5/" rel="nofollow noreferrer">YOLOv5</a> and my custom dataset of images (125).</p>
<ol>
<li>Do you think I can do transfer learning or it won’t be possible since the coco dataset class... | <p>If your dataset is small (like in you case), transfer learning will almost always give better results when compared to training from scratch. As for your second question, yes. The more data you get, the better your model will be able to learn and perform. Considering that it's a relatively different task than which ... | machine-learning|deep-learning|pytorch|object-detection | 0 |
369,791 | 66,950,646 | Python: How to merge duplicate rows only if they are exactly similar in Pandas? | <p>I have a dataframe with columns <code>Items</code> and <code>Ranges</code>.</p>
<pre><code> Items Ranges
0 A 30
1 A 30
2 A -10
3 B 20
</code></pre>
<p>I want to merge duplicate rows and add the range values but only for the rows that are exactly the same. The resulting datafr... | <p>You can groupby and aggregate like:</p>
<pre><code>df.groupby(['Items', 'Ranges'], as_index=False).agg({'Items': 'first', 'Ranges': 'sum'})
</code></pre>
<p>Output:</p>
<pre><code> Items Ranges
0 A -10
1 A 60
2 B 20
</code></pre> | python|pandas|dataframe|merge | 2 |
369,792 | 67,149,749 | I have built the classification model using tensorflow estimator after saving the model , when converting it into tensorflow lite it shows an error | <pre><code>import tensorflow as tf
converter = tf.lite.TFLiteConverter.from_saved_model("/content/drive/MyDrive/tensorflowtest/1618754788") #path to the SavedModel directenter code hereory
converter.target_spec.supported_ops = [
tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.
tf.lite.OpsSet.SEL... | <p>The TF select option in the TFLite product does not allow <code>tf.AsString</code> op yet. For such cases, you can report the feature request at <a href="https://github.com/tensorflow/tensorflow/issues" rel="nofollow noreferrer">here</a>.</p>
<p>The above op isn't included the TF select's allowed list, which can be ... | tensorflow|machine-learning|tensorflow-lite | 0 |
369,793 | 67,165,029 | How to merge pandas dataframe based on substring of column elements python | <p>I have two dataframes A and B. Dataframe A looks like:</p>
<pre><code>col1 col2 col3
a_low 5 6
a_low 3 10
a_high 4 4
</code></pre>
<p>Dataframe B looks like:</p>
<pre><code>col1 colB
a 90
</code></pre>
<p>Now, I want to merge df A and B on the substring <code>a</code> in col1 from df... | <p>You need to extract the part of string from <code>col1</code>, e.g. with <code>str.split</code> or <code>str.extract()</code>, then either merge or map:</p>
<pre><code>dfA['colB'] = (dfA['col1'].str.split('_').str[0]
.map(dfB.set_index('col1')['colB']
)
</code></pre> | python|pandas|dataframe | 2 |
369,794 | 66,877,392 | Matplotlib boxplot with groupby | <p>DataFrame</p>
<pre><code>Year Shows_Released ShowType
2018 13 tvSpecial
2018 14 Short
2018 8 movie
2019 9 tvSpecial
2019 11 Short
2018 10 Documentary
2019 11 movie
2018 6 Docudrama
2... | <p>This should do the trick using only matplotlib:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv('data.csv')
df = df[['Year', 'Shows_Released']].groupby("Year").sum().reset_index()
plt.bar(df.Year, df.Shows_Released,tick_label=df.Year )
plt.savefig("test")
</code... | python-3.x|pandas|matplotlib|boxplot | 0 |
369,795 | 66,855,586 | Error when I add an Embedding Layer to my ANN(Keras Functional API) | <p>Error looks something like this,</p>
<p><em><strong>InvalidArgumentError</strong></em>: indices[14,1] = -34 is not in [0, 6505)
[[node model_12/embedding_16/embedding_lookup (defined at :3) ]] [Op:__inference_train_function_14552]
Errors may have originated from an input operation.
Input Source operations connected... | <p>The error comes from the fact that your input (most likely what you called <em>train_X_ann</em>) must be a tensor of integers with values between 0 and 6504, which correspond to the indices of the tokens you want to embed (since you specified input_dim=6505 for the Embedding layer). Looking at the error, it seems th... | python|tensorflow|keras|nlp|word2vec | 0 |
369,796 | 67,130,086 | Convert dict with list and dict inside to a df | <p>I'm having a bit of an issue. I have a dict looking like this:</p>
<pre><code>example_dict = {"AUTHID":[],"visibility":[], "game_owned": {"game_name": [], "game_playtime":[]}}
</code></pre>
<p>And I'm fetching data on the Steam website using ID as a key in the API to... | <p>We can try flattening the nested dictionary <code>game_owned</code> by making the records from the nested lists present in <code>game_name</code> and <code>game_playtime</code> keys, then prepare a dataframe named <code>games</code> from these records and <code>join</code> it with the dataframe created from the keys... | python|pandas|dataframe|dictionary | 3 |
369,797 | 67,162,851 | Deep learning script detecting GPU after a very long time | <p>The script runs correctly, and it is using the GPU as I have seen activity on my CUDA GPU Performance when the script finally runs.</p>
<p>However, it takes 166 secs to actually start running the model, running the model takes 3 seconds.</p>
<p>My setup is the following:</p>
<pre><code>GPU NV... | <p><code>RTX 3060</code> cards are based on the <code>Ampere</code> architecture for which compatible <code>CUDA version start with 11.x.</code></p>
<p>Your issue can be resolved once you upgrade tensorflow version to <code>2.4.0</code>, CUDA to <code>11.0</code> and cuDNN to <code>8.0</code>.</p>
<p>For more details y... | python|performance|tensorflow | 0 |
369,798 | 66,888,128 | Compare each row of a data frame with all rows of another one | <p><strong>EDIT</strong></p>
<p>The @ashkangh's answer to the original question is perfectly fine, but the question itself turned out to be a bit less trivial: for <code>df1</code> not all possible values for <code>width</code> and <code>thickness</code> but only min and max values are given. Moreover, <code>width</cod... | <p>Using <code>explode</code> method and <code>merge</code> you can get your result:</p>
<pre><code>df1.explode('width').explode('thickness')\
.merge(df2, on=['width', 'thickness'], how='inner')[['order_id', 'piece_id']]
</code></pre>
<p>Output:</p>
<pre><code> order_id piece_id
0 0 13
1 0 ... | python|python-3.x|pandas|dataframe | 1 |
369,799 | 66,901,730 | How To Make A Dataframe From A Variable? | <p>i have a code to print like this :</p>
<pre><code>print('Logistic Regression')
print('Data Train :', logreg.score(X,y))
print('Data Test :', logreg.score(X_test,y_test))
print('KNN')
print('Data Train :', knn.score(X,y))
print('Data Test :', knn.score(X_test,y_test))
</code></pre>
<p>and the output is :</p>
<pre><co... | <p>If those are the only 2 models, you can use this:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame({"Logistic Regression":[logreg.score(X,y), logreg.score(X_test,y_test)], "KNN":[knn.score(X,y), knn.score(X_test,y_test)]}, index=['Data Train', 'Data Test']... | python|pandas|dataframe | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.