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
6,200
62,604,708
Adding Multiple Pandas Columns to Sparse CSR Matrix
<p>so my question is based on this <a href="https://stackoverflow.com/questions/41927781/adding-pandas-columns-to-a-sparse-matrix">question</a>.</p> <p>I have Twitter data where I extracted unigram features and number of orthographies features such as excalamation mark, question mark, uppercase, and lowercase. I want t...
<p>You have problems with list syntax and <code>sparse.coo_matrix</code> creation.</p> <pre><code>np.array(X_train['exclamation'])[:,None]) </code></pre> <p><code>Series</code> to array is 1d, with None, becomes (n,1)</p> <pre><code>np.array(list(X_train['exclamation'], X_train['question'], X_train['uppercase'], X_trai...
python|pandas|numpy|scipy|sparse-matrix
1
6,201
62,706,210
Create an array of matrices from 1D arrays in python
<p>Could you please help to create an array of matrices when elements are taken to be 1D arrays in python.</p> <p>For Ex: Here is what I am trying to do</p> <pre><code>import numpy as np ele_1 = np.linspace(0,1,num= 50) ele_2 = np.linspace(1,2,num= 50) ele_3 = np.linspace(2,3,num= 50) ele_4 = np.linspace(3,4,num= 50) ...
<pre><code>In [153]: ele_1 = np.linspace(0,1,num= 50) ...: ele_2 = np.linspace(1,2,num= 50) ...: ele_3 = np.linspace(2,3,num= 50) ...: ele_4 = np.linspace(3,4,num= 50) In [154]: Mat_array = np.array([[ele_1,ele_2],[ele_3,ele_4]]) # correction? ...
python|numpy
3
6,202
62,649,647
Under what situation will np.genfromtxt read in an array of voids
<p>Trying to read a .Data file using np.genfromtxt</p> <pre><code>a = np.genfromtxt(&quot;u.data&quot;, dtype = [int, int, int, int], delimiter = '\t') </code></pre> <p>The output is an array of numpy voids. However, if I do not specify the data type, then the output is a normal array. I wonder what went wrong. I shoul...
<p>Various ways of loading a simple csv</p> <pre><code>In [148]: txt = &quot;&quot;&quot;1,2,3 ...: 4,5,6&quot;&quot;&quot; </code></pre> <p>default float:</p> <pre><code>In [149]: np.genfromtxt(txt.splitlines(), delimiter=',') Out[149]: array([[1., 2., 3.], [...
numpy|numpy-ndarray
1
6,203
62,663,877
how to count observations based on timestamp condition
<p>I have a Pandas dataframe in the following format:</p> <pre><code>id name timestamp 001 movie1 2012-05-05 19:52:04 001 movie5 2012-05-05 13:42:52 001 movie3 2012-05-04 18:29:11 002 movie8 2012-05-05 13:18:31 002 movie7 2012-05-04 09:13:28 003 movie7 2012-05-05 19:23:45 003 movie1 2012-05-04...
<p>You can try this, sort by user id and date, group by the user id, and find diff in hours:</p> <pre><code>df['timestamp'] = pd.to_datetime(df['timestamp']) df.sort_values(by=['id', 'timestamp'], inplace=True) df['time_diff'] = df.groupby(by=['id'])['timestamp'].diff().astype('timedelta64[h]') df['&lt;2'] = df['time_d...
python|pandas|dataframe|timestamp|pandas-groupby
2
6,204
62,570,557
Extract keywords from a dataframe column to another column
<p>I have a dataframe in the following format : <a href="https://www.kaggle.com/hsankesara/flickr-image-dataset" rel="nofollow noreferrer">link to the csv file</a></p> <pre><code> image_name caption_number caption 0 1000092795.jpg 0 Two young guys with shaggy hair look at their... 1 10000927...
<p>The reason was the caption column had nan values so it is required to drop the nan values before applying the function.</p> <pre><code>#replaces all occurring digits in the strings with nothing df['caption'] = df['caption'].str.replace('\d+', '') #drop all the nan values df=df.dropna() #if you need the whole row to...
python|pandas|keyword
2
6,205
73,651,847
How can I create a vector of longitud len(x) numbered one by one from 0 to len(x) in python
<p>I have a len(x), and need create a vector of that lenght (lenx), starting with a 0, so the last one should be len(x)-1.</p> <p>how can I do this in python?</p>
<p>I am not sure of what you mean by &quot;vector&quot;, but I guess it is either of:</p> <p><strong>A Python list:</strong></p> <pre><code>vector = [i for i in range(len(x))] </code></pre> <p>or</p> <pre><code>vector = list(range(len(x))) </code></pre> <p><strong>A numpy array:</strong></p> <pre><code>np.array(range(l...
python|numpy
0
6,206
73,811,862
Getting coordinates of the edges of the box inside the image in python
<p>I am trying to get the coordinates <code>[x, y]</code> of the edges of the box in the image attached.</p> <p>This is the image I am using to get the edge coordinates:</p> <p><img src="https://i.stack.imgur.com/ekSXa.jpg" alt="image" /></p> <p>I am finding difficulty in getting. Anybody, please help me in getting the...
<p>Try referencing <code>img</code> instead of <code>image</code>. You are initially trying to index the <code>Image</code> object rather than the actual image data which is in <code>img</code>:</p> <pre class="lang-py prettyprint-override"><code>cv2.imwrite(&quot;image.jpg&quot;, img[y1:y2-1,x1:x2-1]) </code></pre>
python|numpy
0
6,207
73,672,752
What happens with workers when they are done with their task?
<p>I have a task, which I aim to parallelize with the help of the <code>joblib</code>-library. The function is fairly slow when ran sequentially, therefore I tried using parallelization paradigms to speed up the process.</p> <pre><code>with Parallel(n_jobs = -1,verbose = 100) as parallel: test = parallel(delayed(create...
<p>I am not that familiar with <code>joblib</code> but I quickly perused the documentation. It appears that you are using the default &quot;multiprocessing&quot; backend that is based on Pythons <code>multiprocessing.Pool</code> implementation, of which I do know a bit. This class creates a pool of processes as you wou...
python|pandas|multithreading|multiprocessing|joblib
1
6,208
71,192,005
Value replacement based on multiple conditions
<p>My pandas dataframe looks like <a href="https://i.stack.imgur.com/Eq8zX.png" rel="nofollow noreferrer">this </a>. For each row I want to replace values in Q2 to &quot;positive&quot; if the term &quot;xxpos&quot; occurs within the &quot;SNIPPET&quot; column and if the value in Q2 == 1. Also I want to replace values i...
<p>You can try with the following code.</p> <pre class="lang-py prettyprint-override"><code>df.loc[(df['Q2']==1) &amp; (df['SNIPPET'].str.contains('xxpos')), 'Q2'] = 'Positive' df.loc[(df['Q2']==1) &amp; (df['SNIPPET'].str.contains('xxneg')), 'Q2'] = 'Negative' </code></pre>
python|pandas|string
0
6,209
71,342,640
Is there a way to delete an entire row and shift the cells up in xlwings?
<p>If I wanted to delete an entire row and shift the cells up is there a way to do that? Below is a snippet of my loop which is iterating through the column and clearing the contents of the cell if it doesn't match my parameters. Is there a way rather than clearing just the cell in column A I could delete the whole row...
<p>Use <a href="https://docs.xlwings.org/en/stable/api.html#xlwings.Range.delete" rel="nofollow noreferrer">delete()</a> and specify the rows number(s) you want to delete in range():</p> <pre><code>import xlwings as xw wb = xw.Book(r&quot;test.xlsx&quot;) wb.sheets[0].range(&quot;2:2&quot;).delete() </code></pre> <p>...
python|excel|pandas|numpy|xlwings
0
6,210
71,140,280
I'm trying to merge a small dataframe to another large one, looping through the small dataframes
<p>I am able to print the small dataframe and see it is being generated correctly, I've written it using the code below. My final result however contains just the result of the final merge, as opposed to passing over each one and merging them.</p> <p>MIK_Quantiles is the first larger dataframe, df2_t is the smaller dat...
<p>Your loop does not do anything meaningful, other than increment <code>i</code>.</p> <p>You do a merge of 2 (static) dfs (<code>MIK_Quantiles</code> and <code>df2_t</code>), and you do that <code>df_length</code> number of times. Everytime you do that (first, i-th, and last iteration of the loop), you overwrite the o...
python|pandas|loops|merge
1
6,211
71,360,345
How to handle .json fine in tabular form in python?
<p>By using this code:</p> <pre><code>import pandas as pd patients_df = pd.read_json('/content/students.json',lines=True) patients_df.head() </code></pre> <p>the data are shown in tabular form look like this: <a href="https://i.stack.imgur.com/1Srhq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Sr...
<p>Possible solution could be the following:</p> <pre><code># pip install pandas import pandas as pd import json def separate_column(row): for e in row[&quot;scores&quot;]: row[e[&quot;type&quot;]] = e[&quot;score&quot;] return row with open('/content/students.json', 'r') as file: data = [json....
python|json|python-3.x|pandas
2
6,212
52,102,805
Two dataframes broadcast together in multiple subplots
<p>I want to plot 5 different subplots, one for each year of data. For each year, I want to show the DEMs and REPs for each county. I have written the following code so far:</p> <pre><code>fig = plt.figure(figsize=(13,10)) plt.subplot(3, 2, 1) plt.bar(data=districts_2018[['DEM', 'REP']], x=districts_2018.i...
<p>You may directly use the pandas wrapper to plot grouped bar plots. Set the <code>ax</code> to the respective subplot you want the plot to appear in.</p> <pre><code>fig, axes = plt.subplots(3,2,figsize=(13,10)) for ax, df in zip(axes.flat, [districts_2018, districts_2017, ....]) df[['DEM', 'REP']].plot.bar(ax=ax...
python|pandas|matplotlib|plot
1
6,213
60,567,266
Reshaping Numpy array repeating some elements
<p>I have trained a NN in Keras with LSTM, so I have been using 3D tensors. Now I want to predict with a dataset and I have to insert a 3D tensor in my NN. </p> <p>(In my case I used <code>features = 2</code> and <code>lookback = 2</code>, so input elements in LSTM are <code>(batch_size, lookback, features)</code>)</p...
<p>You are looking for sliding windows and there's <a href="https://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_windows" rel="nofollow noreferrer"><code>skimage's view_as_windows</code></a> for that -</p> <pre><code>In [46]: from skimage.util.shape import view_as_windows In [44]: features = 2...
python|numpy|keras
2
6,214
72,660,393
How to convert a 2D Numpy object array containing same-length lists to a normal 3D Numpy array?
<p>I have a 2D object array of arrays of the same size, and I want to convert this to an ordinary 3D array. The array dimensions are huge, so this should preferably be done in an optimized and in-place way.</p> <p>I found a question about doing this for an 1D array containing arrays of size 1, but the solutions, and an...
<p>So you have a 2d object dtype array:</p> <pre><code>In [110]: arr Out[110]: array([[array([1, 2, 3, 4]), array([1, 2, 3, 4]), array([1, 2, 3, 4])], [array([1, 2, 3, 4]), array([1, 2, 3, 4]), array([1, 2, 3, 4])], [array([1, 2, 3, 4]), array([1, 2, 3, 4]), array([1, 2, 3, 4])]], dtype=object) In...
python|arrays|numpy|types|casting
0
6,215
59,875,481
How to find the maximum value of a column with pandas?
<p>I have a table with 40 columns and 1500 rows. I want to find the maximum value among the 30-32nd (3 columns). How can it be done? I want to return the maximum value among these 3 columns and the index of dataframe.</p> <pre><code>print(Max_kVA_df.iloc[30:33].max()) </code></pre> <p><a href="https://i.stack.imgur.c...
<p>hi you can refer this example</p> <pre><code>import pandas as pd df=pd.DataFrame({'col1':[1,2,3,4,5], 'col2':[4,5,6,7,8], 'col3':[2,3,4,5,7] }) print(df) #print(df.iloc[:,0:3].max())# Mention range of the columns which you want, In your case change 0:3 to 30:33, here 33 will be excluded ser=df.iloc[:,0:3].m...
python|excel|pandas
1
6,216
59,522,090
Resample daily data to hourly dataframe and copy contents
<p>I have the following Dataframe:</p> <pre><code> Date Holiday 0 2018-01-01 New Year's Day 1 2018-01-15 Martin Luther King, Jr. Day 2 2018-02-19 Washington's Birthday 3 2018-05-08 Truman Day 4 2018-05-28 Memorial Day ... ... ... 58 2022-10-10 Columbus Day 59 2022-11-11 Veterans Da...
<p>How about</p> <pre><code>df.set_index("Date").resample("H").ffill().reset_index().rename( {"Date": "Timestamp"}, axis=1 ) </code></pre>
python|python-3.x|pandas
1
6,217
32,252,728
Pandas Indexing vs Copy Error
<p>I have the Data2 column in my dataframe. I am trying to create a new column ('NewCol') by applying a filter to the Data2 column. Below code works and the results of the new column is correct. But I get the below error message when running the code. How can I fix this? I would think this impacts performance.</p> <p>...
<p>Try using <code>.loc</code></p> <pre><code>df.loc[df['Data2']&gt; 60, 'NewCol'] = 'True' </code></pre> <p>Pandas is very efficient in memory management. For most operations (filters) it returns reference to data already existing in memory (DataFrame). However in some cases it has to make copy and return this. Any ...
python|pandas
1
6,218
40,699,349
How to use a custom pandas groupby aggregation function to combine rows in a dataframe
<p>I have a dataframe with a <code>name</code> column and a <code>department</code> column. There are repeats in the <code>name</code> column that have different <code>department</code> values but all other column values are identical. I'd like to <em>flatten</em> these repeats into a single row and combine the differe...
<pre><code>df = pd.DataFrame( dict( name=list('ABCDEFGACEF'), dept=list('xyxyzxyzyxz') ) ) df.groupby('name').dept.apply(list).reset_index() </code></pre> <p><a href="https://i.stack.imgur.com/QFP7y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QFP7y.png" alt="enter image ...
python|pandas|group-by
1
6,219
40,671,443
Numpy: how to return a view on a matrix A based on submatrix B
<p>Given a matrix A with dimensions axa, and B with dimensions bxb, and axa modulo bxb == 0. B is a submatrix(s) of A starting at (0,0) and tiled until the dimensions of axa is met.</p> <pre><code>A = array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) </cod...
<p>You can obtain this as follows:</p> <pre><code>&gt;&gt;&gt; A = np.array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) &gt;&gt;&gt; A[np.ix_([1,3],[1,3])] = 20 &gt;&gt;&gt; A array([[ 0, 1, 2, 3], [ 4, 20, 6, 20], [ 8, 9, 10, 11], ...
python|numpy|matrix
3
6,220
57,812,300
Python pandas to calculate mean of datetime of multiple columns
<p>Given an example table <code>df</code> as below, how to calculate mean date of <code>TIME1, TIME2, TIME3.</code></p> <pre><code>df['AVG_TIME'] = df[['TIME1', 'TIME2', 'TIME3']].mean(axis=1) </code></pre> <p>This returns <code>NaN</code> values</p> <pre><code>ID TIME1 TIME2 TIME3 0 2018-07-11 2018-07-09 ...
<p>This could be done as follows:</p> <pre class="lang-py prettyprint-override"><code>import time import datetime import pandas as pd # build the df c = ['TIME1' , 'TIME2' , 'TIME3'] d = [['2018-07-11', '2018-07-09', '2018-07-12'], ['2018-07-12', '2018-06-12', '2018-07-15'], ['2018-07-13', '2018-06-...
python|pandas|datetime
0
6,221
34,396,128
Resample pandas dataframe by both name and origin
<p>I have the following Pandas DataFrame object <code>df</code>. It is a train schedule listing the date of departure, scheduled time of departure, and train company.</p> <pre><code>import pandas as pd df = Year Month DayofMonth DayOfWeek DepartureTime Train Origin Datetime 1988-01-01 1988 1 ...
<p>My input data (add and change some date):</p> <pre><code>print df Year Month DayofMonth DayOfWeek DepartureTime Train \ Datetime 1988-01-01 1988 1 1 5 1457 BritishRail 1988-01-01 1...
python|pandas|time-series
1
6,222
36,896,172
"undefined symbol" error when importing SWIG+python module
<p>I created a *.so file for use in Python using SWIG, but when I import it I get this:</p> <pre><code>/_analyzer.so: undefined symbol: autocorellation </code></pre> <p>I did almost everything according to this instruction: <a href="https://scipy.github.io/old-wiki/pages/Cookbook/SWIG_NumPy_examples.html" rel="nofoll...
<p>The difference between your code and the cookbook examples is that your code is C++. Therefore, you need to pass the <code>-c++</code> option to SWIG. In the construction of <code>Extension(...)</code> in setup.py, simply add <code>swig_opts=['-c++'],</code>.</p> <p>Note that distutils will still invoke the C compi...
python|c++|numpy|swig
0
6,223
37,011,828
Pandas: delete duplicate rows
<p>I have the following df:</p> <pre><code>url='https://raw.githubusercontent.com/108michael/ms_thesis/master/crsp.dime.mpl.abbridged' zz=pd.read_csv(url) zz.head(30) date feccandid feccandcfscore.dyn pacid paccfscore cid catcode type_x di amtsum state log_diff_unemployment party type_y...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a>:</p> <pre><code>print zz.drop_duplicates() </code></pre>
python|pandas
2
6,224
49,519,954
exp() overflow error python 3
<p>I tried various solutions for below, but I still get the errors as described:</p> <pre><code>log1p(1 + math.exp(comp * -1)) </code></pre> <p>Error: <code>OverflowError: math range error</code></p> <p>So I changed it to: <code>log1p(1 + np.exp(comp * -1))</code> Now I get error : <code>RuntimeWarning: overflow enc...
<p>I replaced the code as below:</p> <pre><code>loss = loss - log1p(expit(val)) </code></pre> <p>Basically I rearranged my code to be able to use the expit function...</p>
python-3.x|numpy|exp|overflowexception
0
6,225
28,200,786
How to plot scikit learn classification report?
<p>Is it possible to plot with matplotlib scikit-learn classification report?. Let's assume I print the classification report like this:</p> <pre><code>print '\n*Classification Report:\n', classification_report(y_test, predictions) confusion_matrix_graph = confusion_matrix(y_test, predictions) </code></pre> <p>an...
<p>Expanding on <a href="https://stackoverflow.com/users/3089523/bin">Bin</a>'s answer:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np def show_values(pc, fmt="%.2f", **kw): ''' Heatmap with text in each cell with matplotlib's pyplot Source: https://stackoverflow.com/a/25074150/395857 ...
python|numpy|matplotlib|scikit-learn
42
6,226
27,979,443
What is the real working of ndim in NumPy?
<p>Consider:</p> <pre><code>import numpy as np &gt;&gt;&gt; a=np.array([1, 2, 3, 4]) &gt;&gt;&gt; a array([1, 2, 3, 4]) &gt;&gt;&gt; a.ndim 1 </code></pre> <p>How is the dimension 1? I have given a equation of three variables. It means it is three-dimensional, but it is showing the dimension as 1. What is the logic of ...
<p>As the <a href="http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html" rel="nofollow noreferrer">NumPy documentation</a> says, <code>numpy.ndim(a)</code> returns:</p> <blockquote> <p>The number of dimensions in <code>a</code>. Scalars are zero-dimensional</p> </blockquote> <p>E.g.:</p> <pre><code>a = np.arr...
python|numpy
5
6,227
28,035,236
test if list contains a number in some range
<p>Let's say I have a list <code>L=[1.1, 1.8, 4.4, 5.2]</code>. For some integer, <code>n</code>, I want to know whether <code>L</code> has a value <code>val</code> with <code>n-1&lt;val&lt;n+1</code>, and if so I want to know the index of <code>val</code>.</p> <p>The best I can do so far is to define a generator</p>...
<p>If L is sorted, you could use <code>bisect.bisect_left</code> to find the index i for which all L[&lt; i] &lt; n &lt;= all L[>= i].</p> <p>Then</p> <pre><code>if n - L[i-1] &lt; 1.0: val = L[i-1] elif L[i] - n &lt; 1.0: val = L[i] else: val = None # no such value found </code></pre> <hr> <p><stro...
python|numpy
4
6,228
73,424,093
'poorly' organized csv file
<p>I have a CSV file that I have to do some data processing and it's a bit of a mess. It's about 20 columns long, but there are multiple datasets that are concatenated in each column. see dummy file below</p> <p>I'm trying to import each sub file into a separate pandas dataframe, but I'm not sure the best way to parse...
<pre><code>from io import StringIO import pandas as pd data =&quot;&quot;&quot; TIME,HDRA-1,HDRA-2,HDRA-3,HDRA-4 0.473934934,0.944026678,0.460177668,0.157028404,0.221362174 0.911384892,0.336694914,0.586014563,0.828339071,0.632790473 0.772652589,0.318146985,0.162987171,0.555896202,0.659099194 0.541382917,0.03370676...
pandas|csv|python-3.9
0
6,229
35,085,830
Python pandas plot time-series with gap
<p>I am trying to plot a pandas DataFrame with TimeStamp indizes that has a time gap in its indizes. Using pandas.plot() results in linear interpolation between the last TimeStamp of the former segment and the first TimeStamp of the next. I do not want linear interpolation, nor do I want empty space between the two dat...
<p>Try:</p> <pre><code>df.plot(x=df.index.astype(str)) </code></pre> <p><a href="https://i.stack.imgur.com/1Rb14.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1Rb14.png" alt="Skip the gap"></a></p> <p>You may want to customize ticks and tick labels.</p> <p><strong>EDIT</strong></p> <p>That works for me...
python|pandas|plot|time-series
9
6,230
67,298,754
ImportError: Missing optional dependency 'xlrd'. Install xlrd >= 1.0.0 for Excel support Use pip or conda to install xlrd
<p>I used pandas to read excel file and then received an ImportError shown below.</p> <p>code:</p> <pre><code>pressure_2018=pd.read_excel('2018_pressures.xlsx') </code></pre> <p>Error:</p> <pre><code>ImportError: Missing optional dependency 'xlrd'. Install xlrd &gt;= 1.0.0 for Excel support Use pip or conda to install ...
<p>You can install <a href="https://pypi.org/project/openpyxl/" rel="noreferrer">openpyxl</a> using <code>pip install openpyxl</code> and then try:</p> <pre><code>pd.read_excel('2018_pressures.xlsx', engine='openpyxl') </code></pre> <p>This is an alternative solution but it will work.</p>
python|pandas
11
6,231
67,426,181
How to use the result of tf.argmax to access values at the corresponding positions?
<p>I want to access values of a tensor next to their maximal values. For that, I get the locations of the maxima via <code>tf.argmax</code>, add one to it and then need to look up the values.</p> <pre><code>f0_binned = tf.random.normal([2, 1000, 360]) idx = tf.argmax(f0_binned, axis=-1) # [2, 1000] tf.gather(f0_binned...
<p>You can calculate the gradients using TF and then use NumPy to find the values you are looking for:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import numpy as np f0_binned = tf.random.normal([2, 1000, 360]) idx = np.argmax(f0_binned, axis=-1) i, j, k = f0_binned.numpy().shape I, J =...
python|tensorflow
1
6,232
67,542,315
Pandas expanding dataframe returning multiple values on apply
<p>Is there a way I can apply percentile function on multiple percentile values on an expanding dataframe.</p> <pre><code>import numpy as np import pandas as pd a = np.random.rand(1000) df = pd.DataFrame(a,columns=['Data']) val = [25,30] df['25th_Perc'] = df.expanding(min_periods=1).apply(lambda x: np.nanpercentile...
<p>I have only a solution with <code>numpy</code>:</p> <pre class="lang-py prettyprint-override"><code>a = np.tril(df[&quot;Data&quot;].values) a[np.triu_indices(a.shape[0], k=1)] = np.nan p = np.nanpercentile(a, val, interpolation=&quot;nearest&quot;, axis=1) df[[&quot;25th_Perc&quot;, &quot;50th_Perc&quot;]] = p.T </...
python|pandas|numpy
1
6,233
67,564,125
Item wrong length when use pandas isin to filter column
<p>I'm experienced item wrong length when use pandas isin to filter column</p> <p>Here's my code</p> <p><code>selected_raw_data = raw_data[raw_data.columns.isin(selected['Column'])].copy()</code></p> <p>Error message here</p> <pre><code>--------------------------------------------------------------------------- ValueEr...
<p>Assuming selected['Column'] resolves to a list or list-like (like a series or a column of a dataframe) of column names, you can use:</p> <pre><code>raw_data[selected['Column']].copy() </code></pre> <p>to filter for the selected columns.</p>
python|pandas|dataframe
1
6,234
34,539,965
Data Frame in Panda with Time series data
<p>I just started learning pandas. I came across this;</p> <pre><code>d = date_range('1/1/2011', periods=72, freq='H') s = Series(randn(len(rng)), index=rng) </code></pre> <p>I have understood what is the above data means and I tried with IPython:</p> <pre><code>import numpy as np from numpy.random import randn impo...
<p>To give you some pointers in addition to @Dthal's comments:</p> <pre><code>r = pd.date_range('1/1/2011', periods=72, freq='H') </code></pre> <p>As commented by @Dthal, you can simplify the creation of your <code>DataFrame</code> randomly sampled from the normal distribution like so:</p> <pre><code>df = pd.DataFra...
python|pandas|matplotlib|dataframe|histogram
1
6,235
60,169,813
Python: Find roots of 2d polynomial
<p>I have a 2D numpy array C which contains the coefficients of a 2d polynomial, such that the polynomial is given by the sum over all coefficients:</p> <pre><code>c[i,j]*x^i*y^j </code></pre> <p>How can I find the roots of this 2d polynomial? It seems that numpy.roots only works for 1d polynomials.</p>
<p>This is a polynomial in two variables. In general there will be infinitely many roots (think about all the values of x and y that will yield xy=0), so an algorithm that gives you all the roots cannot exist.</p>
python|numpy|polynomials|equation-solving
2
6,236
49,969,484
sequence tagging task in tensorflow using bidirectional lstm
<p>I am little interested in sequence tagging for NER. I follow the code "<a href="https://github.com/monikkinom/ner-lstm/blob/master/model.py" rel="nofollow noreferrer">https://github.com/monikkinom/ner-lstm/blob/master/model.py</a>" to make my model like below:</p> <pre><code>X = tf.placeholder(tf.float32, shape=[No...
<p>Please check the dimensions of the tensors y_true, output(both the places), logits and prediction and check whether it comes as per your expectation. </p>
python|tensorflow|lstm|sequence-to-sequence|named-entity-recognition
0
6,237
50,114,964
Concat consecutive rows by grouping columns
<p>I am trying something in Python to concat <code>ProdID</code> based on ProdCategory. All I need is last two columns <code>MainProdConcat</code> and <code>MainProdConcat_PCOnly</code>.</p> <p>Let me know if its possible</p> <pre><code>OrderN0 ProdID ProdCategory ItemNo ProdType MainItem MainProdConcat MainP...
<p>Given print(df):</p> <pre><code> OrderN0 ProdID ProdCategory ItemNo ProdType MainItem 0 123334 1 PC 100 Main 100 1 123334 2 PC 110 Option 100 2 123334 3 PC 120 Option 100 3 123334 4 PC 130 O...
python|pandas
0
6,238
64,094,104
How to take one column out of a dataframe in python
<p>THIS PROGRAM IMPORTS A DATAFRAME AND THEN ATTEMPTS TO EXTRACT ONE COLUMN HOWEVER I RECEIVE AN EROR WHEN I TRY TO EXTRACT ONE COLUMN (THE OPEN COLUMN)</p> <p>import tensorflow as tf print(tf.<strong>version</strong>)</p> <h1>IMPORT LIBRARIES</h1> <pre><code>import pandas as pd import numpy as np import io from googl...
<p>you can extract the column using the iloc method, like this:</p> <pre><code>apple_open_price = apple_all_stock_data.iloc[:, 3].values </code></pre> <p>The colon will indicate the lines and the number after the comma the respective column, remembering the first column starts at 0.</p> <p>In pandas we have two very in...
python|pandas|csv|opencsv
0
6,239
64,165,643
how to find the cells which values are a string type inside a dataframe
<p>I have a dataframe, when I tried to calcualte pct_change(), it shows me an error of <code>TypeError: unsupported operand type(s) for /: 'str' and 'float'</code>. Then I tried to convert the type into float, it shows me <code>ValueError: could not convert string to float</code>:</p> <pre><code>unemployment_df['Unempl...
<p>Pandas doesn't really distinguish between types more granular than <code>object</code>.</p> <pre><code>df[df['col']].apply(lambda x: isinstance(x, str)) </code></pre> <p>will give you the rows that contain strings in column <code>'col'</code></p> <p>You could then clean them up however you wish.</p>
python|pandas
1
6,240
64,082,656
Why can't I split the calendar year into 10-day increments correctly?
<p>I have the following code that splits the calendar year into 10-day increments in which the first ten-day increment should be a &quot;1&quot;, the next 10-day increment, &quot;2&quot;, etc.</p> <p>For some reason I only have nine &quot;1s&quot; whereas there should be ten. Could someone help me with this?</p> <pre c...
<p>Because <code>tm_yday</code> starts with <code>1</code> and not <code>0</code>.</p> <p>You should use this if you want to start counting from <code>1</code>:</p> <pre class="lang-py prettyprint-override"><code>from datetime import timedelta, datetime datetimes = np.arange( datetime(2018,1,1), datetime(2019,1,1)...
python|numpy|datetime|series
1
6,241
63,979,191
Problem with changing value of multiple rows to NaN
<p>I have this DataFrame:</p> <pre><code>test = database[['WEATHER']] </code></pre> <p><img src="https://i.stack.imgur.com/VVEda.png" alt="enter image description here" /></p> <p>Some of the values of WEATHER are &quot;Unknown&quot; and &quot;Other&quot;, which don't bring much value to it so I want to change them to N...
<p>Typically, you want to avoid iterating over a pandas <code>DataFrame</code>. Here is how I would do it:</p> <pre><code>&gt;&gt;&gt; df.a 0 Other 1 Unknown 2 BLAH Name: a, dtype: object &gt;&gt;&gt; df.a = np.choose(df.a.isin(['Other', 'Unknown']), [df.a, np.nan]) &gt;&gt;&gt; df.a 0 NaN 1 NaN 2...
python|numpy|dataframe|for-loop|nan
0
6,242
63,900,788
Compare timestamp with datetime
<p>I have one timestamp from a dataframe and a datetime object, I want to compare them to do a select in a dataframe. My data are as followed:</p> <pre><code>print(type(datetime.datetime.now())) &lt;class 'datetime.datetime'&gt; print(type((df.created_at[0]))) &lt;class 'pandas._libs.tslibs.timestamps.Timestamp'&gt; <...
<p>Timestamp is a timezone-aware object, while the datetime object you get from <code>datetime.datetime.now()</code> is timezone-naive since you don't specify otherwise, hence the error. You should convert so that they're either both timezone-aware or both timezone-naive.</p> <p>For example, you can call <code>datetime...
python|pandas|datetime
2
6,243
63,871,200
Plotting the Convergence Results of scipy.optimize.differential_evolution
<p>I have two dataframes (df_1, df_2), some variables (A,B,C), a function (fun) and a global, genetic optimiser that finds the maximum value of fun for a given range of A,B,C.</p> <pre><code>from scipy.optimize import differential_evolution df_1 = pd.DataFrame({'O' : [1,2,3], 'M' : [2,8,3]}) df_2 = pd.DataFrame({'O' ...
<p>So I am not sure to have found the best way, but I found one. It uses the fact that list are pass by reference. That means that if you pass the list to the function and modify it, it will be modified for the rest of the programme even if it is not returned by the function.</p> <pre><code># Params results = [] # thi...
python|pandas|matplotlib|genetic-algorithm|scipy-optimize
2
6,244
64,119,007
Move row up and reset index pandas dataframe
<p>I have a dataframe with the following columns. need to sortby tr_date and move the 6th index row to 1st index.</p> <pre><code>original datafarame index tr_date val_date des con cr dr bal 0 05-06-2020 05-06-2020 JH876875 NEFT 0 500 500 1 02-07-2020 02-07-2020 45546 ...
<p>this code works for changing the rows:</p> <pre><code>df.iloc[6], df.iloc[1] = df.iloc[1], df.iloc[6] </code></pre> <p>greetings Jan</p>
python|pandas|dataframe
1
6,245
46,911,163
How to get similar elements of two numpy arrays with a tolerance
<p>I would like to compare values from columns of two different numpy arrays A and B. More specifically, A contains values from a real experiment that I want to match with theoretical values that are given in the third column of B.</p> <p>There are no perfect matches and therefore I have to use a tolerance, e.g. 0.01....
<p>I'd imagine it would be something like</p> <pre><code>i = np.nonzero(np.isclose(A[:,:,None], B[:, 2]))[-1] </code></pre> <p><a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.isclose.html" rel="nofollow noreferrer"><code>np.isclose</code></a> accepts a few different tolerance parameters.</p...
arrays|python-3.x|performance|numpy|comparison
1
6,246
32,929,318
Is there a way to test an SQLAlchemy Connection?
<p>I'm using SQLAlchemy to connect to write a pandas DataFrame to a MySQL database. Early on in my code I create an SQLAlchemy engine:</p> <pre><code>engine = create_my_sqlalchemy_connection() </code></pre> <p>I execute some queries, do some calculations, and then try to use that same engine to write to the database ...
<p>You can have SQLAlchemy check for the liveness of the connection with the parameter <code>pool_pre_ping</code>: <a href="https://docs.sqlalchemy.org/en/13/core/engines.html#sqlalchemy.create_engine.params.pool_pre_ping" rel="nofollow noreferrer">https://docs.sqlalchemy.org/en/13/core/engines.html#sqlalchemy.create_e...
python|pandas|sqlalchemy
4
6,247
38,630,716
Issue creating a Numpy NDArray from PyArray_SimpleNewFromData
<p>I try to do a python wrapper to bind some C++ functions and types to python. My issue is when I try to convert a custom matrix type to a numpy ndarray. The most convincing solution is to use <code>PyArray_SimpleNewFromData</code>.</p> <p>To test its behaviour, as I didn't manage to do what I wanted I tried to imple...
<p>I would try with an array that has been allocated by malloc, and then perhaps settings some flag named <code>OWNDATA</code> in order to avoid a memory leak. </p> <p>At least the garbage data can be explained if the instance of <code>numpy.ndarray</code> does not copy the data but just stores a pointer to the suppli...
python|c++|numpy|wrapper
3
6,248
63,165,778
Numpy Array to Rust by ndpointer, fails in Windows (works on Linux)
<p>Objective: Pass an np.ascontiguousarray to a Rust function via ctypes. Rust makes various changes to the array in place. Process continues in Python. the code is tested an runs as expected in a Linux environment (Built in rust-cargo stable on Linux, called from Python 3.8 in Manjaro, 4.19 Kernel), but raises the er...
<p>Following Jmb's suggestion of <a href="http://jakegoulding.com/rust-ffi-omnibus/slice_arguments/" rel="nofollow noreferrer">http://jakegoulding.com/rust-ffi-omnibus/slice_arguments/</a> and</p> <ul> <li><a href="https://doc.rust-lang.org/std/slice/fn.from_raw_parts_mut.html" rel="nofollow noreferrer">https://doc.rus...
numpy|rust|ffi
1
6,249
67,950,144
extract headers from dataframe's column containing both headers and values
<p>I am trying to read an excel file that has a column that consists of both numerical information and headers. Below I enclose the screenshot of this excel file: <a href="https://i.stack.imgur.com/ZOuOq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZOuOq.png" alt="excel file" /></a></p> <p>As you ...
<p>Aside from reading the excel file, the main issue you’ll have here is that the specification column has repeated values, so if you set it as an index and try getting <code>2</code>, it’s not going to know which model to return.</p> <p>To load the data:</p> <pre><code>df = pd.read_excel(path, header=[5,6], sheet_name...
python|excel|pandas|dataframe|pandas-groupby
1
6,250
68,008,609
Numpy: use array of indices to replace values in another array
<p>I have the following two bidimensional arrays:</p> <pre><code>np.random.seed(1) a = np.random.normal(1,11,(5,5)) b = np.random.randint(0,5,(2,2)) print(a) print(b) </code></pre> <p>What yields this:</p> <pre><code>[[ 18.867799 -5.72932055 -4.80988927 -10.80265484 10.51948392] [-24.31692567 20.19292941 -7.3...
<p>Maybe not the sexiest answer but if it doesn't have to be fast you could use a vanilla <code>for</code> loop</p> <pre><code>for i in b: a[i[0], i[1]] = 0 </code></pre>
python|numpy
0
6,251
67,963,735
Python: Is there a direct simple way to delete a row of a .csv file without the read-delete-rewrite process?
<p>I have a .csv file that includes hundreds of millions of rows (yes, big data), and I want to use Python to delete the last row of it. I do know some methods that follow the read-delete-rewrite process. For example, use <code>pandas</code> library, <code>pd.read_csv()</code> to read it first, use <code>.drop()</code>...
<p>I would not use Python at all. Just use Unix command-line tools. <a href="https://superuser.com/a/543959">Here's an example</a> using the <code>head</code> command to skip the nth last line. That being said, if you want to do anything more complex then skipping the last line, then you should put this file into a dat...
python|pandas|dataframe|csv|data-processing
0
6,252
41,353,885
Theano function using individual elements of input
<p>I am trying to build a Theano function that takes a <code>T.vector</code> of Euler angles as input and returns a directional vector corresponding to those Euler angles. First, I take the sines and cosines of each element of the vector, then I arrange these into a rotation matrix. Finally, I multiply the directional ...
<p>use <code>theano.tensor.stacklists()</code>.</p> <pre><code>rot_matrix = T.stacklists([[...], ...]) </code></pre>
python|numpy|graphics|rotation|theano
2
6,253
41,399,481
How do you decode one-hot labels in Tensorflow?
<p>Been looking, but can't seem to find any examples of how to decode or convert back to a single integer from a one-hot value in TensorFlow.</p> <p>I used <code>tf.one_hot</code> and was able to train my model but am a bit confused on how to make sense of the label after my classification. My data is being fed in via...
<p>You can find out the index of the largest element in the matrix using <a href="https://www.tensorflow.org/api_docs/python/math_ops/sequence_comparison_and_indexing#argmax" rel="noreferrer"><code>tf.argmax</code></a>. Since your one hot vector will be one dimensional and will have just one <code>1</code> and other <c...
python|tensorflow|machine-learning|deep-learning|one-hot-encoding
25
6,254
61,252,660
How do I parallelize .apply in pandas on string?
<p>I realize this question might've been asked before, but I didn't find solution that works specifically for strings and is relatively simple.</p> <p>I have a data frame that has a column with a zip code that uses remote API to fetch details about this zip code. What I'm trying is to parallelize data fetching to perf...
<p>I may have found a solution from the related post.</p> <p><a href="https://stackoverflow.com/questions/45545110/how-do-you-parallelize-apply-on-pandas-dataframes-making-use-of-all-cores-on-o/55643414#55643414">This one</a> worked for me, while others didn't. I also had to this: <a href="https://github.com/darkskyap...
python|pandas|dataframe
0
6,255
61,360,663
populating empty dataframe from a list in python
<p>I need to populate dataframe from the list.</p> <pre><code>lst=[1,"name1",10,2,"name2",2,"name2",20,3] df=pd.DataFrame(columns=['a','b','c']) j=0 for i in range(len(list(df.columns))-1): for t,v in enumerate(lst): col_index=j%3 df.iloc[i,col_index]=lst[t] j=j+1 </code></pre> <p>The above ...
<p>Create a list of dictionarys <code>[{key:value, key:value}, {key:value, key:value}, {key:value, key:value}]</code></p> <p>Add this straight as a dataframe. You can also control what is added this way by making a fucntion and passing data to it as the dictionary is built.</p> <p>You can achieve this using itertool...
python|pandas
1
6,256
68,513,904
Get line count of a specific column and get the value of that specific column using row number
<p>python, pandas read from csv file.</p> <p>How do I get only TMI value from a specific row?</p> <p>I mean by using ROW and single INDEX or COLUMN,</p> <p>Like only get TMI 17 or 20 value and see how many TMI is there and get TMI line count.</p> <pre><code>import pandas as pd with open('./Essentials/test2.csv','r') as...
<p>to get a value of a specific cell</p> <pre><code>weather_df.at[row index, 'column name'] </code></pre> <p>for example the following will give you a value of <code>17</code></p> <pre><code>weather_df.at[0, 'TMI'] </code></pre> <p>to get the number of cells excluding NaN use <code>.count()</code></p> <pre><code>weathe...
python|pandas|csv|datatable
0
6,257
68,486,220
Using tensorflow in ML, why my kernel restarts constantly?
<p>from the kernel :</p> <pre><code>In[1]: runfile('/home/yannick/Documents/ML/MNIST-reco/neural_network_V1.py', wdir='/home/yannick/Documents/ML/MNIST-reco') Restarting kernel... In [1]: </code></pre> <p>The thing is that when i run the code, instead of working, it restarts the kernel and nothing happends plea...
<p>I needed to delete my tensorflow lib and reinstall it using anaconda, then it work again. It's just about re-importing the libs on anaconda and relaunch spyder. hth</p>
python|tensorflow
0
6,258
53,336,497
Matplotlib: Stacked area chart for all the groups
<p>I am trying to create a stacked area chart for all the groups in my data on a similar timeline x-axis. My data looks like following </p> <pre><code>dataDate name prediction 2018-09-30 A 2.309968 2018-10-01 A 1.516652 2018-10-02 A 2.086062 2018-10-03 A 1.827490 2018-09-30 B 0.965861 2018-10-01...
<p>Say your data is stored in a dataframe named <code>df</code>. Then you can pivot the dataframe and plot it directly. Make sure your dates are actual dates, not strings.</p> <pre><code>df["dataDate"] = pd.to_datetime(df["dataDate"]) df.pivot("dataDate", "name", "prediction").plot.area(); </code></pre> <p><a href="h...
python|pandas|matplotlib|stacked-chart
4
6,259
65,554,263
How do we output a Panda dataframe via Python for use as a .csv?
<p>What's the quickest way to output a Panda dataframe via Python for use as a .csv?</p> <p>My output is called 'dframe' and it is really simple. Here is some code for context:</p> <p>dframe = df.head()</p>
<p>You can try</p> <pre><code>dframe.to_csv(r'your path') </code></pre>
python|pandas|output
0
6,260
65,687,227
Set values of pandas df cell based on conditions
<p>My df is as follows:</p> <p><a href="https://i.stack.imgur.com/ff1Dp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ff1Dp.png" alt="enter image description here" /></a></p> <p>What I want to do is, Condition: <code>Fruit Name</code> is NOT (<code>Apple or Mango</code>) and <code>veggie Name</code...
<p>You didn't use the exact name of the column <code>Enjoy Eating?</code>, so it created a new column called <code>Enjoy Eating</code> with NaN as default values. Just add the question mark and it will work as expected.</p> <p><code>df.loc[(~df[&quot;Fruit Name&quot;].isin([&quot;Apple&quot;,&quot;Mango&quot;]))&amp; (...
python|pandas|dataframe
0
6,261
65,629,347
Create dataframe in a "for" loop, in which a function can be applied to them
<p>The first for loop seems to work. However, when I move onto doing a groupby function on the next dataframe, something about the global variable in the for loop doesn't store the dataframe's correctly. Any help would be much appreciated. Thank you</p> <pre><code>chan_group = list(df_2017['Default Channel Grouping'].v...
<p>From @Nathan Furnal</p> <p><code>df_2017.groupby([&quot;Default Channel Grouping&quot;, &quot;Month&quot;]).sum()</code></p>
python|pandas|dataframe|for-loop|global
0
6,262
65,832,397
How can I find duplicates in a pandas data frame?
<p>I got the task to highlight all email duplicates in a pandas data frame. Is there a function for this or a way to drop all the NON duplicates which leaves me with a nice list off all the duplicates in the dataset?</p> <p>The table consists of six columns:</p> <pre><code>Email, FirstName, LastName, C_ID, A_ID, Create...
<p>Something like this might be the solution you're looking for:</p> <pre><code>import pandas as pd series = [ ('a@a.com','Bill', 'Schneider', 123, 321, 20190502), ('a@a.com', 'Damian', 'Schneider', 124, 231, 20190502), ('b@b.com', 'Bill', 'Schneider',164, 313, 20190503) ] # Create a DataFrame object d...
python|pandas|dataframe
3
6,263
65,527,125
Creating a dict of list from pandas row?
<p>I have a weird problem. I have a index and bunch of columns in a dataframe. I want the index to be a key and all the other columns to be in a list. Here's a example</p> <p>df:</p> <pre><code> 0 1 2 3 Barker Minerals Ltd Blackout Media Corp Booking Holdings Inc Booking Holdings I...
<p>The easiest answer as pointed out in the comments by Michael Szczesny:</p> <pre><code>df.T.to_dict(orient=&quot;list&quot;) </code></pre> <p>The output:</p> <pre><code>{'Barker Minerals Ltd': [nan, nan, nan, nan], 'Blackout Media Corp': [nan, nan, nan, nan], 'Booking Holdings Inc': ['Booking Holdings Inc', 'Book...
python|pandas
3
6,264
21,115,741
Average of a time related datasets in Pandas with missing values
<p>For a project I am working on I need to calculate average price of products for shops. Every time a shop changes the price of a product a new entry is added to the dataset. If a shop stops (temporarily or permanently) to sell a product, an entry is made with the time stamp and a price value of -1. Example:</p> <pre...
<p>AFAIR, <code>pandas</code> doesn't handle masked values the <code>numpy.ma</code> way. However, it should handle <code>nans</code> when computing the mean. The simplest solution is to parse your <code>Dataframe</code> and replace your price of <code>-1.00</code> by <code>np.nan</code> with something like:</p> <pre>...
python|numpy|pandas
0
6,265
63,636,901
Drop a row from Pandas Dataframe when any of the columns are duplicate
<p>I have a dataframe that contains answers to many questions.</p> <p>Each row represents an answer-er and the columns are the answers to the questions given Because people often spam those questionnaires sometimes there are answer-ers that give the same answer many times like ''yes good'', ''yes good''....</p> <p>I wo...
<pre><code># importing pandas package import pandas as pd data = {'ID': ['Id1', 'Id2','Id3', 'Id4'], 'Question 1': ['Ans. str1', 'Ans. string1','Ans. string1', 'Ans. string1'], 'Question 2': ['Ans. str2', 'Ans. string2','Ans. string2', 'Ans. string2'], 'Question 3': ['Ans. str3', 'Ans. st...
python|pandas|rows|drop
0
6,266
63,467,610
Execute SQL file, return results as Pandas DataFrame
<p>I have a complex SQL Server query that I would like to execute from Python and return the results as a Pandas DataFrame.</p> <p>My database is read only so I don't have a lot of options like other answers say for making less complex queries.</p> <p><a href="https://stackoverflow.com/questions/46694359/read-external-...
<p>I got it working.</p> <p>I had to use global variables by replacing @ with @@ I was able to get the query working as expected.</p> <p><code>DECLARE @@closing_period int = 0, @@starting_period int = 0</code></p> <p>Update: My ODBC driver was very outdated - after updating to the latest version, I no longer needed gl...
python|sql-server|pandas|pyodbc
1
6,267
63,718,944
Tensorflow Image Processing Function
<p>Guys I have made the tutorial of Basic Image Classification from Tensorflow.org. But I couldnt understand the codes of def image_process. Beceause there is no explanation in tutorial.</p> <p>This is code:</p> <pre><code>def plot_image(i, predictions_array, true_label, img): true_label, img = true_label[i], img[i] ...
<p>Lets start with the train code (Documentation inline)</p> <pre><code># TensorFlow and tf.keras import tensorflow as tf from tensorflow import keras # Helper libraries import numpy as np import matplotlib.pyplot as plt # load data fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_imag...
python|tensorflow|keras
0
6,268
24,782,365
Looping over 1st dimension of 3D numpy array to create a smaller 3D array, via slicing
<p>this is my first post so apologies if the formatting isn't quite right. I am writing some code for my masters dissertation, in which I am am studying satellite images of sea ice near the Alaskan coast. The satellite instrument I am using has 9 cameras, so for each image/band I have 9 subdatasets, which I am trying t...
<p>Here no need to iterate through 3D array . Remember when you want to perform some operations on elements of array (may be after getting the shorter array) then you will need to iterate over it.. when you want to create another subarray from existing there will be a way always to get rid of iteration in most the ca...
python|arrays|numpy|3d|netcdf
0
6,269
29,914,981
Fill in a numpy array without creating list
<p>I would like to create a numpy array without creating a list first. <br>At the moment I've got this: </p> <pre><code>import pandas as pd import numpy as np dfa = pd.read_csv('csva.csv') dfb = pd.read_csv('csvb.csv') pa = np.array(dfa['location']) pb = np.array(dfb['location']) ra = [(pa[i+1] - pa[i]) / float(p...
<p>You can calculate with vectors in numpy, without the need of lists:</p> <pre><code>ra = (pa[1:] - pa[:-1]) / pa[:-1] rb = (pb[1:] - pb[:-1]) / pb[:-1] </code></pre>
python|arrays|list|numpy
4
6,270
53,565,895
xlsx pandas write to s3 (with tabs)
<p>I have a project where i need to write dataframes to xlsx in an s3 bucket. It's quite simple to load a file from s3 with pandas quite simply by: df= pd.read_excel('s3://path/file.xlsx')</p> <p>But writing a file to s3 gives me problems. </p> <pre><code> import pandas as pd # Create a Pandas dataframe from t...
<pre><code>import io import boto3 import xlsxwriter import pandas as pd bucket = 'your-s3-bucketname' filepath = 'path/to/your/file.format' df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]}) with io.BytesIO() as output: with pd.ExcelWriter(output, engine='xlsxwriter') as writer: df.to_excel(writer,...
pandas|amazon-web-services|amazon-s3|xlsx
5
6,271
53,569,622
Difference between tf.train.Checkpoint and tf.train.Saver
<p>I found there are different ways to save/restore models and variables in <code>Tensorflow</code>. These ways including:</p> <ul> <li><a href="https://www.tensorflow.org/api_docs/python/tf/saved_model/simple_save" rel="nofollow noreferrer">tf.saved_model.simple_save</a></li> <li><a href="https://www.tensorflow.org/a...
<p>According to Tensorflow <a href="https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p><code>Checkpoint.save</code> and <code>Checkpoint.restore</code> write and read object-based checkpoints, in contrast to <code>tf.train.Saver</code> which writ...
python|tensorflow|deep-learning|eager-execution
0
6,272
53,633,043
Memory efficient solution to replace invalid values in a large DataFrame?
<p>This question is a continuation of the following: <a href="https://stackoverflow.com/questions/53625099/how-to-replace-certain-rows-by-shared-column-values-in-pandas-dataframe">How to replace certain rows by shared column values in pandas DataFrame?</a></p> <p>Let's say I have the following pandas DataFrame:</p> <...
<p>What if you try something a bit more memory efficient, like dictionary-based replacement instead of series-based? </p> <pre><code>mapping = dict(df.drop_duplicates('Name', keep='first').values) df['Age'] = df['Name'].map(mapping) print(df) Name Age 0 Alex 10 1 Bob 12 2 Clarke 13 3 Bob 12 ...
python|pandas|performance|dataframe
1
6,273
19,862,686
Error in astype float32 vs float64 for integer
<p>I'm sure this is due to a lapse in my understanding in how casting between different precision of float works, but can someone explain why the value is getting cast as 3 less than its true value in 32 vs 64 bit representation?</p> <pre><code>&gt;&gt;&gt; a = np.array([83734315]) &gt;&gt;&gt; a.astype('f') array([ 8...
<p>A <a href="http://en.wikipedia.org/wiki/Single_precision_floating-point_format" rel="nofollow">32-bit float</a> can exactly represent about 7 decimal digits of mantissa. Your number requires more, and therefore cannot be represented exactly.</p> <p>The mechanics of what happens are as follows:</p> <p>A 32-bit floa...
python|python-2.7|numpy|floating-point
4
6,274
20,206,615
How can a pandas merge preserve order?
<p>I have two DataFrames in pandas, trying to merge them. But pandas keeps changing the order. I've tried setting indexes, resetting them, no matter what I do, I can't get the returned output to have the rows in the same order. Is there a trick? Note we start out with the loans order 'a,b,c' but after the merge, it's...
<p>Hopefully someone will provide a better answer, but in case no one does, this will definitely work, so…</p> <p>Zeroth, I'm assuming you don't want to just end up sorted on <code>loan</code>, but to preserve <em>whatever</em> original order was in <code>x</code>, which may or may not have anything to do with the ord...
python|pandas
27
6,275
72,060,825
My code works outside the function but not inside
<p>The function below is not working anymore :</p> <pre><code>def videos_to_watch(section): #OK global list_already_watched list_already_watched = already_watched(ID).tolist() if section == 111: list_to_watch = set(p111)-set(list_already_watched) elif section == 113: list_to_watch = ...
<p>I'm not sure if this will help, but maybe you should initialize the variable as well. Like so:</p> <pre><code>def videos_to_watch(section): #OK global list_already_watched = 0 list_already_watched = already_watched(ID).tolist() if section == 111: list_to_watch = set(p111)-set(list_already_watc...
python|pandas|dataframe|function|global-variables
-1
6,276
71,859,126
How to generate uncorrelated samples with Numpy
<p>I'd like to generate random samples on python, but each with their own standard deviation.</p> <p>I thought I could use <code>np.random.normal(0, scale=np.array(standard_deviation), size=(len(np.array(standard_deviation)), number_of_simulations)</code></p> <p>However, bumpy seems not to work when I put an array for ...
<p>The NumPy random functions <em>do</em> accept arrays, but when you also give a <code>size</code> parameter, the shapes must be compatible.</p> <p>Change this:</p> <pre><code>np.random.normal(0, scale=np.array(standard_deviation), size=(len(np.array(standard_deviation)), number_of_simulations) </code></pre> <p>to</p>...
python|arrays|numpy|random|standard-deviation
1
6,277
22,029,167
Creating a Multi-Index / Hierarchical DataFrame from Dictionaries
<p>Say I have the following dictionaries:</p> <pre><code>multilevel_indices = {'foo': ['A', 'B', 'C'], 'bar': ['X', 'Y'], 'baz': []} column_data_1 = {'foo': [2, 4, 5], 'bar': [2, 3], 'baz': []} </code></pre> <p>How can I create a multi-index DataFrame using these dictionaries?</p> <p>It should be s...
<p>use <code>concat</code>:</p> <pre><code>multilevel_indices = {'foo': ['A', 'B', 'C'], 'bar': ['X', 'Y'], 'baz': []} column_data_1 = {'foo': [2, 4, 5], 'bar': [2, 3], 'baz': []} pd.concat([pd.Series(column_data_1[k], index=multilevel_indices[k]) for k in multilevel_indices], keys=multilevel...
python|pandas
2
6,278
55,553,062
How to count_values() for greater than column counts
<p>I am trying to determine how many rows have over 1000 counts for a specific column within my data. </p> <pre><code>police_2013 = pd.read_csv('..Data.csv') police_2013.unit.value_counts() </code></pre> <p>In this code, <code>police_2013.unit.value_counts()</code> gives me how many calls the Unit had. I want to coun...
<p>I think you want this.<br> This gives you how many unique values > 1000 are in the column <code>unit</code> of your dataset</p> <pre><code>len(police_2013[police_2013['unit']&gt;1000].unit.value_counts()) </code></pre>
python|pandas
0
6,279
56,810,854
How does df.groupby('A').agg('min') translate to featuretools?
<p>Say I have this simple snippet of code. I will group, aggregate, and merge the dataframe:</p> <hr> <h1>Using Pandas:</h1> <hr> <h3>Data</h3> <pre><code>df = pd.DataFrame({'A': [1, 1, 2, 2], 'B': [1, 2, 3, 4], 'C': [0.3, 0.2, 1.2, -0.5]}) </code></pre> df: <pre><code> A B C...
<p>Here is the recommended way to do it in Featuretools. You do need to create another table to make it work exactly as you want. </p> <pre><code>import featuretools as ft import pandas as pd df = pd.DataFrame({'A': [1, 1, 2, 2], 'B': [1, 2, 3, 4], 'C': [0.3, 0.2, 1.2, -0.5]}) e...
python|pandas|group-by|featuretools|feature-engineering
2
6,280
56,725,660
How does the groups parameter in torch.nn.conv* influence the convolution process?
<p>I want to convolve a multichannel tensor with the same single channel weight. I could repeat the weight along the channel dimension, but I thought there might be an other way.</p> <p>I thought the groups parameter might do the job. However I don't understand the documentation. That's why I want to ask how the grou...
<p>Just minor tips since I never used it.</p> <p>Group parameter multiplies the number of kernels you would normally have. So if you set group=2, expect 2 times more kernels.</p> <p>The definition of <a href="https://pytorch.org/docs/stable/nn.html#conv2d" rel="nofollow noreferrer">conv2d</a> in PyTorch states group...
python|pytorch
1
6,281
56,780,825
Pandas dataframe partition by different keys in one run
<p>In SQL we can count by different keys in one go with a help of OLAP functions, which improve sql performance:</p> <pre><code>select B, C, D, count(A) over (partition by B, C, D order by D) as by_BCD. count(A) over (partition by B, C order by D) as by_BC, count(A) over (partition by B order by D) as by_B, count(A)...
<p>In my comment above, I suggested using a <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html" rel="nofollow noreferrer">Multiindex</a>.</p> <p>My assumption was, that the performance penalty arises from the implicit indexing within group by statements.</p> <p>Creating the df as described...
python|pandas
0
6,282
25,790,740
Create a vector of mean substituted values based on another vector
<p>In my line of work it is not uncommon to have a continuous vector that needs to be 'discretized'. What I want to do is replace the values of a continuous variable that has been discretized by <code>cut</code> with the mean of another variable over those cut ranges.</p> <p><strong>EDIT</strong></p> <p>Furthermore, ...
<p>You could try:</p> <pre><code> x.disc &lt;- cut(x, c(-Inf, -2, 0, 2, Inf), labels=FALSE) lookup &lt;- aggregate(x, list(x.disc), mean) lookup$x[x.disc] </code></pre>
r|pandas
1
6,283
26,364,329
Fastest Count of Row Dependent Date Ranges
<p>I have a data set that looks like this (End_Time is 7 hours after Start_Time):</p> <pre><code> Value Start_Time End_Time 1 A 2014-10-14 05:00:00 2014-10-14 12:00:00 2 A 2014-10-14 08:00:00 2014-10-14 15:00:00 3 A 2014-1...
<p>In my opinion the only way you can achieve this quickly is if <code>Start_Time</code> increases. You could dispatch some complexity at insertion time by keeping ordered rows. With a sorted list of rows, testing if the following ones are within <code>[Start_Time, End_Time]</code> is easy, since as soon as you get an ...
python|pandas
0
6,284
66,892,709
Reinforcement Learning - only size-1 arrays can be converted to Python scalars - is it data problem?
<p>I'm new to pytorch and even though I was searching for this error I can't seem to understand where axactly I'm doing something wrong.</p> <p>I'm trying to run a codewith a model that trades 3 different stocks. My data is a csv file with three columns with closing prices of stocks.</p> <p>I'm trying to run this part ...
<p>You are passing <code>state = env.reset()</code> to:</p> <ul> <li><code>action = model.act(state)</code></li> <li><code>probs, state_value = self.forward(state)</code></li> <li><code>x = torch.tensor(x).cuda()</code></li> </ul> <p>And hence torch is throwing an error. It expects a numeric or array type input.</p>
python|pytorch|reinforcement-learning
0
6,285
66,864,453
How to change legend labels in scatter matrix
<p>I have a scatter matrix that I want to change the labels for. On the right-hand, I want to change the blue color <code>1</code> to Say Mystery and the red color <code>2</code> to say Science. I also want to change the labels of each graph to label their counterpart [Spicy, Savory, and Sweet]. I tried using dict to r...
<p>You can create a new column called <code>Q11_Labels</code> that maps <code>1</code> to <code>Mystery</code> and <code>2</code> to <code>Science</code> from the <code>Q11_Ans</code> column, and pass <code>colors='Q11_Labels'</code> to the <code>px.scatter_matrix</code> function. If you still want the legend to displa...
pandas|dataframe|plotly
0
6,286
66,806,383
Pandas Pivot Table Based on Specific Column Value
<p>I need to pivot my data in a df like shown below based on a specific date in the YYMMDD and HHMM column &quot;20180101 100&quot;. This specific date represents a new category of data with equal amounts of rows. I plan on replacing the repeating column names in the output with unique names. Suppose my data looks like...
<p>Does this suffice?</p> <pre><code>cols = ['YYMMDD', 'HHMM'] df.set_index([*cols, df.groupby(cols).cumcount()]).unstack() BestGuess(kWh) 0 1 YYMMDD HHMM 20180101 100 20 5 200 70 7 20201231 2100 50 2 ...
python|pandas|pivot
0
6,287
67,014,581
I have Dataframe in pandas with column Case Number, True value, Predicted, confidence. I need to split values accordingly with all combination shown
<p><strong>I have dataframe given below <a href="https://i.stack.imgur.com/wR9lP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wR9lP.png" alt="enter image description here" /></a></strong></p> <p>and am expecting result to be <a href="https://i.stack.imgur.com/eJhpP.png" rel="nofollow noreferrer"><...
<p>You can <code>split()</code> the pipe-strings into lists, pad each row's lists to the same length, then <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.explode.html" rel="nofollow noreferrer"><strong><code>explode()</code></strong></a> the lists.</p> <p>Using toy data:</p> <pre class="lang-py pre...
python|pandas|dataframe|numpy|pandas-datareader
1
6,288
47,280,228
Tensorflow: How to create confusion matrix
<p>I am new to tensorflow, I used this tutorial: </p> <p><a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/" rel="nofollow noreferrer">https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/</a>. </p> <p>I have trained the same model on new dataset which contains 3 labels. I ...
<p>You have 3 labels (say 0,1,2). Let's assume that you have a test set of size 10 and you get the following tensors: truth: [0,0,0,0,1,1,2,2,2,2] prediction: [2,0,0,1,1,1,2,1,2,2] Then you can do as,</p> <pre><code>&gt;&gt;&gt; import tensorflow as tf &gt;&gt;&gt; truth = [0,0,0,0,1,1,2,2,2,2] &gt;&gt;&gt; prediction...
python|python-2.7|tensorflow|tensorboard
3
6,289
47,131,780
Replace dots in a float column with nan in Python
<p>I have a data frame df like this</p> <pre><code>df = pd.DataFrame([ {'Name': 'Chris', 'Item Purchased': 'Sponge', 'Cost': 22.50}, {'Name': 'Kevyn', 'Item Purchased': 'Kitty Litter', 'Cost': '.........'}, {'Name': 'Filip', 'Item Purchased': 'Spoon', 'Cost': '...'}], index=['Store 1', 'Store 1', 'Stor...
<p>Use <code>DataFrame.replace</code> with the <code>regex=True</code> switch.</p> <pre><code>df = df.replace('\.+', np.nan, regex=True) df Cost Item Purchased Name Store 1 22.5 Sponge Chris Store 1 NaN Kitty Litter Kevyn Store 2 NaN Spoon Filip </code></pre> <p>The pattern <cod...
python|pandas|dataframe|nan|missing-data
5
6,290
68,230,315
Pandas: Replace blank field only with "Na" in a specific column mixed with float objects and blank strings
<p><strong>I have this dataframe:</strong></p> <pre><code> id cars rent sale 0 123 Kia 2 1 345 Bmw 1 4 2 Mercedes 1 3 345 Ford 1 4 Audi 2 1 </code></pre> <p>I want to fill the blank field only in <strong>the column id with &quot;...
<p>As your <code>id</code> column is mixed with float objects and blank fields, and assume you don't want to change the float objects to strings, you can use <code>.replace()</code> with regex, as follows:</p> <pre><code>df['id'] = df['id'].replace(r'^\s*$', 'Na', regex=True) </code></pre> <p><strong>Explanation:</stro...
python|pandas|dataframe
0
6,291
68,159,097
Python - move specific rows of columns in csv file
<p>I'm new to Python. I have no idea the way to move specific rows of columns in csv file.</p> <p>As shown in the picture below, I would like to move columns B and C to the right (column D) where column D does not have value.</p> <p>Thanks a lot.</p> <p>desired outcome</p> <p><a href="https://i.stack.imgur.com/h2y1o.pn...
<p>I guess you only want remove rows without nil.<br /> so I write a simple example for this</p> <pre class="lang-py prettyprint-override"><code>#split Nil and None Nil df1 = data[data['D']=='Nil'] df2 = data[data['D']!='Nil'] #move None Nil rows df2['D'] = df2['C'] df2['C'] = df2['B'] df2['B'] = [&quot;&quot; for _ i...
python|pandas|csv
1
6,292
68,424,959
Speed up nested for loop with NumPy
<p>I'm trying to write a package about image processing with some numpy operations. I've observe that the operations inside the nested loop are costly and want to speed it up.</p> <p>Input is an 512 by 1024 image and be preprocessing into a edge set, which is a list of (Ni,2) ndarrays for each array i.</p> <p>And next,...
<p>The question is quite broad so I'll only give a few non-obvious tips based on my own experience.</p> <ul> <li>If you use Cython, you might want to change the <code>for</code> loops into <code>while</code> loops. I've managed to get quite big (x5) speed-ups just from this, although it may not help for all possible ca...
python|image|numpy|loops|nested-loops
0
6,293
68,165,821
Changing size of scatter plot points by value
<p>I am trying to make a scatter plot and scale the size of points on the basis of numbers from a different list.</p> <p>So I am making a scatter plot of <code>y</code> vs <code>x</code> but the size of each point will depend on the corresponding number from <code>s</code>. Essentially, the larger the value of the elem...
<p>You are so close</p> <pre><code>ax.scatter(x, y, s=s) </code></pre>
python|numpy|matplotlib
1
6,294
59,076,750
how to convert code older version of tensorflow into tensorflow 2.0
<p>how can i convert my older version of tensorflow code to newer version as CNN ,RNN ,CTC is not working in newer version. I updated tensorflow thereafter many of the function stop working properly and shows error. Some of the function are not in the package anymore. I dont have idea about how to convert it into new ...
<p>You can run tf1 code in tf2 by importing tf a bit differently:</p> <pre><code>import tensorflow.compat.v1 as tf tf.disable_v2_behavior() </code></pre> <p>For details on how to migrate your code you should look here: <a href="https://www.tensorflow.org/guide/migrate" rel="nofollow noreferrer">https://www.tensorflow...
python|tensorflow|machine-learning|keras|deep-learning
0
6,295
59,233,327
Creating Bin for timestamp column
<p>I am trying to create a proper bin for a timestamp interval column,</p> <p>using code such as </p> <pre><code>df['Bin'] = pd.cut(df['interval_length'], bins=pd.to_timedelta(['00:00:00','00:10:00','00:20:00','00:30:00','00:40:00','00:50:00','00:60:00'])) </code></pre> <p>The Resulting df looks like:</p> <pre><cod...
<p>In pandas <code>inf</code> for timedeltas not exist, so used maximal value. Also for include lowest values is used parameter <code>include_lowest=True</code> if want bins filled by timedeltas:</p> <pre><code>b = pd.to_timedelta(['00:00:00','00:10:00','00:20:00', '00:30:00','00:40:00', ...
python|python-3.x|pandas|data-science|bins
1
6,296
59,161,920
Python Pandas slicing with various datatypes
<p>I have a column in a dataframe with two data types, like this:</p> <pre><code>25 3037205 26 2019-09-04 19:54:57 27 2019-09-09 17:55:45 28 2019-09-16 21:40:36 29 3037206 30 2019-09-06 14:49:41 31 2019-09-11 17:17:11 32 3037207 33 2019-09-11 17:19:04 </co...
<p>Another approach:</p> <pre><code>s = pd.to_numeric(df['col1'], errors='coerce') df.assign(val=s.ffill().astype(int)).loc[s.isnull()] </code></pre> <p>Output:</p> <pre><code> col1 val 26 2019-09-04 19:54:57 3037205 27 2019-09-09 17:55:45 3037205 28 2019-09-16 21:40:36 3037205 30 2019-...
python|pandas|dataframe|datetime|slice
4
6,297
59,072,242
Python Logistic Regression error : "TypeError: issubclass() arg 2 must be a class or tuple of classes"
<p>I'm creating a multiclass classification model with 4 possible outcomes. it worked yesterday but today, I receive the error below. I'm not very familiar with Python so any help in regards to how to fix this is appreciated.</p> <pre><code>from sklearn.model_selection import train_test_split X_train, X_test, y_trai...
<p>Seems like your solver is causing the error. Try changing your solver:</p> <pre><code>solver = 'lbfgs' </code></pre>
python|scikit-learn|logistic-regression|sklearn-pandas
0
6,298
59,398,266
Can't see the impact of drop_duplicates when used for pandas dataframe
<p>I see no change after calling pandas.drop_duplicates() on the dataframe I'm working on in Python.</p> <pre><code>df = pd.read_excel('sample_data.xlsx', index_col=0) df.drop_duplicates() </code></pre> <p><a href="https://i.stack.imgur.com/pm4UJ.png" rel="nofollow noreferrer">This is the data I'm working on</a></p>
<p>There are two issues that I can see you are having with the code:</p> <ol> <li>You are not passing a subset. By default, in panda's <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer">documentation</a>, <code>drop_duplicates()</code> w...
python|pandas
1
6,299
59,097,688
how to delete nan values in pandas?
<p>How to delete NaN values in <code>pandas</code>? When I was to print the code to (.csv). The columns are irregular and filled with NaN values. </p> <pre><code>import pandas as pd egzersizler = [{'Hareket Adı': 'Smith Machine Shrug', 'Url': 'https://www.bodybuilding.com/exercises/smith-machine-shrug'}, {'Hareket A...
<p>Try this, it should fix you dataframe:</p> <pre><code>ndf = df ndf['Kas Grubu'] = ndf['Kas Grubu'].dropna().reset_index().drop(columns='index') ndf['Ekipmanlar'] = ndf['Ekipmanlar'].dropna().reset_index().drop(columns='index') ndf['Düzey'][54]="Level: Unknown" ndf['Düzey'] = ndf['Düzey'].dropna().reset_index().dr...
python|pandas
0