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
15,400
34,839,393
How this mixed scipy.sparse / numpy program should be handled
<p>I am currently trying to use numpy as well a scipy in order to handle sparse matrices, but, in the process of evaluating sparsity of a matrix, I had trouble, and I don't know how the following behaviour should be understood:</p> <pre><code>import numpy as np import scipy.sparse as sp a=sp.csc.csc_matrix(np.ones((3...
<p>The nonzero count is available as an attribute:</p> <pre><code>In [295]: a=sparse.csr_matrix(np.arange(9).reshape(3,3)) In [296]: a Out[296]: &lt;3x3 sparse matrix of type '&lt;class 'numpy.int32'&gt;' with 8 stored elements in Compressed Sparse Row format&gt; In [297]: a.nnz Out[297]: 8 </code></pre> <p>As W...
python|numpy|scipy|sparse-matrix
1
15,401
60,212,545
How to detect black shaped contour on photo with OpenCV-Python
<p>I am trying to detect black shape on photo like this. </p> <p><img src="https://i.stack.imgur.com/CN94O.jpg" alt="enter image description here"></p> <p>So far i have picture with shape but still on there is many lines and noise and from that i cannot use the findContours() because it's also mark the line. Can Yo...
<p>You're on the right track. After obtaining your binary image you need to perform <a href="https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html" rel="nofollow noreferrer">morphological operations</a> to filter out noise and isolate the object. ...
python|numpy|opencv|image-processing|computer-vision
3
15,402
65,374,914
ImageDataGenerator gives different result than cv2
<p>I have been trying to create a neural network architecture that recognizes traffic signs. I am using the German Traffic Signs dataset and is composed of 43 classes. First of all, if I get the data by using cv2 and stack them into an array, then DNN works perfectly! I get %99 accuracy and tiny loss.</p> <p><a href="h...
<p>Posting answer here from the comment section for the benefit of the community.</p> <p>The default parameter of <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator#flow_from_directory" rel="nofollow noreferrer">flow_from_directory</a> for shuffle will be set to <code>Tr...
python|tensorflow|image-processing|keras
0
15,403
65,426,594
Errors using pylab and numpy in Python 3.8.0
<p>I have installed the required modules, matplotlib, numpy, and pillow, but when I try to use pylab in Python 3.8.0 a long error message is displayed. Similar issues arise when trying to use other related modules such as numpy or matplotlib.</p> <pre><code>Traceback (most recent call last): File &quot;&lt;pyshell#0&...
<p>Try this:</p> <pre><code>pip uninstall numpy </code></pre> <p>and then:</p> <pre><code>pip install numpy==1.19.3 </code></pre> <p>A google search showed me that this error occurs when using python3.9 and <strong>numpy1.19.4</strong> So uninstalling numpy1.19.4 and installing <strong>1.19.3</strong> will work.</p> <...
python|numpy|matplotlib|module
1
15,404
49,936,594
convert alphanumeric value to date
<p>I get <code>a1523245800</code> value in the date field from my incoming data feed. I wish to know, how to convert this value into the date dtype? I have tried <code>pandas.to_datetime</code> but that does not seem to work. thankyou. </p> <p>here is my code</p> <pre><code>pd.to_datetime([`a1523245800`], errors='coe...
<p>Remove <code>a</code> by <code>str[1:]</code> for remove first char or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>str.extract</code></a> for get numeric part first and then <a href="http://pandas.pydata.org/pandas-docs/stable/generat...
python|pandas|numpy|datetime
2
15,405
50,141,501
How to enumerate groups within groups in pandas
<p>I have a DataFrame like this:</p> <pre><code> name visit foo 0 andrew BL a 1 andrew BL a 2 andrew BL b 3 andrew BL b 4 bob BL c 5 bob BL c 6 bob BL d 7 bob BL d 8 bob M12 e 9 bob M12 e 10 bob M12 f 11 bob M12 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow noreferrer"><code>factorize</code></a>:</p> <pre><code>df['enu...
python|pandas
3
15,406
50,024,699
Find 'strongest' type per column in CSV
<p>I need to scan a CSV by column and find the strongest data type per, then apply it to the entire column.</p> <p>For example, if I had a CSV that looked like so (yes I not there are no commas...):</p> <pre><code> + C1 + C2 + C3 + C4 R1 | i | s | i | f R2 | i | f | i | i R3 | i | i | s | f # i = int...
<p>An example DataFrame:</p> <pre><code>In [11]: df Out[11]: C1 C2 C3 C4 R1 1 a 6 8.0 R2 2 4. 7 9.0 R3 3 5 b 10.0 </code></pre> <p>I wouldn't try and be clever with any short-circuit evaluation. I'd just take the type of every entry:</p> <pre><code>In [12]: df_types = df.applymap(type) In...
python|python-3.x|pandas|csv
2
15,407
64,147,913
Pandas pivot table - mean value with condition
<p>I have this <code>pivot_table</code>:</p> <pre><code> sum mean pontos_num pontos_num clube opponent home_dummy Athlético-PR 263 1 29.35 1.834375 265 1 59.78 ...
<p>The column name for a multi-index column is a tuple, which you can call.</p> <p>To filter <code>home_dummy</code> on the index, you can use <code>.query()</code>:</p> <pre><code>df.query('home_dummy == 1')[('sum', 'pontos_num')].mean() </code></pre>
pandas
0
15,408
64,037,627
Correlation using scipy
<p>I have two variables, one called <code>polarity</code> and another called <code>sentiment</code>. I would like to see if exists a correlation between these two variables. <code>polarity</code> can take values from <code>0</code> to <code>1</code> (continuous); <code>sentiment</code> can take values <code>-1, 0</code...
<p>try as suggested in the comments to change all your dataframe columns to numeric dtypes:</p> <pre><code>df = df.astype(float) </code></pre> <p>before calling the pearsonr function.</p>
python|pandas|scipy|pearson-correlation
0
15,409
63,835,528
Filter a list of strings but the filter must appear at a certain place
<p>I have a python dataframe with a column populated with strings of the same length like <code>0302000C0AABGBG</code> , <code>0407020B0AAAGAG</code>, <code>040702040BGAAAC</code></p> <p>I want to filter to identify all values that contain 'AA' but it must be at position _________AA ____ i.e. do not include <code>04070...
<p>Append to your regex <code>\w{4}$</code> (requiring that four word characters occur at end of line) in <code>str.contains</code> call</p>
python|pandas|string
0
15,410
63,865,495
How to index column names from one df to another df series?
<p>I have 2 data frames, 1 with raw data (df) and the other with a template describing what's in which well. How to index column names 'A1' from df with templates column well_id 'A1' which is in series, to get to the sample name?</p> <p>This is how raw data is exported, so I'm trying not to make it without changing the...
<p>Say, you wish to aggregate all the sample names against each of the given values, you can first merge the dataframes and then do a <code>groupby</code> on <code>name</code>. Using this, you can calculate, for example, the mean against each name like this, which can be used to further plot it:</p> <pre><code>import p...
python|pandas|dataframe|multi-index
1
15,411
46,946,042
Python Pandas - Concatenating strings between columns
<p>I have two dataframes with two columns each:</p> <p>df1:</p> <pre><code> C1 C2 0 x a 1 y b 2 z c </code></pre> <p>df2:</p> <pre><code> C1 C2 0 q s 1 r u 2 t v </code></pre> <p>I want to make a third column that concatenates both columns. I want to make a third dataframe suc...
<p>You have many different methods for doing this, I took the fastest method from <a href="https://stackoverflow.com/questions/19377969/combine-two-columns-of-text-in-dataframe-in-pandas-python">the answers here</a> and tried out this exmaple, seems to work fine. </p> <p>I would think the only problem with your <code...
python|pandas
1
15,412
32,952,542
Querying Pandas DataFrame with column name that contains a space or using the drop method with a column name that contains a space
<p>I am looking to use <code>pandas</code> to drop rows based on the column name (contains a space) and the cell value. I have tried various ways to achieve this (drop and query methods) but it seems I'm failing due to the space in the name. Is there a way to query the data using the name that has a space in it or do I...
<p>If I understood correctly your issue, maybe you can just apply a filter like:</p> <pre><code>df = df[df['Sale Item'] != 'item1'] </code></pre> <p>which returns:</p> <pre><code> Date price Sale Item 1 2012-06-12 1610.02 item2 2 2012-06-13 1618.07 item3 3 2012-06-14 1624.40 item4 4 201...
python|pandas
8
15,413
38,639,577
Python: np.where with multiple condition
<p>I have df and I try create new column, where numbers from one column is some phrase. I use </p> <pre><code>df["Family"] = np.where(df["Qfamilystatus"] == 1, "Не замужем / Не женат", "Замужем / женат / живу в гражданском браке", "Разведен/ живем порознь", "Вдовец / вдова") </code></pre> <p>I mean <code>1 - Не замуж...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> function by <code>dictionary</code>.</p> <p>Sample:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Qfamilystatus':[1,2,3,4]}) print (df) Qfamilystatus 0 ...
python|numpy|pandas
3
15,414
63,103,298
Converting a pandas column of UTC time to seconds
<p>I have a pandas dataframe where one of the column <code>created_at</code> is an UTC object (I did <code>df.dtypes</code> to find the type). I need to convert it to numeric for all the rows.</p> <p>Following <a href="https://stackoverflow.com/questions/51112320/convert-pandas-dataframe-column-of-utc-time-string-to-fl...
<p>The following will convert a datetime object to the unix epoch:</p> <pre><code>epoch = pd.to_datetime('1970-01-01') date_in_seconds = round((date - epoch).total_seconds()) </code></pre> <p>Where &quot;date&quot; is a datetime object you want to convert</p>
python|pandas
2
15,415
63,068,088
How to set the values under column value condition in pandas
<p>Here is my dataframe</p> <pre><code> col1 col2 0 1.0 5.0 1 2.0 6.0 2 NaN 7.0 3 3.0 8.0 </code></pre> <p>I want to add the column('col3') which has the value col1 or col2 as value condition. Col3 value is same to col1 but except if col1 value is 'NaN' then col3 value is set to col2.</p> ...
<p><code>pandas</code> has a builtin function for that: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.combine_first.html" rel="nofollow noreferrer"><code>combine_first</code></a></p> <pre><code>df[&quot;col3&quot;] = df[&quot;col1&quot;].combine_first(df[&quot;col2&quot;]) </code></p...
pandas
1
15,416
63,138,545
Pandas python help - can't seem to get the code to do what I need it to
<p><a href="https://i.stack.imgur.com/yBPlt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yBPlt.jpg" alt="enter image description here" /></a>I have to write a script to read a csv file and drop columns with a '.' and read strings False and True as 0 and 1. I have been able to code the drop columns...
<p>The best way to achieve both tasks is to mask the columns according to the properties you want.</p> <p>For the first part, assuming <code>data</code> is your DataFrame, you can mask out (using <code>~</code>) the columns containing a dot:</p> <pre><code>data = data[~data.columns.str.contains(&quot;\.&quot;)] </code>...
python|python-3.x|pandas|pycharm|pandas-datareader
0
15,417
32,053,539
Creating Temporary Table on Netezza from Pandas DataFrame
<p>I am looking to change over my workflow from SAS to Python, and have been prety successful thus far except for one pretty big thing. I cannot figure out how to upload Pandas DataFrames to my company's Netezza for use in later queries. This is actually pretty important as we have many datasets that we upload and us...
<p><a href="https://github.com/IBM/nzalchemy" rel="nofollow noreferrer">nzalchemy</a> can help here.</p> <ul> <li>Install sqlalchemy using <code>pip install sqlalchemy</code></li> <li><a href="https://github.com/IBM/nzalchemy#prerequisites" rel="nofollow noreferrer">Install nzalchemy</a></li> <li>For linux systems inst...
python|sql|pandas|odbc|netezza
1
15,418
32,030,343
subtracting the mean of each row in numpy with broadcasting
<p>I try to subtract the mean of each row of a matrix in numpy using broadcasting but I get an error. Any idea why?</p> <p>Here is the code:</p> <pre><code>from numpy import * X = random.rand(5, 10) Y = X - X.mean(axis = 1) </code></pre> <p>Error:</p> <pre><code>ValueError: operands could not be broadcast together ...
<p>The <code>mean</code> method is a <em>reduction</em> operation, meaning it converts a 1-d collection of numbers to a single number. When you apply a reduction to an n-dimensional array along an axis, numpy collapses that dimension to the reduced value, resulting in an (n-1)-dimensional array. In your case, since <...
python|numpy
49
15,419
41,549,784
Can TensorFlow RNNCell have more dimensions than 3D?
<p>I'd like to use <code>tf.nn.rnn</code> with 5D tensors of video frames (samples, time, height, width, channels) without having to flatten and reshape on each <code>cell.__call__</code>. Is this possible?</p>
<p>As of TensorFlow 1.2 this will be supported. It's also possible already by setting <code>time_major=True</code> and reordering the dims accordingly outside of the <code>tf.nn.rnn</code> call.</p>
tensorflow
0
15,420
41,298,243
cnn using tensorflow for own image set - what should be the tfrecord format
<p>I have an image data set of size 600 x 400 each and I have converted each of the images to TFRecord format. But I am unable to figure out how to use this data? I have seen the imagenet dataset and found only one single binary file (when extracted it form<a href="http://download.tensorflow.org/models/image/imagenet/i...
<p>Tensorflow doesnt look for single tfrecord file. So feel free and point your "data directory" and "train directory" to the location which has set of tfrecord files.</p> <p>Also, keep in mind files should be in respective directories based on their names like TRAIN-*.tfrecord files in "train directory".</p> <p>Answ...
tensorflow|neural-network
0
15,421
41,306,483
ValueError when performing integration in Numpy
<p>I am receiving a <code>ValueError</code> which I cannot decifer. I am tryig to perform a simple integration task, using the <code>integrate.quad</code> on a <code>lambda</code> function. Here is the code:</p> <pre><code>import numpy as np p = np.arange(0,1,1/1000) x = 0 y = 1 z = 0.9 pdfl = lambda p: 2*(p-x)/((y-x)...
<p>This error, as you can see from the side bar questions, is the result of using an array in a context that expects a scalar True/False.</p> <p>My guess is the <code>quad</code> is testing the bounds, <code>pp</code> against <code>inf</code>. It works fine when you give it one bounds, e.g. <code>0.5</code>, but prod...
python|python-3.x|numpy|lambda|integration
2
15,422
68,686,639
What does np.expand_dims(X_val, -1) peform? Don't understand the significance of -1
<p>I have a numpy array with dimensions (100,50,20). I understand what np.expand_dims(X_val, axis=0) does but cant wrap my head around the -1.</p>
<p>It is just like np.newaxis, directly np.newaxis should be faster as it is skip all intermidiate steps.</p> <p>I took a quick look at code base and for axis=-1. I will explain below.</p> <p><strong>How expand_dim works inside</strong></p> <ul> <li>There are other checks and validations inside, I am skipping for simpl...
python|numpy|numpy-ndarray
2
15,423
36,461,885
Error installing tables via pip
<p>I'm tying to install tables as follows (I have no sudo permissions):</p> <pre><code>pip install --user tables </code></pre> <p>And I get the following error:</p> <pre><code>Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-pWg1M_/tables/setup.py';exec(compile(getattr(tokenize, 'open...
<p>You can check the log pip has mentioned at /home/hudson/pg/fkgm22/.pip/pip.log to see what went wrong. I guess you will get a much more detailed error message which you can try to analyse.</p>
python|pandas|pip|pytables
0
15,424
52,952,067
Different results before and after OneHotEncoder
<p>I encoded y vector using OneHotEncoder, run my neural network and got output. Here <code>a</code> represents my y vector, and <code>b</code> stands for prediction result</p> <pre><code>a = np.array([[0., 0., 1., 0.], [0., 0., 1., 0.], [0., 0., 1., 0.], [0., 0., 1., 0.], [0., 0., 1., 0.],...
<p>Your issue comes from the fact that <code>a!=b</code> returns an array of arrays, checking whether the elements at each index are different. The first returns an array of arrays where the first value is <code>[False False True True]</code>, meaning that for the first items in <code>a</code> and <code>b</code>, the...
python|numpy
2
15,425
53,330,491
What does the nrows argument for from_records() do in pandas?
<p>I am trying to learn how to submit a Pull-Request to an open-source project. So I chose the <a href="https://github.com/pandas-dev/pandas/issues/23445" rel="nofollow noreferrer">issue #23455</a> from pandas-dev. It is a simple documentation error. However I realized that I have no idea what the nrows actually does i...
<p><code>nrows</code> is a parameter used to select the first n elements of a record. If you see the code it currently only works on an iterator. There might be some reason why only on an iterator which I currently dont know. </p> <p>An example to show the use case of nrows is to convert the sales data to an iterator....
python|pandas|dataframe|open-source
1
15,426
65,817,843
How to create new rows with missing years and populate them with current rows
<p>I have a dataset that looks like this:</p> <pre><code>overflow_data={'state': ['CA', 'CA', 'HI', 'HI', 'HI', 'NY', 'NY'], 'year': [2010, 2013, 2010, 2012, 2016, 2009, 2013], 'value': [1, 3, 1, 2, 3, 2, 5]} pd.DataFrame(overflow_data) </code></pre> <p>Starting DataFrame:</p> <p><a href="https://i.stack.imgur.com/Z...
<p>I think you are looking for <code>pivot</code> and fill:</p> <pre><code>(df.pivot('year','state','value') # you can print this line alone to see what it does .ffill().bfill() # fill missing the data based on the states .unstack() # transform back to original form .res...
python|pandas
4
15,427
65,786,842
XML Python parser - looping nested node
<p>With a help of community I got XML parser to panda's dataframe. I noticed that there is one issue to tackle. In below data sample there is a scenario where one <code>dept</code> has 1+ owners.</p> <p>Current loop pulls the latest one, I need every node from <code>owners</code></p> <p>Data:</p> <pre><code>&lt;?xml ve...
<p>Issue has been resolved in previous subject (<a href="https://stackoverflow.com/questions/65755193">Loop through XML in Python</a>)</p> <p>Solution:</p> <pre><code>import xml.etree.ElementTree as ET import pandas as pd root = ET.fromstring(xml) ns = {'ns0': 'http://SOMELINK'} pd.DataFrame([{**{f&quot;{d.tag.split('...
python|xml|pandas|parsing|xml-parsing
0
15,428
21,193,145
Filtering of structured array via bit-wise operation (bitmask) on column data
<p>I have a structured array. One column (<code>event_type</code>) is a bitfield. I would like to filter the data via the <code>event_type</code>.</p> <p>Previously I used <code>filter()</code> but it produces a <code>list</code> that would need to be back converted into an array, and I would need to preserve <code>dt...
<p>I think you can merge the two lines into:</p> <pre><code>mask = (data['event_type'] &amp; event_type).astype(bool) </code></pre>
python|arrays|python-3.x|numpy
0
15,429
2,678,425
Fitting Gaussian KDE in numpy/scipy in Python
<p>I am fitting a Gaussian kernel density estimator to a variable that is the difference of two vectors, called "diff", as follows: gaussian_kde_covfact(diff, smoothing_param) -- where gaussian_kde_covfact is defined as:</p> <pre><code>class gaussian_kde_covfact(stats.gaussian_kde): def __init__(self, dataset, cov...
<p>A density peaked whose mass is at one point is not Gaussian, so strictly speaking, what you want to do is undefined (and such distribution does not have a finite covariance).</p> <p>Now, in your case, for a vector which is all zero, you could special-case it, bypassing the whole infrastructure. A simple way to dete...
python|statistics|numpy|scipy|probability
2
15,430
63,585,062
How do I drop * values in a data frame in pandas?
<p>I am working with a data frame in pandas and some of the values in a certain column have <code>*</code> values. When I try to run a visual on that column using Seaborn I get the following error:</p> <blockquote> <p>ValueError: could not convert string to float: '*'</p> </blockquote> <p>I know what columns have <code...
<p>You can do to following. In my example, I will have the data frame <code>df</code> with two columns <code>y</code> and <code>z</code> which might potentially have a <code>*</code> in them.</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'x': [1, 2, 3, 4], 'y': [1, 4, '*', 16], 'z': [2, 3, 5, '*']...
python|pandas|seaborn
0
15,431
63,686,361
How to iterate over a column in panda and populate on another column
<p>I have two columns in df, Start_time and hours_extracted</p> <pre><code>from datetime import datetime for i in df['Start_time']: x =(i.hour)*3600 y= (i.minute)*60 z= (i.second) k=x+y+z print (x,y,z, k) df['hours_extracted']= k df.head() </code></pre> <p>its just using one value of k to ...
<p>If you want to fix your code then you have to use</p> <pre><code>for l, i in enumerate(df['Start_time']): x =(i.hour)*3600 y= (i.minute)*60 z= (i.second) k=x+y+z df.loc[l, 'hours_extracted']= k </code></pre> <p>But a better way is</p> <pre><code>df['hours_extracted'] = df['Start_time'].apply...
python|pandas
2
15,432
63,601,323
What does zero-indexed mean in context of axis in numpy arrays?
<p>I was studying concatenation of numpy arrays, where I encountered this code snippet:</p> <pre><code># concatenate along the second axis (zero-indexed) np.concatenate([grid, grid], axis=1) </code></pre> <p>What does the term zero-indexed mean in this context?</p> <p>Maybe this screenshot may help you understand my pr...
<p>Python uses zero-based indexing. That means, the first element(value 'red') has an index 0, the second(value 'green') has index 1, and so on. Since you are concatenating its relevant as the array starts with 0 index</p>
python|numpy
1
15,433
53,382,585
How to calculate correlation matrix from pandas containing tabulated data
<p>Here is my input file:</p> <pre><code>inputfile_pd=pd.DataFrame([['2018-02-02',10, 2], ['2018-02-02',1, 3], ['2018-02-02',3, 4], ['2018-02-03',3, 2], ['2018-02-03',2, 3], ['2018-02-03',4, 4], ['2018-02-04',4, 3],['2018-02-04',1, 4]], columns=['DateOfSale','Sales','Client_id']) </code></pre> <p>therefore it looks ...
<p>something like this?</p> <pre><code>inputfile_pd.pivot('DateOfSale','Client_id').corr() Sales Client_id 2 3 4 Client_id Sales 2 1.0 -1.000000 -1.000000 3 -1.0 1.000000 -0.785714 4 ...
python|pandas|matrix|correlation
0
15,434
53,435,626
Who can helpme? PANDAS and MySql
<p>I need help. I´m new programming in python.</p> <p>My code is:</p> <pre><code>import redis import json import pandas as pd import numpy as np import matplotlib.pyplot as plt import time import mysql.connector mydb = mysql.connector.connect( host="XXXXXXXXXXXXXXXX", user="XXXXXXXXXXX", passwd="XXXXXXX" ) df ...
<p>You should specify value by using <code>df.loc[row,col]</code>.</p> <blockquote> <p>con : sqlalchemy.engine.Engine or sqlite3.Connection <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="nofollow noreferrer">doc</a> # you got error because of incorrect connection ...
python|mysql|pandas
1
15,435
19,942,995
python cross section curve fitting
<p>I have a set of points describing a cross section of a simple surface cavity/bulge. Polynomial approximation would be enough, but <em>numpy.polyfit</em> needs a certain degree. I thought of several iterations with different degrees to chose one with the smallest mean residual. Is there any existing function for this...
<p>Unless I'm mistaken, you'll always get the smallest residual with the largest degree allowed. If you allow the degree <code>d</code> to be chosen by the optimizer, it will choose infinitely large <code>d</code>, though in practice it will stop when <code>d = dof</code> where <code>dof</code> is the number of degrees...
python|numpy|scipy|curve-fitting
2
15,436
71,837,792
how to recognize columns numeric and categorical in pandas using pandas profiling . only need dtype code not Analysis code of pandas profiling
<p>I only need code to recognize the dtype of columns as done in pandas profiling (numeric and categorical) could you please extract only that code for me from pandas profiling package code.</p> <p>series = series.fillna(np.nan)</p> <pre><code># get `infer_dtypes` (bool) from config if config.infer_dtypes: # Infer ...
<p>According to <a href="https://pandas-profiling.ydata.ai/docs/master/index.html" rel="nofollow noreferrer">Pandas Profiling documentation</a> the dtype of variables are inferred using Visions library Try this sample for columns type recognition:</p> <pre><code>from visions.functional import infer_type from visions.t...
python|python-3.x|pandas|pycharm|pandas-profiling
0
15,437
71,896,443
Filter Data with Pandas in Pycharm
<p>This is my code so far in Pycharm for my Streamlit Data app:</p> <pre><code>import pandas as pd import plotly.express as px import streamlit as st st.set_page_config(page_title='Matching Application Number', layout='wide') df = pd.read_csv('Analysis_1.csv') st.sidebar.header(&quot;Filter Data:&...
<p>The .isin() function is useful for creating a vector of Bools on which to filter the rows of your DataFrame. For filtering categorical columns, as in your example, it's the simplest way to go. Documentation <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.isin.html" rel="nofollow noreferrer">he...
python|pandas
2
15,438
71,838,858
Connecting two Columns with list Elements for Pivot in Pandas
<p>I have two columns (keys, values) which I want to pivot with pandas.</p> <p>After importing, my dataset looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;"></th> <th style="text-align: left;">Work Center</th> <th style="text-align: left;">key</th> ...
<p>First you can <code>split</code> on <code>key</code> and <code>value</code> columns and <code>explode</code> them to rows</p> <pre class="lang-py prettyprint-override"><code>df_ = (df .set_index(['Work Center']) .apply(pd.Series.explode).reset_index() .replace('', pd.NA) .dropna(subset=['key']) ) </code>...
python|pandas
0
15,439
56,593,684
Exporting dataframe with xlwings without having a index column
<p>I have following code: </p> <pre><code>import xlwings as xw wb = xw.Book('Test.xlsx') sht1 = wb.sheets['Testsheet'] sht1.range('A8').value = df1 </code></pre> <p>I have want to export my df1 but without column1 (index column). how do i do this?</p> <p>Right now it looks like this:</p> <pre><code>Column1 A B C <...
<p>You can set this via options:</p> <pre><code>import xlwings as xw import pandas as pd wb = xw.Book('Test.xlsx') sht1 = wb.sheets['Testsheet'] sht1.range('A8').options(pd.DataFrame, index=False).value = df1 </code></pre> <p>See the docs: <a href="http://docs.xlwings.org/en/stable/converters.html#pandas-dataframe-c...
python|pandas|dataframe|xlwings
2
15,440
56,669,487
How to implement a SVM model when the predicted values are pairs of indexes that match?
<p>I am trying to fit a SVM model where my predicted true values are multiindexes that match. The problem is that I dont know how to specify that the multiindixes are the true values.</p> <p>I cannot use the record linkage classification step because it is not very flexible. </p> <pre class="lang-py prettyprint-overr...
<p>You don't have to specify the <code>index</code>, instead use the generated boolean <code>Series</code> as the labels for the classification.</p> <p>Here's an example.</p> <pre class="lang-py prettyprint-override"><code># Sample data data = pd.DataFrame({'a': [1, 2, 3], 'b': [1, 1, 0]}) data...
python|pandas|scikit-learn|multi-index|record-linkage
0
15,441
56,717,783
How to associate ID from pandas dataframe of longlat points with second dataframe?
<p>I have a dataframe that contains the ID and coordinates of some points</p> <pre><code>df ID x y geometry 0 0 -73.847701 18.024993 POINT (-73.84770051912155 18.02499306784136) 1 1 -73.849600 18.025617 POINT (-73.84959983488658 18.02561663390971) 2 2 -73.860621 18.031506 ...
<p>I would first take the word POINT away:</p> <pre><code>df["geometry"] = df["geometry"].map(lambda x: x.str.split("POINT ")[1]) #Output ID x y geometry 0 0 -73.847701 18.024993 (-73.84770051912155 18.02499306784136) 1 1 -73.849600 18.025617 (-73.84959983488658 18.0256166339097...
python|pandas
0
15,442
56,586,806
Can't read time series data into a numpy array
<p>I have been trying to create a time series dataset from a .csv file.</p> <p>What I can't get around is that it has 2 time indexes: respectively the transaction date and the time, stored in two separate strings.</p> <p>When trying this:</p> <pre><code>Date, Time, Open,High,Low,Close,Volume = np.loadtxt('EURUSD.txt...
<p><em>Comments are easy, complete answers are what you are looking for here @Trebled.</em></p> <p>Anyways, as @hpaulj mentioned, <strong>a converter to appropriately parse the datetime columns is needed</strong> of your data. I usually do these kind of input/output operations using <a href="http://pandas.pydata.org/p...
python|python-3.x|numpy
0
15,443
56,708,521
Get similar rows in data frame that only changes 1 value or more per column
<p>My problem is the following: imagine you have a dataframe NxM filled with binary numbers: </p> <pre><code>pd.DataFrame([[0, 0, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 1, 0]] </code...
<p>You can shift the records. After shifting you can compare values to return True/False. After this you count the True Values. I set true==1 for the example so you have exactly 1 change between lines.</p> <p>I'm unsure exactly what your specific outcome is supposed to look like but maybe you can enhance this.</p> ...
python|python-3.x|pandas
0
15,444
56,810,511
Tensorflow.js: expandDims() + cast() issue
<p>I need to provide a <code>float32</code> tensor for my model. I need to use <code>expandDims(tensor, axis=0)</code> to change its shape from <code>[240, 320, 3]</code> to <code>[1, 240, 320, 3]</code>. However, it appears that the <code>expandDims()</code> operation casts my tensor to <code>int32</code>.</p> <p>Whe...
<p>Tfjs can't use JS operations on tensors, you have to use <code>tf.div()</code> and <code>tf.sub()</code>.</p> <blockquote> <p>image_v = (tf.cast(image_raw, "float32") / 255.0) - 0.5;</p> </blockquote> <p><code>image_v</code> is now <code>NaN</code>, because <code>({}/255)-0.5 === NaN</code> </p> <blockquote> ...
tensorflow|tensorflow.js
1
15,445
56,718,958
How can I access a numpy array column by name?
<p>I´ve this numpy array:</p> <pre><code>array([((-24560412, 18229, 62, 198, 201, 5, -1, 6, 1, 239176.42401979),), ..., ((-25883120, -681084, 2583, 278, 201, 5, 1, 255, 1, 239424.37447651),)], dtype=[('point', [('X', '&lt;i4'), ('Y', '&lt;i4'), ('Z', '&lt;i4'), ('intensity', '&lt;u2'), ('flag_byte', 'u1...
<p>you should be able to do:</p> <pre><code>array_name['point']['Z'] </code></pre>
python|numpy
1
15,446
67,112,621
Change x axis labelling Matplotlib?
<p>I would like to explicity pass a list with 0,1,2, etc. as x labels instead of what gets retunred by the value counts function. Any ideas how to do this?</p> <pre><code>df2 = idx_open.hour.value_counts(bins=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]).sort_index() df2.plot(kind='bar',color=['bl...
<p>you can try with the <code>xticks</code> option to make custom labels with this you can specify a list or set arranges. See here for documentation: <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xticks.html" rel="nofollow noreferrer">https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.x...
python|pandas|matplotlib
0
15,447
67,035,528
How to add rows from one dataframe to another dataframe one after another using pandas
<p>i have two dataframe like df1</p> <pre><code> time kw 0 13:00 30 1 13:02 28 2 13:04 29 </code></pre> <p>and df2</p> <pre><code> time kw 1 13:01 30 2 13:03 28 3 13:05 29 </code></pre> <p>i want to add rows from one dataframe to another for end result like</p> <pre><code> time kw ...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.append.html" rel="nofollow noreferrer"><code>df.append</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>df.sort_values</code></a>:</p> <pre>...
python|pandas|dataframe
1
15,448
47,264,403
Dump a pandas DataFrame which contains column name as "name" to mysql table
<p>I am trying to dump my crawled data to mysql using pandas and to_sql.</p> <p>I am approaching in two ways 1></p> <pre><code>{# -*- coding: utf-8 -*- import numpy as np import pandas as pd import MySQLdb from sqlalchemy import create_engine import os from pandas.io import sql import MySQLdb columns_list= ['persons...
<p>I think you have a typo there since you have written <code>df</code> inside the <code>to_sql</code> method, try: <code>df.to_sql(con=con, name='table_name',if_exists='replace',flavor='mysql')</code></p>
python|mysql|pandas|pandas-to-sql
1
15,449
68,236,800
How to use map function to compare and fill in dataframe?
<p>I have the json object like below:</p> <pre><code>lookup = [ { &quot;ID&quot;: &quot;70B52DA6-F099-4D01-BBD0-03EA97292C26&quot;, &quot;Type&quot;: &quot;A&quot; &quot;Name&quot;: &quot;Galaxy Puzzle&quot; }, { &quot;ID&quot;: &quot;442B1598-20CF-4425-8A28-0438FBF77C46&quot;, &quot;Type&quot...
<p>To <a href="https://stackoverflow.com/questions/28457149/how-to-map-a-function-using-multiple-columns-in-pandas">map a function using multiple columns</a> you may use <code>DataFrame.apply(,axis=1)</code></p> <pre><code>df = pd.DataFrame([[None, &quot;A&quot;, &quot;Galaxy Puzzle&quot;, &quot;TRUE&quot;], ...
python|json|pandas|dataframe|dictionary
1
15,450
68,202,331
How to find rows of a DataFrame that matches a given set of conditions for all columns?
<p>Given the following Pandas DataFrame, how can I get all the rows where <strong>only</strong> Test1 and Test2 failed? In my true dataset I have about 70 different tests and need an easy way to filter devices based on different tests they failed.</p> <pre><code>import pandas as pd data = [['SN-01', 'Fail', 'Pass', 'P...
<p>Here is one way:</p> <pre><code>cols = ['Test1','Test2'] d = df.set_index('Serial').eq('Pass') d[cols].sum(axis=1).eq(0) &amp; d.sum(axis=1).eq(len(d.columns)-len(cols)) </code></pre>
python|pandas|data-analysis
0
15,451
68,069,190
Nightmare of installing and running Tensorflow in R Studio on windows 10
<p>Please, I have been having trouble for weeks now trying to install and run tensorflow and keras in R Studio. I have tried everything I can find online to no avail. I have anaconda installed on my system, do I need to uninstall it? After running this line of code:</p> <pre><code>install_tensorflow(method = &quot;cond...
<p>there have been significant changes to the installation pathway in the R package recently. Can you please try the following (in a fresh R session):</p> <pre><code>install.packages(&quot;keras&quot;) reticulate::install_miniconda() keras::install_keras() </code></pre> <p>If the above doesn't work, can you please file...
python|r|windows|tensorflow
2
15,452
68,402,208
How to resolve IndexError and how to save 3 data computed in for loop to array/.csv?
<p>I imported a file using pandas. Data look as follows:</p> <p><img src="https://i.stack.imgur.com/7QPeV.png" alt="My data looks like this" /></p> <p>I coded to get the data of 'open' from first day of every year saved as start_open and last day of the year saved as end_open for 27 years. My code is as follows:</p> <p...
<p>I can't test it but error shows problem with <code>IndexError</code> in</p> <pre><code>start_open = sub_93.iloc[0]['open'] </code></pre> <p>so probably you get empty <code>sub_93</code> and it doesn't have <code>[0]</code> (and <code>[-1]</code>).</p> <p>You should check it and skip calculations</p> <pre><code> sub...
python|arrays|pandas|numpy|data-analysis
0
15,453
59,106,311
How to count the values corresponding to each unique value in another column in a dataframe?
<p>i have a table like this:</p> <pre><code>Car Type | Color | ID VW | Blue | 123 VW | Red | 567 VW | Black | 779 ----------------------- AUDI | Silver | 112 AUDI | Black | 356 AUDI | White | 224 </code></pre> <p>how can i get something like this? where each row contain...
<p>Use for number of unique values per groups use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFr...
python|pandas
3
15,454
59,191,701
Finding mean of specific column and keep all rows that have specific mean values
<p>I have this dataframe.</p> <pre><code>from pandas import DataFrame import pandas as pd df = pd.DataFrame({'name': ['A','D','M','T','B','C','D','E','A','L'], 'id': [1,1,1,2,2,3,3,3,3,5], 'rate': [3.5,4.5,2.0,5.0,4.0,1.5,2.0,2.0,1.0,5.0]}) &gt;&gt; df name id rate 0 A ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> for means by all groups with same size like original DataFrame, so possible filter by <a href="http://pandas.pydata.org/pandas-docs/stable/us...
python|pandas|dataframe|pandas-groupby|mean
3
15,455
59,288,733
Neural network versus random forest performance discrepancy
<p>I want to run some experiments with neural networks using PyTorch, so I tried a simple one as a warm-up exercise, and I cannot quite make sense of the results.</p> <p>The exercise attempts to predict the rating of 1000 TPTP problems from various statistics about the problems such as number of variables, maximum cla...
<p>can you please print the shape of your input ? I would say check those things first:</p> <ul> <li>that your target y have the shape <code>(-1, 1)</code> I don't know if pytorch throws an Error in this case. you can use <code>y.reshape(-1, 1)</code> if it isn't 2 dim</li> <li>your learning rate is high. usually when...
python|machine-learning|neural-network|pytorch|random-forest
4
15,456
59,320,625
Python not recognising duplicates
<p>A sample snapshot of first 5 rows of 2 data sets that I have Emp1 dataframe:</p> <pre><code>Name -------- John Matt Anish Dave Mike </code></pre> <p>Emp2 dataframe:</p> <pre><code>Name -------- Sue Matt Raj Dave Simon </code></pre> <p>I concatenated both (converting them to objects in the process just in case)</...
<p>There is possible some trailing whitespaces, so remove them:</p> <pre><code>df1['name'] = df1['name'].str.strip() df2['name'] = df2['name'].str.strip() </code></pre>
python|python-3.x|pandas|merge
2
15,457
59,312,265
How to compare a value in one dataframe to a column in another using fuzzywuzzy ratio
<p>I have a dataframe <code>df_sample</code> with 10 parsed addresses and am comparing it to another dataframe with hundreds of thousands of parsed address records <code>df</code>. Both <code>df_sample</code> and <code>df</code> share the exact same structure:</p> <pre><code>zip_code city state street_n...
<p>I'm not familiar with <code>fuzzy</code>, so this is more of a comment than an answer. That said, you can do something like this:</p> <pre><code># cross join df_merge = pd.merge(*[d.assign(dummy=1) for d in (df, df_sample)], on='dummy', how='left' ) filters = pd.DataFrame() ...
python|pandas|dataframe|match|fuzzywuzzy
2
15,458
59,277,077
`import pandas` with an error of `ModuleNotFoundError: No module named 'pandas.msgpack'`
<p>I always could run this code:</p> <pre><code>import pandas as pd </code></pre> <p>But I can't now, for some reason it raises:</p> <pre><code>&gt;&gt;&gt; import pandas as pd Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import pandas as pd File "C:\Users\rep\Anacon...
<p>Just for future readers, I solved it long ago by copying <code>pandas</code> from the environment to outside the environment, surely I accidentally modified pandas outside the environment.</p> <p>Everything works as fine now. I am pretty sure I accidentally moved <code>msgpack</code> under <code>io</code>.</p>
python|pandas|import
0
15,459
14,006,741
Python NumPy doesn't resize correctly
<p>Why is this code not working? I can't get this numpy array to resize correctly.</p> <pre><code>import numpy a = numpy.zeros((10,10)) a[3,2] = 8 a.resize((5,5)) if a[3,2] == 8: print "yay" else: print "not working" raw_input() </code></pre>
<p>From the docs [<code>help(a.resize)</code>]:</p> <pre><code>Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped: &gt;&gt;&gt; a = np.array([[0, 1], [2, 3]], order='C') &gt;&gt;&gt; a.resize((2, 1)) &gt;&gt;&gt; a array([[0], [1]]) </code></pre> <p...
python|arrays|numpy|resize
6
15,460
13,983,498
Visually separating bar chart clusters in pandas
<p>This is more of a hack that almost works.</p> <pre><code>#!/usr/bin/env python from pandas import * import matplotlib.pyplot as plt from numpy import zeros # Create original dataframe df = DataFrame(np.random.rand(5,4), index=['art','mcf','mesa','perl','gcc'], columns=['pol1','pol2','pol3'...
<p>Still pretty hacky, but it works:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np # Create original dataframe df = pd.DataFrame(np.random.rand(5,4), index=['art','mcf','mesa','perl','gcc'], columns=['pol1','pol2','pol3','pol4']) # Estimate average avera...
python|matplotlib|plot|pandas
3
15,461
44,952,929
Same prediction for each inference
<p>I saved a tensorflow model using <code>tf.saved_model.builder.SavedModelBuilder</code>. However, when I try to make predictions in java, <strong>in most of the time</strong> it returns the same results (for fc8 (alexnet) the layer before softmax) in some cases, it produces some real different results and it's most l...
<p>I am assuming that there is no random operation left in your graph, such as dropout. (Seems to be the case, since you often get the same results).</p> <p>Alas, <a href="https://github.com/tensorflow/tensorflow/issues/3103" rel="nofollow noreferrer">some operations in tensorflow seem to be non-deterministic</a>, suc...
java|tensorflow
1
15,462
44,932,910
Seaborn plot per column in a pandas dataframe?
<p>I have a little dataframe that looks somewhat like this:</p> <pre><code>csv = [{"Oranges" : 12, "Apples" : 4, "Kiwis" : "Yes"}, {"Oranges" : 1, "Apples" : 8, "Kiwis" : "No"}, {"Oranges" : 1, "Apples" : 14, "Kiwis" : "Yes"}, {"Oranges" : 11, "Apples" : 3, "Kiwis" : "No"}, ] df = pd.DataFrame(csv) </code></pre> <p>O...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.difference.html" rel="nofollow noreferrer"><code>difference</code></a> for column <code>Kiwis</code> and then use <code>apply</code> with selecting columns by subset <code>[]</code>:</p> <pre><code>import matplotlib.pyplot as pl...
python-3.x|pandas|foreach|seaborn
1
15,463
45,206,561
PyTorch RuntimeError : Gradients are not CUDA tensors
<p> I am getting the following error while doing seq to seq on characters and feeding to LSTM, and decoding to words using attention. The forward propagation is fine but while computing loss.backward() I am getting the following error.</p> <blockquote> <p>RuntimeError: Gradients aren't CUDA tensors</p> </blockquote>...
<p>Make sure that all the objects that inherit <code>nn.Module</code> also call their <code>.cuda()</code>. Make sure to call before you pass any tensor to them. (essentially before training)</p> <p>For example, (and I am guessing your <code>encoder</code> and <code>decoder</code> are such objects), do this right befor...
pytorch
1
15,464
45,012,534
What is an epoch and how is related to steps and batch_size?
<p>I have looked through other solution to the similar questions but none gave a complete explanation. For my understanding, the epoch is a test round in which the test-set divided in 'm' batch_size goes under 'n' steps. And in this case, no of epochs will be the size(data-set)/m.</p> <p>Ok, but what if the batch_size...
<p>Commonly, those terms are interpreted as such:</p> <p><strong>Epoch</strong>: A full pass over your dataset. In the evaluation case, typically you'll go though your test set once (thus, for one epoch). In training, however, it's common to train the estimator on the same dataset multiple times (and thus having a num...
python|tensorflow
1
15,465
45,222,582
MATLAB use of bracket, semicolon and single quotes with matrix
<p>I have this piece of code in MATLAB:</p> <pre><code>scaling = 1; rho = scaling * (0:1 / (int_len / 2):1); rho = [rho'; rho(end - 1:-1:2)']; </code></pre> <p>and actually I have to translate it to Python. I don't know MATLAB and I couldn't figure out what this code is doing. The value of int_len in this case is not...
<p>Your interpretation of the second line is correct. In the third line, the 1-by-N row vector <code>rho</code> is first transposed with <code>'</code>(<strong>note:</strong> this should really be <a href="https://www.mathworks.com/help/matlab/ref/transpose.html" rel="nofollow noreferrer"><code>.'</code></a>) to create...
python|matlab|numpy|matrix
2
15,466
45,204,915
Adding up observations with similar index and x-values
<p>I have a dataset which has date time data as the index, and a few variables, but only two are relevant here - 'price' and 'quantity'. <a href="https://i.stack.imgur.com/qaZfT.png" rel="nofollow noreferrer">link to screenshot of data</a></p> <p>So what I am trying to achieve here is to merge the highlighted observat...
<p>Assume the dataset is a list fill with <code>NamedTuple</code>s. You can use groupby from itertools to filter by datetime and price.</p> <pre><code>from itertools import groupby after_merge = [] for _, group in groupby(dataset, key=lambda item: (item["datetime"], item["price"]): quantity = sum(item["quantity...
python|pandas
0
15,467
57,077,138
pandas get multiple groupby results into the same table
<p>I have the following <code>df</code>,</p> <pre><code>ccode year_month user tcode 10 201903 WF MI 10 201903 WF MI 10 201903 QQ MI 10 201903 QQ MI 20 201904 BATCH MI 20 201904 WF MI 20 201904 ...
<p>You've done all the hard work. It's a relatively simple <code>merge</code> from here:</p> <pre class="lang-py prettyprint-override"><code>(inv_tran_user_ccode_ym_gr_df.drop('count', axis=1) .merge(inv_tran_user_ym_gr_df.drop('count', axis=1), on=['year_...
python|pandas|dataframe|pandas-groupby
3
15,468
57,024,183
selecting data from list whiles keeping the order
<p>trying to select subset from a list, however the order is reversed after selection</p> <p>tried using pandas isin </p> <pre><code>df.mon =[1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,...] # selecting results = df[df.month.isin([10,11,12,1,2,3])] print(results.mon] mon = [1,2,3,10,11,12, 1,2,3,10,11...
<p>In your case , we using <code>Categorical</code> + <code>cumcount</code> </p> <pre><code>#results = df[df.mon.isin([10, 11, 12, 1, 2, 3])].copy() results.mon=pd.Categorical(results.mon,[10,11,12,1,2,3]) s=results.sort_values('mon') s=s.iloc[s.groupby('mon').cumcount().argsort()] s Out[172]: mon 9 10 10 11 11...
python|pandas|numpy|python-xarray
1
15,469
57,190,148
Pandas Python user input an attribute for dataframe object
<p>I'm trying to allow the user to input the attribute for the dataframe object. </p> <p>I've tried changing my input into a string. I've also tried using my input saved to a variable. Both these options do not work.</p> <pre><code>data = pd.read_csv('2019FallEnrollees.csv') input1_col = input("Enter comparison grou...
<p>Welcome! To access a column in pandas you cannot use <code>data.column</code> Try <code>data[column]</code> or in your case <code>test[input1_col]</code> Before you do so, make sure the column does exist and the user is not inputting a nonexistant column.</p> <p>Sometimes the column name can be an integer and conve...
python|pandas
0
15,470
57,049,232
How to add non-zero elements to noise?
<p>I have a numpy array and a noise function.</p> <pre><code>def gaussian_noise(X,sigma=0.1): noise = np.random.normal(0, sigma, X.shape) return X + noise </code></pre> <p><strong>How to add some noise to non zero element?</strong> For example:</p> <pre><code># input an array a = array([[1, 0, 3], ...
<p>Simple selection problem</p> <pre><code>def gaussian_noise(X,sigma=0.1): X = np.array(X, dtype=np.float) M = X!=0 noise = np.random.normal(0, sigma, X.shape) X[M] += noise[M] return X </code></pre> <p>will do</p>
python|numpy
0
15,471
45,784,494
Adding series to pandas dataframe
<p>I have a dataframe p_md. The index is a DateTime. I want to make a new column called Finish where if the index is before 5PM of that day, the column value is 11PM of that day. Otherwise if it is after 5PM, the Finish column value is 11PM of the NEXT day.</p> <p>What I have so far:</p> <pre><code>p_md["Finish"] = p...
<p>If I understand you correctly, I would create the "Finish" as:</p> <pre><code>p_md["Finish"] = p_md.index </code></pre> <p>Then, I would use the series apply (<a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/st...
python|pandas|dataframe|indexing
0
15,472
23,354,124
How can I "unpivot" specific columns from a pandas DataFrame?
<p>I have a pandas DataFrame, eg:</p> <pre><code>x = DataFrame.from_dict({'farm' : ['A','B','A','B'], 'fruit':['apple','apple','pear','pear'], '2014':[10,12,6,8], '2015':[11,13,7,9]}) </code></pre> <p>ie:</p> <pre><code> 2014 2015 farm ...
<p>This can be done with <code>pd.melt()</code>:</p> <pre><code># value_name is 'value' by default, but setting it here to make it clear pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value') </code></pre> <p>Result:</p> <pre><code> farm fruit year value 0 A apple 2014 10 1 B app...
python|pandas|pivot-table
44
15,473
35,612,918
Create pandas DataFrame iteratively
<p>I am creating the list as follows:</p> <pre><code>myList = [] for i in range(0,10): val0 = 1 # some formula for obtaining values val1 = 2.5 val2 = 1.8 myList.append([val0,val1,val2]) </code></pre> <p>How can I do the same loop for pandas DataFrame (i.e. <code>myList</code> must be a <code>DataFram...
<p>Ideally you want to create your <code>DataFrame</code> once you have all the data in place. Slightly modifying your example:</p> <pre><code>my_df = [] for i in range(0,10): d = { 'val0' : 1, # some formula for obtaining values 'val1' : 2.5, 'val2' : 1.8 } my_df.append(d) my_df...
python|pandas|dataframe
17
15,474
11,729,851
Function to slice indices in Numpy
<p>I have two index arrays and I want to return all the indices in between, like a slice function, manually it would look like this:</p> <pre><code>ind1 = np.array([2,6]) ind2 = np.array([2,3]) final = np.array([[2,2,2], [4,5,6]]) </code></pre> <p>Since the axis along which to slice is not fixed, I came up with this...
<p>I don't have it in a one liner, but something like the following will reproduce the results you seem to be asking for:</p> <pre><code>def index_slice(arr1, arr2): lens = np.abs(arr1 - arr2) if not all((lens == max(lens)) | (lens == 0)): raise ValueError('The number of indices in some dimensions were...
python|numpy|indexing
0
15,475
28,636,599
Pythonic Way to Solve this Matrix
<p>I've been thinking on this problem, but I can't seem to wrap my head around it.</p> <p>I want to solve a matrix with three equations with unknowns x, y, z so they all equal the same number.</p> <p>Lets say my equations are:</p> <pre><code>x + 3 = A y(2y - 2) = 2A z(4z - 1) = A </code></pre> <p>So I can construct...
<p>You do not have a system of 3 equations with 3 unknowns. You have a system of 3 equations with 4 unknowns: x, y, z and A.</p> <p>That means your answer will be parameterized on A, because you do not have enough equations to solve for all unknowns.</p> <p>Solving a general <a href="http://en.wikipedia.org/wiki/Sys...
python|numpy|matrix|linear-algebra
3
15,476
51,041,109
Numpy 1.11 doesn't install in virtualenv @ Ubuntu Studio
<p>I have Python 3 virtualenv set up @ 4.15.0-23-lowlatency #25-Ubuntu.<br /> Inside virtualenv I have numpy1.14 installed. I want to install numpy1.11.<br /> I get the error:</p> <pre><code>numpy/core/src/multiarray/numpyos.c:18:10: fatal error: xlocale.h: No such file or directory #include &lt;xlocale.h&gt; ...
<p>There exists pre-built binary package for your platform, you should be able install it via <code>wheel</code>:</p> <pre class="lang-sh prettyprint-override"><code>pip install wheel pip install numpy==1.11.* </code></pre> <p>If you have some reasons to build the package from source instead, according to <a href="ht...
python-3.x|numpy|ubuntu|pip|virtualenv
5
15,477
33,250,037
Pandas DF: Replace Middle Part of String
<p>Given the following DataFrame:</p> <pre><code>import pandas as pd DF = pd.DataFrame({'LastFirst':['Last , First','Last , First','Last , First', 'Last , First','Last , First','Last , First','Last , First']}) DF LastFirst 0 Last , First 1 Last , First 2 Last , First 3 Last , First 4 Last , First 5 Las...
<p>You could just do</p> <pre><code>DF.LastFirst = DF.LastFirst.str.replace(' ,', ',') </code></pre>
python|string|pandas
3
15,478
33,142,919
How to compare values in pandas between two different columns?
<p>My Table:</p> <pre><code>A Country Code1 Code2 626349 US 640AD1237 407223 702747 NaN IO1062123 407255 824316 US NaN NaN 712947 US 00220221 870262123 278147 Canada 721AC31234 109123 278144 ...
<p>This will give you a 'is_correct' boolean column:</p> <pre><code>code_lengths = {'US':9, 'Canada':10} df['correct_code_length'] = df.Country.replace(code_lengths) df['is_correct'] = (df.Code1.apply(lambda x: len(str(x))) == df.correct_code_length) | (df.Code2.apply(lambda x: len(str(x))) == df.correct_code_length) ...
python-2.7|pandas
2
15,479
66,602,146
Returning rows in CSV based on column match to values in other CSV
<p>I have a piece of code I use to retrieve specific rows in a large usage data file for specific items which I write out as a list. For any matches in the DOI field the entire row is retrieved.</p> <pre><code>import pandas as pd import numpy as np from pandas import DataFrame df_usage = pd.read_csv(r&quot;usage_data....
<p>If you are trying to filter rows based on the <code>item_list.csv</code> you could try:</p> <pre><code>import pandas as pd import numpy as np from pandas import DataFrame df = pd.read_csv(r&quot;usage_data.csv&quot;, encoding='latin-1') df_items = pd.read_csv(r&quot;item_list.csv&quot;, encoding='latin-1', names=['...
python|pandas|csv
0
15,480
16,235,955
create a multichannel zeros mat in python with cv2
<p>i want to create a multichannel mat object in python with cv2 opencv wrapper.</p> <p>i've found examples on the net where the c++ Mat::zeros is replaced with numpy.zeros, that seems good. but no multichannel type seems to fit..</p> <p>look at the code:</p> <pre><code>import cv2 import numpy as np size = 200, 200...
<p>Try this as <code>size</code>:</p> <pre><code>size = 200, 200, 3 m = np.zeros(size, dtype=np.uint8) </code></pre> <p>Basically what I did to find what arguments I need for the matrix is:</p> <pre><code>img = cv2.imread('/tmp/1.jpg') print img.shape, img.dtype # (398, 454, 3), uint8 </code></pre> <p>But one could...
python|opencv|numpy
22
15,481
57,638,048
pandas groupby head() & tail() not fetching correct values
<p>I have a dataframe as below</p> <pre><code> id s e sa ea 0 AAA 2015-04-22 2015-11-11 2015-05-07 2018-09-28 1 AAA 2015-05-07 2018-09-28 2015-05-07 2018-09-28 2 BBB 1972-11-04 2019-08-01 2019-06-15 2019-12-31 3 BBB 2019-06-15 2019-12-31 2019-06-15 2019-12-31 4 CCC ...
<p>If I understood correctly, you should use <code>first()</code> and <code>last()</code> instead of <code>head()</code> and <code>tail()</code>. </p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df1.groupby('id').first() s e sa ea id AAA 2015-04-22 2015-11-1...
pandas|group-by
3
15,482
57,711,032
sum elements of array
<p>I have an array like this:</p> <pre><code>array = np.array([[[[ 2, -3],[ 3, 2]],[[-4, -1],[-5, 1]], [[-7, -5],[-1, 6]],[[-5, 0],[-4, 2]]], [[[-1, 4],[ 6, 1]],[[-2, -3],[-5, 5]], [[-2, -8],[-1, 7]],[[-1, 8],[-4, 2]]]]) </code></pre> <p><img src="https://i.st...
<p>summing along the 3rd axis should do what you want:</p> <pre><code>res = np.sum(array, axis=3) # or: # res = array.sum(axis=3) </code></pre> <p>which produces</p> <pre><code>[[[ -1 5] [ -5 -4] [-12 5] [ -5 -2]] [[ 3 7] [ -5 0] [-10 6] [ 7 -2]]] </code></pre>
python|arrays|numpy
3
15,483
57,337,768
About concatenating two vectors in python
<p>I have a vector <code>y</code> of size <code>4 x 1</code> , and another vector <code>y2</code> of size <code>1 x 4</code>, I need to concatenate the vectors <code>y</code> and real and imaginary parts of <code>y2</code>. </p> <p>The problem is that when I reshape the vector <code>y2</code> into vector <code>4 x 1</...
<pre><code>Y3 = np.concatenate([y_con.reshape(-1,1), y_m]) </code></pre> <p>y_m is <code>4 X 1</code> so reshape y_con to <code>n X 1</code> to concatenate row wise</p>
python|numpy
1
15,484
24,219,684
Assign new values to an array based on a function ran on other 3 dimensional array
<p>I have a multiband raster where I want to apply a function to the values that each pixel has across all the bands. Depending on the result, a new value is assigned, and a new single-band raster is generated from these new values. For example if a pixel has increasing values across the bands, the value "1" will be as...
<p>At least part of the problem is that when you typed:</p> <pre><code> elif all(a[i] &gt;= a[i+1] for i in range(len(a)-1))==1: print "Trend: decreasing" </code></pre> <p>you probably meant to type this:</p> <pre><code> elif all(a[i] &gt;= a[i+1] for i in range(len(a)-1))==1: return "Trend: de...
python|arrays|numpy
1
15,485
24,245,214
Adding row in Pandas DataFrame keeping index order
<p>I have a <code>DataFrame</code> and I would like to add some inexisting rows to it. I have found the <code>.loc</code> method, but this adds the values at the end, and not in a sorted way. For example</p> <pre><code>import numpy as np import pandas as pd dfi = pd.DataFrame(np.arange(6).reshape(3,2),columns=['A','B...
<p>If your index is almost continuous, only missing a few values here and there. I think you may try the following, </p> <pre><code>In [15]: df=pd.DataFrame(np.zeros((100,2)), columns=['A', 'B']) df['A']=np.nan df['B']=np.nan In [16]: df.iloc[[0,1,2]]=pd.DataFrame({'A': [0,2,4,], 'B': [1,3,5]}) df.iloc[5]=[0,0] df.i...
python|pandas|dataframe
1
15,486
2,275,924
How to get data in a histogram bin
<p>I want to get a list of the data contained in a histogram bin. I am using numpy, and Matplotlib. I know how to traverse the data and check the bin edges. However, I want to do this for a 2D histogram and the code to do this is rather ugly. Does numpy have any constructs to make this easier?</p> <p>For the 1D ca...
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html#numpy.digitize" rel="noreferrer"><code>digitize</code></a>, from core NumPy, will give you the <em>index</em> of the bin to which each value in your histogram belongs:</p> <pre><code>import numpy as NP A = NP.random.randint(0, 10, 100)...
python|numpy|matplotlib|histogram
27
15,487
72,868,538
Split a python pandas column using positional string in another column
<p>I have a dataframe with the structure:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Split</th> <th>Data</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>GT:RC:BC:CN</td> <td>1:4:5:3</td> </tr> <tr> <td>2</td> <td>GT:RC:CN</td> <td>1:7:0</td> </tr> <tr> <td>3</td> <td>GT:BC<...
<p>You can use:</p> <pre><code>out = df.join(pd.concat([pd.Series(d.split(':'), index=s.split(':')) for s,d in zip(df['Split'], df['Data'])], axis=1).T) </code></pre> <p>output:</p> <pre><code> ID Split Data GT RC BC CN 0 1 GT:RC:BC:CN 1:4:5:3 1 4 5 3 1 2 ...
python|pandas|dataframe|split
2
15,488
72,962,927
Is there a way to store output dataframes and appending them to the last output in the same dataframe
<p>I am trying to fetch data from API for 50 parcels. I want them to be in a single data frame. While running this loop the data frame is storing only the last parcel which is satisfying the loop condition. Is there any way to store all the previous outputs also in the same dataframe.</p> <p>For e.g upon running this c...
<p>The issue is resolved by first creating an empty data frame and then appending the outputs in the dataframe within the loop.</p> <p>The updated code is as follows:</p> <pre><code>column_names = [&quot;parcel_foreign_id_x&quot;, &quot;s1product_end_time&quot;, &quot;s1product_ron&quot;,&quot;cohvh_avg&quot;, &quot;co...
python|pandas|dataframe|append
0
15,489
72,984,939
How to convert from pandas Series to an int
<p>I'm trying to convert times from UTC to local times for various countries.</p> <p>To do this I'm searching a dataframe for the country name to find the timezone</p> <pre><code>if (country == &quot;Brazil&quot; or country == &quot;DR-Congo&quot; or country == &quot;Indonesia&quot; or country == &quot;Kazakhstan&quot;...
<p>As stated by @JNevill in a comment, I needed to convert the <code>Series</code> inside of the timedelta itself rather than before it.</p> <p><code>timedelta(hours = int(tz))</code> works great.</p>
python|pandas|dataframe|datetime|timedelta
1
15,490
70,511,735
tf.vectorized_map does not concat variable length tensors (InvalidArgumentError: PartialTensorShape: Incompatible shapes during merge)
<p>I am running into a &quot;InvalidArgumentError: PartialTensorShape: Incompatible shapes during merge&quot; error when I try to tf.concat two tensors who's shapes are dependent on the function input within the vectorized function (even though the output shape is the same for each a,b pair). Below is an example of th...
<p>The problem is you are passing a tensor to <code>tf.ones</code> and <code>tf.zeros</code> instead of a shape. For example, if you pass the tensor <code>a</code> to <code>tf.ones</code>, it will be interpreted as the shape resulting in a tensor with the shape <code>(5, 4, 3, 2)</code>. That is probably not what you w...
python|tensorflow|vectorization|tensorflow2.0|tensor
1
15,491
70,707,446
Pandas multiindex Ranking and Sorting
<p>I have a sorting problem.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>TOT_ENERGY_CONSUMPTION</th> <th>REGION_CODE</th> <th>INDUSTRY_CODE</th> </tr> </thead> <tbody> <tr> <td>11289.15</td> <td>110101</td> <td>I65</td> </tr> <tr> <td>11407.056</td> <td>110101</td> <td>M73</td> </tr> <t...
<p>Use <code>groupby_rank</code> then <code>sort_values</code>:</p> <pre><code>out = df.assign(RANK=df.groupby('REGION_CODE', sort=False)['TOT_ENERGY_CONSUMPTION'] .rank('dense', ascending=False).astype(int)) \ .sort_values(['REGION_CODE', 'RANK']) print(out) # Output TOT_ENERGY_CONSU...
python|pandas|sorting
0
15,492
70,636,801
Map unique values in 2 columns to integers
<p>I have a dataframe with 2 categorical columns (col1, col2).</p> <pre class="lang-py prettyprint-override"><code> col1 col2 0 A DE 1 A B 2 B BA 3 A A 4 C C </code></pre> <p>I want to map the unique string values to integers, for example (A:0, B:1, BA:2, C:3, DE:4)</p> <pre class="lang-py...
<p>To get the same categories across columns you need to reshape to a single dimension first. Then use <code>factorize</code> and restore the original shape.</p> <p>Here is an example using <code>stack</code>/<code>unstack</code>:</p> <pre><code>x = df.stack() x[:] = x.factorize()[0] df2 = x.unstack() </code></pre> <p>...
python|pandas|dataframe
5
15,493
70,556,650
Two consecutive error while drawing a bit pattern
<p>I am trying to draw a bit stream with the code block below:</p> <p>But unfortunately Python throws two errors which are:</p> <pre><code>C:\Users\bahadir.yalin\Anaconda3\lib\site-packages\numpy\core\_asarray.py:171: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple ...
<p>Firstly, <code>-np.ones()</code> wasn't working so I replaced it with <code>-1*np.ones()</code>. Secondly, by not using <code>append()</code> or a similar method you were saving a copy of the array into itself as a new element, like this:</p> <pre><code>&gt;&gt;&gt; [[],np.ones()] #something like this first loop &gt...
python|numpy|matplotlib|math|random
0
15,494
70,511,576
Segmentation fault (core dumped) while trying to print numpy and pandas objects in python via cygwin
<p>I am simply trying to run python (interactively) in cygwin, but whenever I try to print out a numpy array or write a pandas dataframe to a csv file python <strong>prints out</strong> :</p> <pre><code>Segmentation fault (core dumped) </code></pre> <p>To run numpy/pandas I installed with cygwin set-up.exe:</p> <ul> <l...
<p>Turns out it was a <strong>numpy</strong> bug apparently. I'm not sure if it's a proper bug or something else (like my system not being entirely compatible) but I was using <strong>numpy 1.21.4</strong> and <strong>1.21.5</strong>. The problem was solved for me by <em>downgrading to numpy 1.20.3</em>.</p> <p>Sorry i...
python|arrays|pandas|numpy|cygwin
1
15,495
42,663,646
How can I turn pandas dataframe into an ordered list with many to one relationship?
<p>I currently have a pandas dataframe where there are many answers joined on a single question, so I am trying to turn it into a list so I can do cosine similarity. </p> <p>Currently I have the dataframe, where the questions are joined by the answers through the parent_id = q_id, as shown in the picture: </p> <p><a ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <code>apply</code>:</p> <pre><code>#output is tuple with question value df = df.groupby('q_body')['a_body'].apply(lambda x: tuple([x.name] + list(x))...
python|list|pandas|many-to-one
2
15,496
42,916,330
Efficiently count zero elements in numpy array?
<p>I need to count the number of zero elements in <code>numpy</code> arrays. I'm aware of the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.count_nonzero.html" rel="noreferrer">numpy.count_nonzero</a> function, but there appears to be no analog for counting zero elements.</p> <p>My arrays are not...
<p>A <strong>2x</strong> faster approach would be to just use <a href="https://numpy.org/doc/stable/reference/generated/numpy.count_nonzero.html" rel="noreferrer"><em><strong><code>np.count_nonzero()</code></strong></em></a> but with the <em>condition</em> as needed.</p> <pre><code>In [3]: arr Out[3]: array([[1, 2, 0,...
python|arrays|performance|numpy|multidimensional-array
72
15,497
27,350,226
how to make the text size of the x and y axis labels and the title on matplotlib and prettyplotlib graphs bigger
<p>I set the figure size of a matplotlib or prettyplotlib graph to be large. As an example lets say the size is 80 height by 80 width. </p> <p>The text size for the plot title, x and y axis labels (i.e. point label 2014-12-03 and axis label [month of year] become very small to the point they are unreadable.</p> <p>Ho...
<p>The <code>size</code> property:</p> <pre><code>import matplotlib.pyplot as plt plt.xlabel('my x label', size = 20) plt.ylabel('my y label', size = 30) plt.title('my title', size = 40) plt.xticks(size = 50) plt.yticks(size = 60) </code></pre> <p>Example:</p> <pre><code>import numpy as np import matplotlib.pyplot a...
python|matplotlib|pandas|prettyplotlib
21
15,498
27,083,990
matplotlib pcolor axes scale
<p>I have used pcolor to plot a heatmap:</p> <pre><code>df = df.groupby(['d','f'])['beta'].sum() beta_df = df.unstack('f') plt.pcolor(beta_df) </code></pre> <p>beta_df is size 35x35, beginning thus:</p> <pre><code>f 0.05 0.06 0.07 0.08 0.09 0.10 ... d ...
<p>First, it is recommended that you use <code>pcolormesh</code> instead of <code>pcolor</code> (faster and more flexible). You need to tell <code>pcolormesh</code> what is the x and y range of your data. This is done by calling it with the array of x and y values. Assuming your 2D array is called <code>c</code>, you d...
arrays|matplotlib|pandas|heatmap
3
15,499
30,511,585
How to convert a dictionary with datetime objects as keys and numpy arrays as values to 2D numpy array?
<p>I have a dictionary of keys and values that look like this:</p> <pre><code>datetime.datetime(2014, 7, 6, 22, 48, 53): array([ -2.88907517e-04, 1.69103129e-01, -7.10729251e-01, ..., 2.88580034e+07, -7.24711607e+07, -2.38548542e+07])} </code></pre> <p>I need to pass these values to a function, and therefore a new...
<p>Assumed that your Dictionary is <code>dict</code></p> <pre><code>import numpy as np data = np.concatenate([np.reshape(value,(1,-1)) for value in dict.values()]) </code></pre>
python|numpy
1