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
354,600
53,462,586
PyTrends Keeps returning Google Response with error code 400
<p>I've been trying to pull google trends data for a number of different keywords and have been looping over each keyword using pandas to build each individual payload. However, I keep getting a Google error code of 400 when I try using a particular row of the keyword. This is the code that I have currently</p> <pre><...
<p>I had this error. Turns out you the maximum length of keywords to compare is 5.</p>
python-3.x|pandas|google-trends
1
354,601
53,645,291
python pandas module unable to fetch movie name
<p>i have these test codes about web scraping i am trying out but i am unable to fetch all the names of the movies from the site. Here is the Code</p> <pre><code> from requests import get from bs4 import BeautifulSoup import pandas as pd url = 'http://www.imdb.com/search/title? release_date=2017&amp;sort=num_vot...
<pre><code>from requests import get from bs4 import BeautifulSoup import pandas as pd url = 'http://www.imdb.com/search/title?release_date=2017&amp;sort=num_votes,desc&amp;page=1' response = get(url) print(response.text[:500]) html_soup = BeautifulSoup(response.text, 'html.parser') type(html_soup) movie_containers...
python|pandas
-1
354,602
53,797,811
Filtering data out of several columns
<p>I have this data frame:</p> <pre><code>import pandas as pd df = pd.read_csv('olympics.csv', index_col=0, skiprows=1) for col in df.columns: if col[:2]=='01': df.rename(columns={col:'Gold'+col[4:]}, inplace=True) if col[:2]=='02': df.rename(columns={col:'Silver'+col[4:]}, inplace=True) ...
<pre><code>import pandas as pd import numpy as np df = pd.read_csv('olympics.csv', index_col=0, skiprows=1) for col in df.columns: if col[:2]=='01': df.rename(columns={col:'Gold'+col[4:]}, inplace=True) if col[:2]=='02': df.rename(columns={col:'Silver'+col[4:]}, inplace=True) if col[:2]=='...
python|pandas|dataframe
0
354,603
17,348,670
Matrix addition using triples representation in Python
<p>I'd like to know how I can do matrix addition in <code>Python</code>, and I'm running into quite a number of roadblocks trying to figure out the best way.</p> <p>Here's the problem, written as best as I can formulate it right now.</p> <p>I have a data set, which is an adjacency matrix for a directed graph, in whic...
<p>Here is a straightforward method (you can <code>reset_index()</code> at the end if you want)</p> <p>Create with a multi-index on id1 and id2</p> <pre><code>In [24]: df1 = DataFrame([['ID1','ID2',1],['ID1','ID3',1],['ID2','ID4',1]],columns=['id1','id2','value']).set_index(['id1','id2']) In [25]: df2 = DataFrame([[...
python|python-2.7|matrix|pandas|adjacency-matrix
1
354,604
17,413,175
How can I identify the minimum value in a numpy array, excluding the diagonal zeros?
<pre><code> &gt;&gt;&gt; x array([[ 0, 2, 3, 4], [ 6, 0, 8, 9], [ 1, 2, 0, -9] [ -9, 4, 3, 0]) </code></pre> <p>I want to be able to identify -9 as the min(x), not 0.</p> <p>Thanks</p>
<ol> <li><p>Set the diagonal to the maximum value of its <code>dtype</code>. For floating point types, that would be <code>np.inf</code>, but for integers, you have to work a little harder.</p> <pre><code>x[np.diag_indices_from(x)] = np.iinfo(x.dtype).max </code></pre></li> <li><p>Take the <code>min</code>.</p></li> <...
python|arrays|numpy
4
354,605
17,495,999
convert dataframe from wide layout to SQL-style slim layout
<p>How can I convert a dataframe like this:</p> <pre><code> a b c 0 1.067683 -1.110463 0.208670 1 -1.321405 0.368915 -1.055342 2 -0.807333 0.082980 -0.873361 </code></pre> <p>into</p> <pre><code> det value 0 a 1.067683 1 a -1.321405 2 a -0.807333 3 b -1.110463 4 ...
<p>You can do this with <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-melt" rel="nofollow"><code>melt</code></a>:</p> <pre><code>In [11]: from pandas.core.reshape import melt In [12]: melt(df) Out[12]: variable value 0 a 1.067683 1 a -1.321405 2 a -0.8073...
python|pandas
3
354,606
17,492,923
Reading data from csv into pandas when date and time are in separate columns
<p>I looked at the answer to this question: <a href="https://stackoverflow.com/questions/11615504/parse-dates-when-yyyymmdd-and-hh-are-in-separate-columns-using-pandas-in-python">Parse dates when YYYYMMDD and HH are in separate columns using pandas in Python</a>, but it doesn't seem to work for me, which makes me think...
<p>You should update your pandas, I recommend the <a href="http://pandas.pydata.org/getpandas.html" rel="nofollow">latest stable version</a> for the latest features and bug fixes.</p> <p><em>This specific feature was <a href="http://pandas.pydata.org/pandas-docs/version/0.8.0/whatsnew.html#other-new-features" rel="nof...
python|datetime|csv|pandas
3
354,607
17,397,483
How does NumPy process docstrings into sphinx documentation for Parameters?
<p>I want to build our documentation using sphinx and get the same formatting on parameters as the NumPy docs ( <a href="https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt" rel="noreferrer">https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt</a> )</p> <p>I have found two ways to do...
<p>NumPy uses a custom Sphinx extension: <a href="https://pypi.python.org/pypi/numpydoc" rel="noreferrer">https://pypi.python.org/pypi/numpydoc</a>.</p> <p>You can install it with</p> <pre><code>pip install numpydoc </code></pre> <p>and then you add it to the sphinx conf.py file by adding to the extensions list</p> ...
numpy|python-sphinx|docstring
19
354,608
17,156,084
unpacking a sql select into a pandas dataframe
<p>Suppose I have a select roughly like this:</p> <pre><code>select instrument, price, date from my_prices; </code></pre> <p>How can I unpack the prices returned into a single dataframe with a series for each instrument and indexed on date?</p> <p>To be clear: I'm looking for:</p> <pre><code>&lt;class 'pandas.core....
<p>You can pass a cursor object to the DataFrame constructor. For postgres:</p> <pre><code>import psycopg2 conn = psycopg2.connect("dbname='db' user='user' host='host' password='pass'") cur = conn.cursor() cur.execute("select instrument, price, date from my_prices") df = DataFrame(cur.fetchall(), columns=['instrument'...
python|sql|pandas
43
354,609
19,962,495
Estimate joint distribution in Python and sample given response variable
<p>I have a sequence of samples from a function <code>Y = f(X)</code> for which there are <code>d</code> random variables, <code>X_1</code>, <code>X_2</code> ... <code>X_d</code> and a response variable <code>Y</code> with settings for <code>X</code> as <code>x_1</code>, <code>x_2</code>, ... <code>x_d</code> and final...
<p>In general this kind of problem belongs to the field of <em>machine learning</em>, a nice python package you might want to check out is <a href="http://scikit-learn.org/stable/" rel="nofollow">scikit-learn</a>. But if all you need is that sampling, simpler structures would do:</p> <ol> <li><p>keep a list of all (x,...
python|numpy|distribution|probability
0
354,610
20,089,007
Calculate weighted pairwise distance matrix in Python
<p>I am trying to find the fastest way to perform the following pairwise distance calculation in Python. I want to use the distances to rank a <code>list_of_objects</code> by their similarity.</p> <p>Each item in the <code>list_of_objects</code> is characterised by four measurements a, b, c, d, which are made on very ...
<p><code>scipy.spatial.distance</code> is the module you'll want to have a look at. It has a lot of different norms that can be easily applied.</p> <p>I'd recommend using the weighted Monkowski Metrik</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.wminkowski.html#scipy.spatia...
python|numpy|matrix|scipy|scikit-learn
12
354,611
20,304,147
In Python and numpy, How do I replace missing values in an array with the previous element? (Masked array?)
<p>I am pretty new to Python, so thank you in advance for your help with this noob question.</p> <pre><code>import numpy as np a=np.arange(30) a[5]=a[10]=0 print a array([10, 11, 12, 13, 14, 0, 16, 17, 18, 19, 0, 21, 22, 23, 24]) </code></pre> <p>How could I change the zeros to be the preceding value? I know I can...
<p>Handling contiguity was tricky. How about:</p> <pre><code>def fill_from_left(a, x=0): to_fill = (a == x) if a[0] == x: raise ValueError("cannot have {} as first element".format(x)) if to_fill.any(): lefts = ~to_fill &amp; (np.roll(a, -1) == x) fill_from = lefts.cumsum() ...
python|arrays|numpy|replace
4
354,612
6,850,012
How to check if PyObject* points to the type numpy.uint8
<p>How do I use the Python C-API to check if a PyObject* points to the type numpy.uint8 etc? </p> <p>(Note that I want to check if the PyObject* points to the type numpy.uint8, not if it points to an instance of the type numpy.uint8.)</p>
<p>You can use <code>PyType_IsSubtype(child, parent)</code> to see if the child type inherits the parent, but it operates on <code>PyTypeObject*</code>, not <code>PyObject*</code>.</p>
python|c|numpy|python-c-api
1
354,613
6,854,008
Curve fitting a large data set
<p>Right now, I'm trying to fit a curve to a large set of data; there are two arrays, x and y, each with 352 elements. I've fit a polynomial to the data, which works fine:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt coeff=np.polyfit(x, y, 20) coeff=np.polyfit(x, y, 20) poly=np.poly1d(coeff) </cod...
<p>Your fit function does not make sense, it takes no parameter to fit. </p> <p>Curve fit uses a non-linear optimizer, which needs a initial guess of the fitting parameters. If no guess is given, it tries to determine number of parameters via introspection, which fails for your function, and set them to one (somethi...
optimization|numpy|scipy|curve-fitting
3
354,614
6,480,310
ctypes pointer into the middle of a numpy array
<p>I know how to get a ctypes pointer to the beginning of a numpy array:</p> <pre><code>a = np.arange(10000, dtype=np.double) p = a.ctypes.data_as(POINTER(c_double)) p.contents c_double(0.0) </code></pre> <p>however, I need to pass the pointer to, let's say, element 100, <em>without copying the array</em>. There must...
<p>Slicing a numpy array creates a view, not a copy:</p> <pre><code>&gt;&gt;&gt; a = numpy.arange(10000, dtype=numpy.double) &gt;&gt;&gt; p = a[100:].ctypes.data_as(ctypes.POINTER(ctypes.c_double)) &gt;&gt;&gt; p.contents c_double(100.0) &gt;&gt;&gt; a[100] = 55 &gt;&gt;&gt; p.contents c_double(55.0) </code></pre>
python|pointers|numpy|ctypes
11
354,615
6,663,127
How to fit polynomial to data with error bars
<p>I am currently using numpy.polyfit(x,y,deg) to fit a polynomial to experimental data. I would however like to fit a polynomial that uses weighting based on the errors of the points.</p> <p>I have found <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html" rel="noreferrer" title...
<p>For weighted polynomial fitting you can use: </p> <pre><code>numpy.polynomial.polynomial.polyfit(x, y, deg, rcond=None, full=False, w=weights) </code></pre> <p>see <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.polynomial.polyfit.html" rel="noreferrer">http://docs.scipy.org/doc/numpy...
python|numpy|scipy|curve-fitting
16
354,616
15,907,869
Reading key-value pairs into Pandas
<p>Pandas makes it really easy to read a CSV file:</p> <pre><code>pd.read_table('data.txt', sep=',') </code></pre> <p>Does Pandas having something similar for a file with key-value pairs? I came-up with this:</p> <pre><code>pd.DataFrame([dict([p.split('=') for p in l.split(',')]) for l in open('data.txt')]) </code><...
<p>If you know the key names beforehand and if the names always appear in the same order, then you could use a converter to chop off the key names, and then use the <code>names</code> parameter to name the columns:</p> <pre><code>import pandas as pd def value(item): return item[item.find('=')+1:] df = pd.read_ta...
python|pandas
4
354,617
15,651,527
How to stop python pandas from adding "00:00:00" to every date?
<p>Writing time series data to a <code>csv</code> file using <code>pandas.Series.to_csv</code> adds <code>00:00:00</code> to every date index which is annoying when the csv file is opened in another application.</p> <pre><code>Date,price 2000-06-01 00:00:00,90.3 2000-06-02 00:00:00,92.69 2000-06-05 00:00:00,96.1 </cod...
<p>With the new version of Pandas you can use the date_format parameter of the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow">to_csv</a> method:</p> <pre><code>df.to_csv(filename, date_format='%Y%m%d') </code></pre>
python|pandas
2
354,618
15,837,767
Reading parts of ~13000 row CSV file with pandas read_csv and nrows
<p>I'm trying to read segments of a CSV file into a pandas DataFrame, and I'm running into trouble when I set nrows to more than a certain point. My CSV file is split up into different segments with different headers/types of data, so I've gone through the file and found the line numbers of the different segments, and ...
<p>You can use <code>warn_bad_lines</code> and <code>error_bad_lines</code> to turn off bad line error &amp; warning:</p> <pre><code>import pandas as pd from StringIO import StringIO data = StringIO("""a,b,c 1,2,3 4,5,6 6,7,8,9 1,2,5 3,4,5""") pd.read_csv(data, warn_bad_lines=False, error_bad_lines=False) </code></pre...
python|csv|python-3.x|pandas
3
354,619
12,059,357
Trying to write numpy array (generated through a loop) into csv format
<p>I have a code that generates a 1-D numpy array in each iteration. I want the arrays to get appended to the end of a CSV file so that I can read all data from Excel. I am currently trying the following method:</p> <pre><code>for loop in range(0,10): # The following part generates the array Array1 = numpy.ar...
<p>I think you need to use append function to append new array with previous array, asarray function converts input to array.</p> <pre><code> else: # Trying to append the new array with the previous array ArrayMain = numpy.append(ArrayMain,Array3) </code></pre>
python|csv|numpy
2
354,620
12,217,385
How can I create a numpy dtype from the string 'long'?
<p>I have a variable that contains the string 'long'. How can I create a numpy dtype object with some type equivalent to long from this string? I have a file with many numbers and the corresponding types. <code>int</code>, <code>float</code> etc. are no problems, only <code>long</code> doesn't work. I don't want to har...
<p>In this particular case, I think you can use <code>getattr</code> to get it from the <code>numpy</code> module itself:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.dtype('long') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: data type not understood...
python|types|numpy
6
354,621
12,616,821
Numpy slicing from variable
<p>I'm trying to slice a numpy array using a slice that is predefined in a variable. This works:</p> <pre><code>b = fromfunction(lambda x,y: 10*x+y, (5,4),dtype=int) # Just some matrix b[1:3,1:3] # Output: # array([[11, 12], # [21, 22]]) </code></pre> <p>But what I want to do is somthing like this:</p> <pre><...
<p>You can use the built-in <code>slice</code> function</p> <pre><code>s = slice(1,3) b[s,s] ds = (s,s) b[ds] </code></pre>
python|numpy|slice
27
354,622
72,039,582
Terminate called after throwing an instance of 'std::bad_alloc' from importing torch_geometric
<p>I am writing in python and getting the error:</p> <p>&quot;terminate called after throwing an instance of 'std::bad_alloc'.<br /> what(): std::bad_alloc.<br /> Aborted (core dumped)&quot;</p> <p>After lots of debugging, I found out the source of the issue is:</p> <pre><code>import torch_geometric </code></pre> <p>I...
<p>This problem is because of mismatched versions of pytorch. The current pytorch being used is 1.11.0, but when scatter and sparse were installed installed scatter and sparse, 1.10.1 were used:</p> <ul> <li>pip install torch-scatter -f <a href="https://data.pyg.org/whl/torch-1.10.1+cu113.html" rel="nofollow noreferrer...
pytorch|python-import|importerror|bad-alloc|pytorch-geometric
1
354,623
72,039,461
Where to find the .py file of a specific tensorflow object in python
<p>I have the following preprocessing pipeline in Tensorflow:</p> <pre><code>data_transformation = tf.keras.Sequential([layers.experimental.preprocessing.RandomContrast(factor=(0.7,0.9)),layers.GaussianNoise(stddev=tf.random.uniform(shape=(),minval=0, maxval=1)), layers.experimental.preprocessing.RandomRotation(factor=...
<p>You can search on the web for :</p> <p><em><strong>tf layers.experimental.preprocessing.RandomContrast</strong></em></p> <p>Then follow the first link : <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/RandomContrast" rel="nofollow noreferrer">RandomContrast</a> and finally click on <em><strong>vi...
python|tensorflow
1
354,624
71,795,928
Matrix automation in sympy and conversion to numpy
<p>So, I am trying to create a <a href="https://i.stack.imgur.com/wWy3m.png" rel="nofollow noreferrer">matrix</a> where the elements are answers to definite integrals. The elements in this matrix (ψ_1, ψ_2, ψ_3, ψ_4). You can see in the matrix that the subscripts of ψ here are just the index of the matrix element. I do...
<p>I'm not really sure what your are asking. Let's say (ψ_1, ψ_2, ψ_3, ψ_4) are symbolic expressions. For convenience, I'm going to represent them as symbols :</p> <pre class="lang-py prettyprint-override"><code>P = Matrix(symbols(&quot;psi1:5&quot;)) P_conj = conjugate(P) z, V = symbols(&quot;z, V&quot;) M = (P_conj *...
numpy|loops|for-loop|matrix|sympy
1
354,625
71,873,522
How do I determine if two lists of numpy arrays are equal
<p>Suppose I have the following arrays:</p> <pre><code>myarray1 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])] myarray2 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])] </code></pre> <p>I get an error if I do the following:</p> <pre><code>myarray1==myarray2 ValueError: The truth value of an arr...
<pre><code>In [21]: alist1 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])] ...: alist2 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])] In [22]: alist1==alist2 Traceback (most recent call last): Input In [22] in &lt;cell line: 1&gt; alist1==alist2 ValueError: The truth value of an array...
python|numpy
2
354,626
72,068,966
Looping through Dask array made of npy memmap files increases RAM without ever freeing it
<h3>Context</h3> <p>I am trying to load multiple .npy files containing 2D arrays into one big 2D array to process it by chunk later.<br>All of this data is bigger than my RAM so I am using the memmap storage/loading system here:</p> <pre><code>pattern = os.path.join(FROM_DIR, '*.npy') paths = sorted(glob.glob(pattern))...
<p>you've opened the file for read-only, so presumably your changes aren't getting flushed to disk. It's impossible to say exactly what's happening without knowing what's in <code># process data</code> but at first glance it seems like you should be using <code>mmap_mode='r+'</code> for starters.</p> <p>See the <a href...
python|numpy|memory|dask|numpy-memmap
2
354,627
71,889,649
(Conv1D) Tensorflow and Jax Resulting Different Outputs for The Same Input
<p>I am trying to use conv1d functions to make a transposed convlotion repectively at jax and tensorflow. I read the documentation of both of jax and tensorflow for the con1d_transposed operation but they are resulting with different outputs for the same input.</p> <p>I can not find out what the problem is. And I don't...
<p>Function <a href="https://www.tensorflow.org/api_docs/python/tf/nn/conv1d_transpose" rel="nofollow noreferrer"><code>conv1d_transpose</code></a> expects filters in shape <code>[filter_width, output_channels, in_channels]</code>. If <code>filters</code> in snippet above were transposed to satisfy this shape, then fo...
python|tensorflow|multidimensional-array|convolution|jax
0
354,628
71,918,113
Groupby 2 categorical variables
<p>I have a dataframe that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>memory confidence</th> <th>Test (1= correct, 2=incorrect)</th> <th>Experiment</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>56</td> <td>1</td> <td>Experiment 1</td> </tr> <tr> <td>1</td...
<pre><code>import numpy as np import pandas as pd df = pd.DataFrame([ [1, 56, 1, 'Experiment 1'], [1, 78, 0, 'Experiment 1'], [1, 98, 0, 'Experiment 1'], [1, 24, 1, 'Experiment 2'], [2, 45, 0, 'Experiment 2'], [2, 87, 1, 'Experiment 2'] ], columns=['ID', 'memory_confidence', 'accuracy', '...
python|pandas|dataframe|statistics|seaborn
1
354,629
72,084,521
Summarizing meteorological data with the help of a loop
<p>I have a meteorological data set with daily precipitation values for 120 years. I would like to prepare this in such a way that I have monthly average values for 4 climate periods at the end. Example: Average precipitation January, February, March, ... for period 1981 - 2010, average precipitation January, February,...
<p>To get the total value per month and then the average per periods 30 years, you need to use a double <code>groupby</code>:</p> <pre><code>df['date'] = pd.to_datetime(df[['year', 'month', 'day']]) years = pd.date_range('1981-01-01', periods=6, freq='30YS').strftime('%Y') labels = [f'{a}-{b}' for a,b in zip(years, ye...
python|pandas|dataframe|loops
1
354,630
71,888,573
Map two dataframe base on a column and create a new column. Also match partial matching
<p>I have two dataframe</p> <p>One with codes and values need to map to other dataframe</p> <pre class="lang-py prettyprint-override"><code>B = pd.DataFrame({'Code': ['a', 'b', 'c', 'a', 'e','b','b','c'], 'Value': [&quot;House with indoor pool&quot;, &quot;House with Gray_C_Door&quot;, &quot;Big Chand...
<p>You can use <code>re</code> (regular expression) in your own function and apply this function to <code>A['Name']</code> (btw initializing 'Newname' is useless here):</p> <pre><code>import re import pandas as pd import numpy as np B = pd.DataFrame({'Code': ['a', 'b', 'c', 'a', 'e','b','b','c'], 'Va...
python|pandas|dataframe|dictionary|replace
2
354,631
71,928,675
Subtracting dates in Python for Gantt chart
<p>I am following a tutorial to make a Gantt chart with this tutorial: <a href="https://towardsdatascience.com/gantt-charts-with-pythons-matplotlib-395b7af72d72" rel="nofollow noreferrer">https://towardsdatascience.com/gantt-charts-with-pythons-matplotlib-395b7af72d72</a></p> <p>I have tried to recreate part of the tes...
<p>You need to convert date column to datetime type first</p> <pre class="lang-py prettyprint-override"><code>df['Start'] = pd.to_datetime(df['Start']) df['End'] = pd.to_datetime(df['End']) # Or df[['Start', 'End']] = df[['Start', 'End']].apply(pd.to_datetime) </code></pre>
python|pandas|gantt-chart
1
354,632
71,838,955
Python: Use numpy flip with memmap
<p>I writting large array so I'm using <a href="https://numpy.org/doc/stable/reference/generated/numpy.memmap.html" rel="nofollow noreferrer">numpy memmap</a></p> <p>At the end of my operation I would like to use flip function but the problem is, the flip function does not apply after using the flush function on memap<...
<p><code>np.flip</code> creates a new array in memory. You need to set the one mapped to the file. The current code only change the reference of <code>fpc</code> so to reference the new array. You can fix that with:</p> <pre class="lang-py prettyprint-override"><code>fpc[:,:] = np.flip(fpc,0) </code></pre> <p><strong>U...
python|numpy
3
354,633
71,845,276
Manipulate pandas dataframe with custom function
<p>I am having trouble with applying a customer function to a dataframe. The function works fine and returns the correct dataframe. However, after having it applied my dataframe is still the old one.</p> <p>My DataFrame is like this:</p> <pre><code>d = {'col 1' : ['a', 'a', 'a', 'b', 'b', 'b'],'col 2' : [1, 1, 2, 2, 1,...
<p>You just need to store the return in a new variable or store it in the same to replace</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd d = {'col 1' : ['a', 'a', 'a', 'b', 'b', 'b'],'col 2' : [1, 1, 2, 2, 1, 2]} df = pd.DataFrame(data = d) df.set_index('col 1') def tester(x): x = x.group...
python|pandas|dataframe|function
1
354,634
71,921,640
how to make DataFlow from CSV in googleDrive to tf DataSet - in Colab
<p>according to the <a href="https://colab.research.google.com/notebooks/io.ipynb" rel="nofollow noreferrer">instructions in Colab</a> I could get buffer &amp; even take a pd.DataFrame from it (file is just example)...</p> <pre><code># ... authentification file_id = '1S1w0Z7g3bI1PGLPR49PW5VBRo7c_KYgU' # titanic #...
<p><strong>drive.CreateFile</strong> HELPED (<a href="https://towardsdatascience.com/3-ways-to-load-csv-files-into-colab-7c14fcbdcb92" rel="nofollow noreferrer">link</a>) - as so as I understand that working in Colab - I am working in a separate environment (separate from my PC &amp; I'net env)... So I tried (according...
tensorflow
0
354,635
71,835,192
Input multiple dates into PySimpleGUI Multiline box
<p>I would like to be able to paste a list of dates from Excel into a PySimpleGUI multiline box and save the entry as a pandas DateTime list.</p> <p>This is my current code:</p> <pre><code>layout = [ [sg.Text(&quot;Please fill out the following fields:&quot;, font=font)], [ sg.Text(&quot;Date List&quot;...
<p>Call method <code>str.splitlines</code> to <code>values['date_list']</code>, and iterate items by method <code>pd.Timestamp</code>.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import PySimpleGUI as sg font = ('Courier New', 11) layout = [ [sg.Text(&quot;Please fill out the following...
python|pandas|datetime|multiline|pysimplegui
1
354,636
71,889,622
Reduce multiclass image classification to binary classification in Pytorch
<p>I am working on an stl-10 image dataset that consists of 10 different classes. I want to reduce this multiclass image classification problem to the binary class image classification such as class 1 Vs rest. I am using PyTorch torchvision to download and use the stl data but I am unable to do it as one Vs the rest.</...
<p>For torchvision datasets, there is an inbuilt way to do this. You need to define a transformation function or class and add that into the <code>target_transform</code> while creating the dataset.</p> <pre class="lang-py prettyprint-override"><code>torchvision.datasets.STL10(root: str, split: str = 'train', folds: Un...
python-3.x|pytorch|tensor|dataloader|pytorch-dataloader
1
354,637
71,813,766
how to add the value from the next row to the current row
<p>I want to group by <code>id</code> column and add the value from the next row to the current row only for the <code>trip</code> column How can I transform the first data frame to the second data frame shown below?</p> <p><a href="https://i.stack.imgur.com/nxfCN.png" rel="nofollow noreferrer"><img src="https://i.stac...
<p>I am not sure if the only thing requested is to concatenate the trip ID of the next row to the current row but if it is, would you consider using shift(-1) ?</p> <pre><code>df['newtrip']=df['trip']+'-'+df['trip'].shift(-1) </code></pre>
python|pandas|pandas-groupby
1
354,638
72,088,567
How to install fastai on Mac m1
<p>I am trying to install fastai (version 1.0.61) on my new Mac m1.</p> <p>I first tried:</p> <pre><code>pip install fastai==1.0.61 </code></pre> <p>This gave me an error that I didn't have cmake, so I installed cmake successfully with <code>brew install cmake</code>.</p> <p>Then, rerunning the fastai install command, ...
<p>fastai seems to need <code>pyenv</code> which needs CUDA to work. CUDA is available only on Nvidia GPUs and the MAC M1 has a completly differente SOC with no Nvidia GPU</p> <p>You can read the actual error</p> <pre><code>CMake Error at /opt/homebrew/Cellar/cmake/3.23.1/share/cmake/Modules/FindCUDA.cmake:859 </code><...
python|macos|deep-learning|pytorch|fast-ai
1
354,639
71,903,931
System Crash Using pandas for datetimeindex
<p>I'm trying to work my way through this RealPython tutorial on the Python visualization package called bokeh <a href="https://realpython.com/lessons/using-columndatasource-object/#transcript" rel="nofollow noreferrer">https://realpython.com/lessons/using-columndatasource-object/#transcript</a> . This video version is...
<p>Does this give the desired result? (For <code>player_stats</code>)</p> <pre><code>player_stats = pd.read_csv('data/2017-18_playerBoxScore.csv') player_stats['gmDate'] = pd.to_datetime(player_stats['gmDate']) player_stats.set_index('gmDate', inplace=True) </code></pre>
python|pandas|bokeh|datetimeindex
0
354,640
71,968,541
Kronecker product over the rows of a pandas dataframe
<p>So I have these two dataframes and I would like to get a new dataframe which consists of the kronecker product of the rows of the two dataframes. What is the correct way to this?</p> <p>As an example: DataFrame1</p> <pre><code> c1 c2 0 10 100 1 11 110 2 12 120 </code></pre> <p>and DataFrame2</p> <pre><code...
<p>Create <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.from_product.html" rel="nofollow noreferrer"><code>MultiIndex.from_product</code></a>, convert both columns to <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/referen...
pandas|dataframe|kronecker-product
1
354,641
72,091,852
Pandas datetime filter
<p>I want to get subset of my dataframe if date is before 2022-04-22. The original df is like below</p> <p>df:</p> <pre><code> date hour value 0 2022-04-21 0 10 1 2022-04-21 1 12 2 2022-04-21 2 14 3 2022-04-23 0 10 4 2022-04-23 1 12 5 2022-04-23 2 ...
<p>You most likely still have some string dates in one of your rows thus the first element might be ok but a complete comparison of all values using &quot;&lt;&quot; will fail.</p> <p>Either you use timegeb's answer in the comments.</p> <pre><code>df['date'] = pd.to_datetime(df['date']) </code></pre> <p>or you convert ...
python|pandas|dataframe|datetime
1
354,642
72,119,410
Splitting a large pandas datafile based on the data in one colimn
<p>I have a large-ish csv file that I want to split in to separate data files based on the data in one of the columns so that all related data can be analyzed.</p> <pre><code>ie. [name, color, number, state; bob, green, 21, TX; joe, red, 33, TX; sue, blue, 22, NY; ....] </code></pre> <p>I'd like to have it...
<p>You could try something like:</p> <pre><code>import pandas as pd for state, df in pd.read_csv(&quot;file.csv&quot;).groupby(&quot;state&quot;): df.to_csv(f&quot;file_{state}.csv&quot;, index=False) </code></pre> <p>Here <code>file.csv</code> is your base file. If it looks like</p> <pre><code>name,color,number,s...
python|pandas|dataframe
1
354,643
72,107,231
extract the value of a column based on corresponding two other columns in pandas
<p>I tried</p> <pre><code>print(df.loc[df['A'] == 'A value', 'B'].item()) </code></pre> <p>Which returns the value of B corresponding to A value.</p> <p>But what if I wanted to do something like this:</p> <pre><code>print(df.loc[df['A'] == 'B' &amp; df['C'] == 'C Value', 'Grade'].item()) </code></pre> <p>I want the ret...
<p>Suppose I have dataframe which looks like this,</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;"></th> <th style="text-align: center;">A</th> <th style="text-align: center;">B</th> <th style="text-align: center;">C</th> <th style="text-align: center;">D</th> </...
python|pandas|dataframe
1
354,644
71,859,576
Why does numba work on numpy string vectors but not on numpy strings?
<p>Consider the simplest possible function</p> <pre><code>@numba.jit def foo(s1): return s1 </code></pre> <p>Now constructing an array of <code>np.bytes_</code> objects</p> <pre><code>&gt; a = np.array(['abc']*5, dtype='S5') &gt; a array([b'abc', b'abc', b'abc', b'abc', b'abc'], dtype='|S5') </code></pre> <p>Why do...
<p>Neither <code>bytes</code> nor <code>np.bytes_</code> types are listed in <a href="https://numba.pydata.org/numba-doc/latest/reference/numpysupported.html#scalar-types" rel="nofollow noreferrer">the set of types supported by <code>numba</code></a> as of the latest release. The closest things it supports would be:</p...
python|numpy|numba
2
354,645
72,104,599
How to delete empty spaces from pandas DataFrame rows until first populated field?
<p>Lets say I imported a really messy data from a PFD and I´m cleaning it. I have something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Date</th> <th>other1</th> <th>other2</th> <th>other3</th> </tr> </thead> <tbody> <tr> <td>Name1</td> <td>''</td>...
<pre><code>data = df.values.flatten() pd.DataFrame(data[data != &quot;&quot;].reshape(-1, 3), columns = ['Name','Type', 'Date']) </code></pre> <p>or:</p> <pre><code>pd.DataFrame(df.values[df.values != &quot;&quot;].reshape(-1, 3), columns = ['Name','Type', 'Date']) </code></pre> <p>output:</p> <pre><code> Name Ty...
python|pandas|dataframe|rows|data-cleaning
1
354,646
71,837,176
How to get output class from Transformers model?
<p>I am new to Transformers and learning it from the Huggingface site. I was testing &quot;nlpaueb/legal-bert-base-uncased&quot; model and here is my code that I tried:</p> <pre class="lang-py prettyprint-override"><code>from transformers import AutoModel, AutoTokenizer model_name = &quot;nlpaueb/legal-bert-base-uncase...
<p>Use <code>TFAutoModel</code> instead of default (Pytorch) <code>AutoModel</code></p>
python|machine-learning|deep-learning|huggingface-transformers|bert-language-model
-1
354,647
71,813,347
How To Return Incorrectly Predicted Images
<p>I am having trouble figuring out how to create a list containing the first 10 image IDs that were incorrectly predicted.</p> <pre class="lang-py prettyprint-override"><code>import os import torch import torchvision from torch.utils.data import random_split from torchvision.datasets import ImageFolder from torchvisio...
<pre><code>def invalid_predictions(n=10, images, labels): invalid_ids = [] image_count = 0 invalid_count = 0 while invalid_count &lt; n: prediction = predict_image(images[image_count], model) if prediction != labels[image_count ]: invalid_ids.append(image_count ) ...
python|tensorflow|image-processing|deep-learning|pytorch
1
354,648
72,062,829
How to partition/slice rows horizontally in a data frame by contiguous occurrence of same value in column(s) to generate a statistical info in python?
<p>Please find attached snap and provide me how to reach to a solution of desired output mentioned in image description?</p> <p><a href="https://i.stack.imgur.com/6FNjJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6FNjJ.jpg" alt="enter image description here" /></a></p> <p>Code to generate input d...
<p>You can try something like this:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'timestamp':pd.date_range('2022-04-30 00:00:00', periods=19, freq='S'), 'fault_code':['A']*4+['B']*4+['A']*2+['C']*5+['B']*2+['A']*2}) df['group'] = (df['fault_code'] != df['fault_code'].shif...
python|pandas|dataframe
1
354,649
72,072,539
How to create columns in Pandas using a list
<p>I am trying to create a table in Pandas and I want my columns to be titled by the numbers between 0 and 56, but typing them by myself is very inefficient.</p> <p>Here is my code:</p> <pre><code> import pandas as pd x = [i for i in range(57)] df = pd.DataFrame(data=x,columns=[&quot;0&quot;, &quot;1&quot;, &qu...
<p>You need <code>x</code> to be 2D and <code>y</code> 1D (notice the square brackets):</p> <pre><code>import pandas as pd x = [i for i in range(57)] y = [i for i in range(57)] df = pd.DataFrame(data=[x], columns=y) </code></pre> <p>Output:</p> <pre><code> 0 1 2 3 4 5 6 7 8 9 ... 47 48 49 50...
python|python-3.x|pandas
1
354,650
72,138,049
Transform String data into numbers (where string should be always the same number), with the ability to transform them back
<p>I would like to build a Machine Learning solution, predicting upcoming sales per product.</p> <p>The dataset is containing thousand products (which are represented as a string. E.g., ‘Product_1_12345’).</p> <p>Since the product information is essential for the modelling (would like to forecast, on product level), I ...
<p>To convert you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.factorize.html" rel="nofollow noreferrer"><code>pandas.factorize</code></a>:</p> <p>This function output both the factors as numpy array <strong>and the unique IDs in order of the factors</strong>.</p> <p>You can save both and use th...
python|pandas
1
354,651
71,825,391
How to use nsmallest with conditional
<p>I want to use nsmallest between a range in my data frame. I am trying something like this but it doesn't work at all.</p> <pre><code>import pandas as pd df = pd.DataFrame({'day': ['1','1','2','3','3','3'],'price': ['5','4','3','2','6','8'],'income': [20,30,40,20,40,50]}) df.loc[(df['day']&gt;1) &amp; (df['day']&lt;=...
<p>I suspect that your sample actually should be</p> <pre><code>df = pd.DataFrame( {'day': [1, 1, 2, 3, 3 , 3], 'price': [5, 4, 3, 2, 6, 8], 'income': [20, 30, 40, 20, 40, 50]} ) </code></pre> <p>i.e. all integers, and not digit strings? (<code>.nsmallest()</code> doesn't work on strings.) If so, you could do</p> <...
python|pandas|dataframe
1
354,652
71,980,192
How to remove brackets from multi-value keys when converting to dataframes or extend values of a key without extraneous characters
<pre><code>df = pd.DataFrame.from_dict(dict_name, orient='index') df.fillna('NaN', inplace=True) df.to_csv('taxonomy_3.csv', index=True, header=True) </code></pre> <p>The above code handles a nested dictionary to dataframe conversion perfectly fine but if you have a nested dictionary created with the <code>.append()</c...
<p>One option is to <code>stack</code> the columns, <code>join</code> the strings, then <code>unstack</code>:</p> <pre><code>out = pd.DataFrame(my_data).stack().map(', '.join).unstack() </code></pre> <p>But it's probably more efficient to modify the input dictionary in vanilla Python first and then construct the DataFr...
python|pandas
1
354,653
71,791,533
Return entire row and append to value in a dataframe
<p>I am trying to write a function that searches a data frame row by row for a values in a column then appends entire row to the right side of the value if that value is found in any row.</p> <pre><code>Dataframe1 Col1 Col2 Col3 Lookup 400 60 80 90 50 90 68 80 </code></pre> <p>What I want is a following...
<p>You can try this out;</p> <pre><code>df1 = df.iloc[:,0:-1] new = pd.DataFrame() for val in df['Lookup']: s = df1[df1.eq(val).any(1)] new = new.append(s,ignore_index = True) new.insert(0,'Lookup',df['Lookup']) print(new) # Lookup Col1 Col2 Col3 # 0 90 50 90 68 # 1 80 400 60 8...
python|pandas|dataframe|loops
2
354,654
72,126,635
build histograms of the distribution of all numerical variables
<p>I need to build histograms of the distribution of all numerical variables and i really dont catch how to properly do this</p> <pre><code>import pandas as pd ind = [5375, 11681, 5325, 679, 12625, 8090, 11518, 16341, 2607,1742] dats = { 'index' : [5376, 11682, 5326, 680, 12626, 8091, 11519, 16342, 2608,1743], 'date': ...
<p>First of all, not all of these columns are numerical. <code>'date'</code> clearly isn't. Since your &quot;necessary line&quot; only produces four plots, I assume only the weather variables are meant:</p> <pre><code>columns = ['temp', 'atemp', 'hum', 'windspeed'] fig, axs = plt.subplots(2, 2, figsize=(20, 10)) #neces...
python|pandas|matplotlib|seaborn
0
354,655
71,946,124
ModuleNotFoundError: No module named 'dbn' error
<pre><code>from sklearn.model_selection import train_test_split from dbn.tensorflow import SupervisedDBNClassification import numpy as np import pandas as pd from sklearn.metrics.classification import accuracy_score ModuleNotFoundError: No module named 'dbn </code></pre> <p><em>When I try sorting malware dataset ...
<p>One solution is to git clone the repo, enter the folder, install requirements and run your code inside the folder:</p> <pre><code>git clone https://github.com/albertbup/deep-belief-network.git cd deep-belief-network pip install -r requirements.txt python3 543026528.py </code></pre> <p>dbn is a folder inside the deep...
tensorflow|data-mining
0
354,656
71,908,198
Removing a column in Pandas without a columns name
<p>This question would be very basic but I'm struck in dropping a column without a column name. I imported an excel into pandas and the data looked something like below</p> <pre><code> A B 0 24 -10 1 12 -3 2 17 5 3 63 45 </code></pre> <p>I tried to get rid of the first column (supposed to be in...
<p>this should work for the <code>nth</code> column in your dataframe <code>df.drop(columns=df.columns[n], inplace=True)</code>, if it's the first columns, so <code>n = 0</code>.</p>
python|pandas|dataframe
1
354,657
72,132,970
How to read dirty csv file in Python?
<p>I have a very dirty data that I need to read in Python. The csv file seperated with comma, but there are also some commas in the first column of my data that puts me in a tight position. Something like this:</p> <pre><code>import pandas as pd # initialize data of lists. data = {'reportname':['column1,column2, colu...
<p>You can preprocess your file before handing it off to pandas.</p> <pre><code>with open('yourfile.csv', 'r') as f: data = [line.strip().rsplit(',', number_of_columns - 1) for line in f] # if your csv has column names on the first row new_df = pd.DataFrame(columns=data[0], data=data[1:]) </code></pre> <p>This sol...
python|pandas
2
354,658
71,887,295
How to change year and month in a date which is in datetime format?
<p>I have a Python dataframe (8000 rows) with a datetime format column, which has dates like YYYY-MM-DD. I am looking to change it from being a single date to multiple months, and years, with same day.</p> <p>My Output:</p> <pre><code>0 data-1 2011-12-03 1 data-2 2011-12-03 2 data-3 2011-12-03 .. .. data-4 20...
<p>Is this your expected output? It's constructing the Cartesian product of dates ranging from <code>'2018-01-03'</code> to <code>'2022-12-03'</code> and <code>val</code> column. You have <code>date-1</code> to <code>date-m</code>, so I substituted <code>m</code> with 100. Then you'll get 6000 rows.</p> <pre><code>m = ...
python|pandas|dataframe
1
354,659
71,946,500
Retrieve click data from Python Holoviews / Datashader
<p>I'm coming from Python-Dash trying to achieve an interactive graphing functionality by creating a second graph using the click data of the first one. Similar to what can be found <a href="https://dash.plotly.com/interactive-graphing" rel="nofollow noreferrer">here</a></p> <p>I'm stuck in retrieving and correctly usi...
<p>Basically, this requires to create a function to filter the data based on the click data create a streams object in holoviews to capture the events data and then put them together in the table. Notice there could be multiple ways of approximating the x-y coordinates to actual points in the data. In this case, for in...
python|pandas|plotly-dash|holoviews|datashader
0
354,660
72,062,823
How to remove YYYY-MM-DD from datetime, leave HH:MM, and convert it to EST
<p>I'm building a stock researching program that utilizes an API and I can't seem to figure out how to remove the years, months, and day from the datetime. The problem with this is that date is a user input so I tried using f strings but it did not work. The script itself works fine its just that I have plans on automa...
<p>You could surely use momentjs library it provides us with a wide variety of functions that we can use to fulfill our needs in that particular use case. Here is its website: <a href="https://momentjs.com/" rel="nofollow noreferrer">https://momentjs.com/</a></p>
python|pandas|datetime
0
354,661
71,819,107
Extract the values of a dataframe that correspond to a single element of another df
<p>I have 2 pandas dfs (df1 &amp; df2) as seen here:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">df1</th> <th style="text-align: center;">col1</th> <th style="text-align: center;">col2</th> <th style="text-align: center;">col3</th> <th style="text-align: cent...
<p>Assuming that your first columns <code>df1</code> and <code>df2</code> are the index of their respective <code>df</code>, we can extract the values for each unique animal in <code>df1</code> by using the first <code>df</code> as a mask to extract all wanted values from the second one (the result is a new <code>df</c...
python|pandas|dataframe|information-retrieval
3
354,662
72,051,642
How to rename columns of list of dataframes in pandas?
<p>I have list of dataframes where each has different columns, and I want to assign unique column names to all and combine it but it is not working. Is there any quick way to do this in pandas?</p> <p><strong>my attempt</strong></p> <pre><code>!pip install wget import wget import pandas as pd url = 'https://github.co...
<p>The error was coming from the data. Almost all DataFrames sheets had 3 columns but only &quot;NC&quot; had a redundant column that starts as &quot;Unnamed&quot;, which is almost all NaN except for one row which has <code>&quot;`&quot;</code> as value. If we remove that column from that sheet, the rest of the code wo...
python|python-3.x|excel|pandas|dataframe
3
354,663
72,134,236
How can I use scipy interp1d with N-D array for x without for loop
<p>How can I use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html" rel="nofollow noreferrer"><code>scipy.interpolate.interp1d</code></a> when my <code>x</code> array is an N-D array, instead of a 1-D array, without using a loop?</p> <p>The function <code>f</code> from interp...
<p>interp1d and other interpolators from scipy.interpolate only support 1D x arrays. So you'll need to loop over the dimensions of x manually.</p>
function|numpy|lambda|scipy|list-comprehension
0
354,664
16,739,542
pandas series to multi-column html
<p>I have a Pandas series (slice of larger DF corresponding to a single record) that I would like to display as html. While i can convert the Series to a DataFrame and use the <code>.to_html()</code> function this will result in a two-column html output. To save space/give a better aspect ratio I would like to return a...
<p>This is simpler. The ordering is slightly different (read across rows, not down columns), but I'm not sure if that will matter to you.</p> <pre><code>In [17]: DataFrame(np.array([s.index.values, s.values]).T.reshape(3, 4)) Out[17]: 0 1 2 3 0 a 12 b 34 1 c 56 d 78 2 e 54 f 77 </code></pre> <p>A...
pandas
1
354,665
17,020,763
pandas 0.10.1 to 0.11.0 .ix method
<p>I have a huge dataframe with unique index. This was working code in pandas 0.10.1 but seems to break in pandas 0.11.0.</p> <p>Simplistically I have a DataFrame (df) with 2 columns: "Classification' and 'A', Both populated with data. The df is uniquely indexed. I want to overwrite the value in A if the 'Classifi...
<p>This looks like a <a href="https://github.com/pydata/pandas/issues/3836" rel="nofollow">bug</a> in 0.11, on the bright side it appears to be fixed in 0.11.1 (out very soon).</p> <pre><code>0.11.1.dev-bbcafd8 Original DataFrame: Classification Random X 0 SA EQUITY CFD 1 correct 1 bbb ...
python|pandas
1
354,666
16,808,682
Is there in pandas operation complementary (opposite) to groupby?
<p>I have a table (data frame) with many columns. Now I would like to average values in one of the columns. It means that I need to group by over all columns except the one over which I need to average. Of course I can write:</p> <pre><code>df.groupby(['col1', 'col2', 'col3', 'col4', 'col5'])['vals'].mean() </code></p...
<p>You are searching for the complementary columns to a list you have on hands. You can play with <code>df.columns</code>. It represents an <code>Index</code> object that allows some interesting manipulations.</p> <p><code>df.columns.drop(['col6'])</code> returns an <code>Index</code> with the list of columns passed a...
python|group-by|dataframe|pandas
3
354,667
16,683,701
In PANDAS, how to get the index of a known value?
<p>If we have a known value in a column, how can we get its index-value? For example: </p> <pre><code>In [148]: a = pd.DataFrame(np.arange(10).reshape(5,2),columns=['c1','c2']) In [149]: a Out[149]: c1 c2 0 0 1 1 2 3 2 4 5 ........ </code></pre> <p>As we know, we can get a value by the index corre...
<p>There might be more than one index map to your value, it make more sense to return a list:</p> <pre><code>In [48]: a Out[48]: c1 c2 0 0 1 1 2 3 2 4 5 3 6 7 4 8 9 In [49]: a.c1[a.c1 == 8].index.tolist() Out[49]: [4] </code></pre>
indexing|pandas
45
354,668
16,824,607
Pandas: Appending a row to a dataframe and specify its index label
<p>Is there any way to specify the index that I want for a new row, when appending the row to a dataframe?</p> <p>The original documentation provides <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html">the following example</a>:</p> <pre><code>In [1301]: df = DataFrame(np.random.randn(8, 4), columns=['...
<p>The <code>name</code> of the Series becomes the <code>index</code> of the row in the DataFrame:</p> <pre><code>In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D']) In [100]: s = df.xs(3) In [101]: s.name = 10 In [102]: df.append(s) Out[102]: A B C D 0 ...
python|pandas
71
354,669
19,202,654
NaN interpolation in 2D array. Sparsely populated
<p>I have a 2D array with some NaN values. I would like to inpaint (interpolate) those values using the locations where I have data. The array looks like the one below.</p> <p>If possible I would like to do the interpolation so that, as I move away from non-NaN values, I get increasingly closer to the value 0. </p> <...
<p>There are dozens of possible approaches based on what kind of interpolation technique you would like to use. In fact, as your data is rather surrounded by NaNs I would rather think about it as a function smoothing then interpolating. If you want to get closer to zero the more away you are from the not NaNs in terms ...
python|arrays|numpy|scikit-learn
3
354,670
19,086,229
How can I change my python code avoid computed the maxnumber index
<p>Now I have implemented python code.</p> <pre><code>def logistic(z): return 1.0 / (1.0 + np.exp(-z)) def gradient_testing(X,Y,w): K = len(w) N = len(X) s = np.zeros(K) for i in range(N): s += Y[i] * X[i] * logistic(-Y[i] * np.dot(X[i], w)) s = -1 *s/N return s </code></pre> <p><code...
<p>Brief explanation, <code>k_range!=max_idx</code> makes a array having: <code>1</code> where index is not equal to the index of previous maximum and <code>0</code> where index is equal to the index of previous maximum. During the first iteration, <code>max_idx</code> is -1, so <code>k_range!=max_idx</code> gives a ar...
python|numpy
0
354,671
18,969,143
Reverse certain rows in N by 2 array
<p>I have an N by 2 array like this one:</p> <pre><code>[[9 1] [0 5] [6 3] [2 4] [3 5] [4 1] [2 7] [6 8] [7 9] [8 0]] </code></pre> <p>After I make a search in this matrix, I return some indices where the rows must be permuted.</p> <p>In my case, I had <code>w=[1 0 9 8 7]</code>.</p> <p>I use this code to ...
<p>This works by applying the roll to a copy of <code>a</code> only at indices <code>w</code> and then setting those in the original <code>a</code> with the rolled values:</p> <pre class="lang-py prettyprint-override"><code>a[w] = np.roll(a[w], 1, axis=1) </code></pre> <p>Someone had an answer (I think @seberg, but...
python|numpy
2
354,672
22,257,527
How do I get a summary count of missing/NaN data by column in 'pandas'?
<p>In <em>R</em> I can quickly see a count of missing data using the <code>summary</code> command, but the equivalent <code>pandas</code> DataFrame method, <code>describe</code> does not report these values.</p> <p>I gather I can do something like</p> <pre><code>len(mydata.index) - mydata.count() </code></pre> <p>to...
<p>Both <code>describe</code> and <code>info</code> report the count of non-missing values.</p> <pre><code>In [1]: df = DataFrame(np.random.randn(10,2)) In [2]: df.iloc[3:6,0] = np.nan In [3]: df Out[3]: 0 1 0 -0.560342 1.862640 1 -1.237742 0.596384 2 0.603539 -1.561594 3 NaN 3.018954 4 ...
pandas|reporting|nan|missing-data
55
354,673
22,304,820
How to check if all elements of a numpy.array are of the same data type?
<p>I have few numpy arrays, which can be formatted as</p> <pre><code>[1.525, 2.565, 6.367, ...] # elements are float numbers </code></pre> <p>or</p> <pre><code>['', '', '', ...] # elements are empty strings </code></pre> <p>I'd like to find out if all the elements in an array are of the same data type.</p> <p>Fo...
<p>If you're looking for a particular data-type as provided in your example, e.g. all items are floats, then a map and reduce will do the trick:</p> <pre><code>&gt;&gt;&gt; x = [1.525, 2.565, 6.367] &gt;&gt;&gt; all(map(lambda i: isinstance(i, float), x)) True &gt;&gt;&gt; x = [1.525, 2.565, '6.367'] &gt;&gt;&g...
python|numpy
2
354,674
22,184,995
Reading data from data acquisition unit (measurement computing)
<p>I have a data acquisition unit (USB-2408 from Measurement Computing) and am trying to write Python code to display that data in as close to real-time as I can, but obviously that's limited, so I'll take what I can get. I ran across a man that has <a href="http://wiki.scipy.org/Cookbook/Data_Acquisition_with_PyUL" r...
<p>I haven't reached the bottom of this problem yet, but it looks like a problem with <code>numpy</code> because Python cannot find a <code>dtype</code> attribute in <code>np</code>, which is how <code>numpy</code> is imported into the file <code>oldnumeric/typeconv.py</code> within the <code>numpy</code> distribution....
python|python-2.7|numpy|data-acquisition
2
354,675
21,959,625
Undo a Pandas Data Frame
<p>I'm trying to change something from a data frame into a string. peak1 is my data frame that is 1 row and 5 columns. I just want one part of it under the column 'url' and make it into a string.</p> <pre><code>buzz1 = peak1[['url']] </code></pre> <p>However, buzz1 returns:</p> <pre><code> ...
<p>Your command returns a dataframe consisting of a single column, this is why you see the index column.</p> <p>So what you want to do is to return just the first value from the series:</p> <pre><code>peak1['url'].iloc[0] </code></pre> <p>Will give you what you want.</p>
python|pandas|bigdata
1
354,676
22,261,126
Array reshaped according to keys
<p>I don't know the exact technical terms for what I wish to do, so I'll try and demonstrate with an example:</p> <p>I have two vectors the same length, <em>a</em> and <em>b</em>, as below:</p> <pre><code>In [41]:a Out[41]: array([ 0.61689215, 0.31368813, 0.47680184, ..., 0.84857976, 0.97026244, 0.89725481]) ...
<p><code>itertools.groupby</code> can be used to group values (after sorting). Use of <code>numpy</code> <code>arrays</code> is optional.</p> <pre><code>import numpy as np import itertools N=50 # a = np.random.rand(50)*100 a = np.random.randint(0,100,N) # int to make printing more compact b = np.random.randint(35,45,...
python|arrays|numpy|reshape
1
354,677
18,002,070
Interpolating a large dataframe onto a sparse, irregular index
<p>I've got one dataframe containing several years of data sampled at 30 min intervals (7 parameters from a continuous water quality sensor), and I've got another dataframe containing data at a few hundred random points in time, with one minute precision. I'd like to find the interpolated values of the 7 parameters at...
<p>Here's a way to do what I think you want</p> <p>Starting frame df1 and df2</p> <pre><code>In [100]: df1 Out[100]: Temp SpCond Sal DO_pct DO_mgl Depth pH Turb time 2002-07-16 14:00:00 26.0 45.31 29.3 71.6 ...
python|pandas|interpolation
1
354,678
18,193,105
Pandas: use the "and" of two series in `where`
<p>I have written a small function to get the log returns of a series:</p> <pre><code>def get_log_returns(series): logs = numpy.log(series.astype('float64') / series.astype('float64').shift(1)) return logs </code></pre> <p>Now I would like to make sure I only include logs that are "reasonable". I know I can ...
<p>You should use the <code>&amp;</code> operator.</p> <pre><code>logs[(logs &lt; numpy.inf) &amp; (logs &gt; 0)] </code></pre> <p><code>and</code> and <code>or</code> are not supported operations with boolean Series so you have to use the <code>&amp;</code> and <code>|</code> operators.</p>
python|pandas
3
354,679
18,195,231
How to read and plot time series data files as candlestick chart?
<p>Here is the time series data. I'd like to read data file and plot it as candle chart. Actually, I googled to find pyghon logic I want all day long, But I couldn't. Any comments will be appreciated.</p> <p>Thank you in advance.</p> <pre> 2011-11-01 9:00:00, 248.50, 248.95, 248.20, 248.70 2011-11-01 9:01:00, 248.70,...
<p>To read in this data set from the clipboard do</p> <pre><code>from pandas import read_clipboard from matplotlib.dates import date2num names = ['date', 'open', 'close', 'high', 'low'] df = read_clipboard(sep=',', names=names, parse_dates=['date']) df['d'] = df.date.map(date2num) </code></pre> <p>The top-level <code...
python|matplotlib|pandas|time-series
2
354,680
17,945,295
Numpy to weak to calculate a precise mean value
<p>This question is very similar to <a href="https://stackoverflow.com/questions/17463128/wrong-numpy-mean-value">this post</a> - but not exactly</p> <p>I have some data in a .csv file. The data has precision to the 4th digit (#.####).</p> <p>Calculating the mean in Excel or SAS gives a result with precision to 5th d...
<p>To get exact decimal numbers, you need to use decimal arithmetic instead of binary. Python provides the <a href="http://docs.python.org/2/library/decimal.html" rel="nofollow">decimal module</a> for this.</p> <p>If you want to continue to use numpy for the calculations and simply round the result, you can still do t...
python|numpy|precision
3
354,681
17,730,252
Reindexing and filling NaN values in Pandas
<p>Consider this dataset: </p> <pre><code>data_dict = {'ind' : [1, 2, 3, 4], 'location' : [301, 301, 302, 303], 'ind_var' : [4, 8, 10, 15], 'loc_var' : [1, 1, 7, 3]} df = pd.DataFrame(data_dict) df_indexed = df.set_index(['ind', 'location']) df_indexed </code></pre> <p>which looks like</p> <pre><code> ind...
<p>This can be done by <code>stack/unstack</code> and <code>groupby</code> very easily:</p> <pre><code># unstack to wide, fillna as 0s df_wide = df_indexed.unstack().fillna(0) # stack back to long df_long = df_wide.stack() # change 0s to max using groupby. df_long['ind_var'] = df_long['ind_var'].groupby(level = 0).tra...
python|pandas|reshape
2
354,682
4,808,221
Is there a "bounding box" function (slice with non-zero values) for a ndarray in NumPy?
<p>I am dealing with arrays created via numpy.array(), and I need to draw points on a canvas simulating an image. Since there is a lot of zero values around the central part of the array which contains the meaningful data, I would like to "trim" the array, erasing columns that only contain zeros and rows that only cont...
<p>This should do it:</p> <pre><code>from numpy import array, argwhere A = array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) B = arg...
python|arrays|numpy|trim|bounding
24
354,683
4,535,374
initialize a numpy array
<p>Is there way to initialize a numpy array of a shape and add to it? I will explain what I need with a list example. If I want to create a list of objects generated in a loop, I can do:</p> <pre><code>a = [] for i in range(5): a.append(i) </code></pre> <p>I want to do something similar with a numpy array. I know...
<blockquote> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html"><code>numpy.zeros</code></a></p> <p>Return a new array of given shape and type, filled with zeros.</p> </blockquote> <p>or</p> <blockquote> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.on...
python|arrays|numpy
201
354,684
8,881,148
What is the fastest way to convert from a unixtime to a numpy.datetime64?
<p>I suppose that the key here is to have the less number of intermediate conversions but I'm not able to find a simple way in the new Numpy 2.0 dev</p>
<p>Actually, <code>numpy.datetime64</code> objects are basically unix times internally (with 6 extra significant digits to account for millisecond precision). You just need to multiply by <code>1e6</code>.</p> <p>As an example:</p> <pre><code>import numpy as np # Generate a few unix time stamps near today... x = np...
python|numpy|unix-timestamp
3
354,685
8,765,310
scipy.linalg.eig return complex eigenvalues for covariance matrix?
<p>The eigenvalues of a covariance matrix should be real and non-negative because covariance matrices are symmetric and semi positive definite.</p> <p>However, take a look at the following experiment with scipy:</p> <pre><code>&gt;&gt;&gt; a=np.random.random(5) &gt;&gt;&gt; b=np.random.random(5) &gt;&gt;&gt; ab = np....
<p>You have raised two issues:</p> <ol> <li>The eigenvalues returned by <code>scipy.linalg.eig</code> are not real.</li> <li>Some of the eigenvalues are negative.</li> </ol> <p>Both of these issues are the result of errors introduced by truncation and rounding errors, which always happen with iterative algorithms usi...
python|matlab|numpy|scipy|linear-algebra
41
354,686
8,546,309
numpy: point sum
<pre><code>&gt;&gt;&gt; from pandac.PandaModules import Vec3 &gt;&gt;&gt; import numpy &gt;&gt;&gt; l = [] &gt;&gt;&gt; l.append( Vec3(1,1,1) ) &gt;&gt;&gt; l.append( Vec3(1,1,1) ) &gt;&gt;&gt; l.append( Vec3(1,1,1) ) &gt;&gt;&gt; Vec3(1,1,1)+Vec3(1,1,1) Vec3(2, 2, 2) &gt;&gt;&gt; sum(l) Traceback (most recent call las...
<p>Try this:</p> <pre><code>sum(l, start=Vec3(0,0,0)) </code></pre> <p>Or, with numpy, this:</p> <pre><code>numpy.sum(l, axis=0) </code></pre> <p>The speed depends in the implementation of the vector-addition. You should use <a href="http://docs.python.org/library/timeit.html" rel="nofollow"><code>timeit</code></a>...
python|numpy|panda3d
2
354,687
9,008,263
Is there a python method to re-order a list based on the provided new indices?
<p>Say I have a working list: ['a','b','c'] and an index list [2,1,0] which will change the working list to: ['c','b','a']</p> <p>Is there any python method to do this easily (the working list may also be a numpy array, and so a more adaptable method is greatly preferred)? Thanks!</p>
<ul> <li><p>ordinary sequence:</p> <pre><code>L = [L[i] for i in ndx] </code></pre></li> <li><p><code>numpy.array</code>:</p> <pre><code>L = L[ndx] </code></pre></li> </ul> <p>Example:</p> <pre><code>&gt;&gt;&gt; L = "abc" &gt;&gt;&gt; [L[i] for i in [2,1,0]] ['c', 'b', 'a'] </code></pre>
python|numpy
5
354,688
55,348,654
No matching distribution found for tf-nightly when installing tensorflowjs
<p>I am trying to install tensorflowjs on my virtual environment, but am getting the following error:</p> <pre><code>Could not find a version that satisfies the requirement tf-nightly-2.0-preview&gt;=2.0.0.dev20190304 (from tensorflowjs) (from versions: ) No matching distribution found for tf-nightly-2.0-preview&gt;=2...
<p><a href="https://pypi.org/project/tf-nightly-2.0-preview/2.0.0.dev20190326/#files" rel="nofollow noreferrer">tf-nightly-2.0-preview</a> releases binaries for MacOS only for Python 2.7 and 3.6.</p>
pip|tensorflowjs-converter
4
354,689
55,402,406
Convert Dataframe to JSON
<p>I have the following DataFrame:</p> <pre class="lang-py prettyprint-override"><code> price item_name timestamp item1 2018-10-12 12.2 2018-10-13 14.3 2018-10-14 17.1 item2 2018-10-12 ...
<p>Based in your dataframe (columns and index)</p> <pre><code>import pandas as pd import json df = pd.DataFrame( data = [ ('item1', '2018-10-12', 12.2), ('item1', '2018-10-13', 14.3), ('item1', '2018-10-14', 17.1), ('item2', '2018-10-12', 11.4), ('item2', '2018-10-13', 15.6), ('item2', '2018-1...
python|pandas
1
354,690
55,555,010
Group by, aggregate, include separate column
<p>Here's my data:</p> <pre><code>foo = pd.DataFrame({ 'accnt' : [101, 102, 103, 104, 105, 101, 102, 103, 104, 105], 'gender' : [0, 1 , 0, 1, 0, 0, 1 , 0, 1, 0], 'date' : pd.to_datetime(["2019-01-01 00:10:21", "2019-01-05 00:09:18", "2019-01-05 00:09:30", "2019-02-05 00:05:12", "2019-04-01 00:08:46", ...
<p>In R <code>summarise</code> will equal to <code>agg</code> , <code>mutate</code> equal to <code>transform</code> </p> <p>The reason why you have multiple index in columns : Since you pass the function call with <code>list</code> , which means you can do something like <code>{'date':['mean','sum']}</code></p> <pre>...
python|pandas|group-by|aggregate
2
354,691
55,547,897
Using the numpy.random.exponential to draw 10,000,000 samples of X to estimate the expected value of a payout
<p>Assume the dollar amount of damage involved in an automobile accident is an exponential random variable with a mean of 1000. Of this, the insurance company only pays the amount exceeding the deductible of 400. If X is a random variable representing the dollar amount of damage, then the insurance payout is max(X-400,...
<p>I think your doing too much.</p> <pre><code>import numpy as np a = np.random.exponential(1000., size=10000000) np.maximum(a-400, 0).mean() Out[13]: 670.3739442241515 </code></pre> <p>If you are doing the sampling I don't think you need to integrate. </p>
python|numpy|montecarlo|quad
2
354,692
55,427,479
python search and find specify numbers location in array 2d
<p>i have array np.array two dimensional array </p> <pre><code>[[8, 12, 5, 2], [12,15, 6,10], [15, 8, 12, 5], [12,15,8,6]] </code></pre> <p>i want to create another 2d array , (each number in array,how many repeated,locations)</p> <pre><code>(2,1,[1,4]), (5,2,[1,3],[3,4]) ,(6,2,[2,3],[4,4]) , (8,3,[1,1],[3,1],[4,3]...
<p>Here is one way using <code>np.unqiue</code> and <code>np.where</code>, notice the index in <code>numpy</code> <code>array</code> is start from 0 not 1 </p> <pre><code>x,y=np.unique(a.ravel(), return_counts=True) l=[] for v,c in zip(x,y): l.append((v,c,np.column_stack(np.where(a==v)).tolist())) l Out[344]: [...
python|python-3.x|python-2.7|numpy
1
354,693
55,557,014
tensorflow nested map_fn concat two tensors
<p>say I have two tensors:</p> <pre><code>a=Tensor("zeros_3:0", shape=(2, 4, 5), dtype=float32) b=Tensor("ones_3:0", shape=(2, 3, 5), dtype=float32) </code></pre> <p>how can I concat each element along axis 2 to get a new tensor shaped <code>(2,3,4,10)</code>, using nested map_fn or other tf functions?</p> <p>here i...
<p>You can use <code>tf.tile</code> and <code>tf.expand_dims</code> with <code>tf.concat</code>. An example:</p> <pre><code>import tensorflow as tf a = tf.random_normal(shape=(2,4,5),dtype=tf.float32) b = tf.random_normal(shape=(2,3,5),dtype=tf.float32) # your code concat_list = [] for i in range(a.get_shape()[1]): ...
tensorflow|nested
1
354,694
55,270,124
Geopy, checking cities, avoiding duplicates, pandas
<p>I want to get the lat of ~ 100 k entries in a pandas dataframe. Since I can query geopy only with a second delay, I want to make sure I do not query duplicates (most should be duplicates since there are not that many cities)</p> <pre><code>from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="xxx...
<p>Prepare the initial dataframe:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ 'some_meta': [1, 2, 3, 4], 'city': ['london', 'paris', 'London', 'moscow'], }) df['city_lower'] = df['city'].str.lower() df </code></pre> <pre><code>Out[1]: some_meta city city...
python|pandas|geopy
0
354,695
55,466,833
mapping missing values in one column of pandas dataframe using dictionary with reference to another column values
<p>I have a dataframe as</p> <pre><code>&gt; print(df) [Out:] activity-code activity ------------------------- 0 unknown 99 NaN 84 sports 72;99 NaN 57 recreational 57;99;11 NaN 11 NaN </code></pre> <p>and a dictionary with ac...
<p>Use <code>apply</code> and <code>str.split</code>, than in <code>apply</code>, use a list comprehension and join it by <code>';'</code>:</p> <pre><code>df['activity'] = df['activity-code'].str.split(';').apply(lambda x: ';'.join([act_dict[int(i)] for i in x])) </code></pre> <p>And now:</p> <pre><code>print(df) </...
python|python-3.x|pandas|dictionary
2
354,696
55,327,129
Function to transform 3d points to a new coordinate system with numpy
<p>I have <code>n</code> points in space: <code>points.shape == (n,3)</code></p> <p>I have a new coordinate system defined by a point <code>O = [ox, oy, oz]</code> and 3 orthogonal vectors of different lengths: <code>Ox = [oxx, oxy, oxz], Oy = [oyx, oyy, oyz], Oz = [ozx, ozy, ozz]</code>.</p> <p>How can I write a fun...
<p>You have 4 non-coplanar points in original system (where <code>lx</code> is length of the first vector and so on):</p> <pre><code>(0,0,0), (lx,0,0), (0,ly,0), (0,0,lz) </code></pre> <p>and their twins in new system</p> <pre><code> [ox, oy, oz] [oxx + ox, oxy + oy, oxz + oz] [oyx + ox, oyy + oy, oyz + oz] [ozx + o...
python|numpy|math|3d|geometry
2
354,697
55,243,341
Elapsed time in pandas time series
<p>I have a pandas time-series dataframe and I want to know the total elapsed time of the dataframe or points within the dataframe. How do I do this? </p> <p>The following is some example data from my dataframe:</p> <pre><code>elapsed_time Layer 1970-01-01 00:20:30 20.0 1970-01-01 00:20:31 20.0 1970-0...
<p>The easiest would be to reset the index in order to have access to the timestamp as a column for the group by:</p> <pre><code>res = df.reset_index().groupby('Layer')['elapsed_time'].agg(['min', 'max']) res['max'] - res['min'] </code></pre> <p>You can also use <code>first</code> and <code>last</code> if you know ...
python-3.x|pandas|time-series
2
354,698
55,390,298
Pandas Dataframe replace Nan from a row when a column value matches
<p>I have dataframe i.e.,</p> <pre><code>Input Dataframe class section sub marks school city 0 I A Eng 80 jghss salem 1 I A Mat 90 jghss salem 2 I A Eng 50 Nan salem 3 III A Eng 80 gphss Nan 4 III A ...
<p>Use forward and back filling missing values per groups with <code>lambda function</code> in columns specified in list with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="noreferrer"><code>DataFrame.groupby</code></a> - is necessary for each combination same val...
python|python-3.x|pandas|nan
8
354,699
55,499,193
Keras: TensorFlow 1.3 model fails under TensorFlow 1.4 or later (wrong predictions)
<p>I have a model trained on TensorFlow 1.3, Keras 2.0.6-tf using the <code>tensorflow.contrib</code> Python API. Works like a charm.</p> <p>But when I load the model in a TensorFlow 1.4 (or later) environment, predictions are constant, i.e., not correct. There is no error message whatsoever.</p> <p>All I do is:</p> ...
<p>Here's how I finally got the Keras/TF 1.3 model to work with Keras/TF > 1.3:</p> <h3>In TensorFlow 1.3 Environment</h3> <pre><code>import tensorflow as tf from tensorflow.contrib.keras.python.keras import backend from tensorflow.contrib.keras.python.keras.models import load_model name = 'my_model_name' model = lo...
python|tensorflow|keras|tf.keras
0