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
358,300
63,463,977
Show all DataFrame with df.to_string()
<p>I used PyCharm for a long time. To print all DataFrame I typed:</p> <pre><code>print (df.to_string()) </code></pre> <p>Now I want to do the same in VisualStudio Code, but it prints only 117 first values. <a href="https://i.stack.imgur.com/qcJiY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qcJiY...
<p>Do you run it in debug mode?</p> <p>This problem is not caused by the terminal line limit, it should be caused by the debug mode configuration. You can run the python file through python command directly in the terminal to get the full output.</p>
python|pandas|visual-studio-code|pycharm
1
358,301
63,364,989
Convert a dictionary of dictionary into a row wise dataframe in pandas
<p>I have dictionary as shown below</p> <p>d1:</p> <pre><code>{'teachers': 49, 'students': 289, 'R': 3.7, 'holidays': 165, 'E': {'from': '2020-02-29T20:00:00.000Z', 'to': '2020-03-20T20:00:00.000Z', 'F': 3, 'C': 2}, 'OS':18 'sC': {'from': '2020-03-31T20:00:00...
<p>You can use <code>json_normalize</code> and then tranpose the dataframe:</p> <pre><code>d = {'teachers': 49, 'students': 289, 'R': 3.7, 'holidays': 165, 'Em': {'from': '2020-02-29T20:00:00.000Z', 'to': '2020-03-20T20:00:00.000Z', 'F': 3, 'C': 2}, 'OS':18, 'sC': {...
python-3.x|pandas|dataframe|dictionary
3
358,302
63,474,554
How to calculate euclidean distance if given Conditions?
<p>I have a sample of companies with financial figures which I would like to compare. My data looks like this:</p> <pre><code> Cusip9 Issuer IPO Year Total Assets Long-Term Debt Sales SIC-Code 1 783755101 Ryerson Tull Inc 1996 9322000.0 2632000.0 ...
<p>I replicated the data you provided and then calculated the distances. For each issuer I find the closest issuer and its distance. See modified code below. Please let me know if you need more details.</p> <pre><code>issuers = [&quot;Ryerson Tull Inc&quot;, &quot;Siebel Sys Inc&quot;, &quot;Travis Boats &amp; Motors I...
python|pandas|dataframe
0
358,303
63,331,667
Operations with Numpy arrays with zero dimensions
<p>Is a numpy array of shape (0,10) a numpy array of shape (10). I'm writing a very simple function that will alternate between 2 and 3 dimensions and I am wondering know whether the output of something like this:</p> <pre><code>def Pick(N = 0, F, R, Choice=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]): if N==0: return...
<p>Abstractly, an array of shape (N,M,L) can be represented identically by an array of shape (&lt;&gt;,N,&lt;&gt;,M,&lt;&gt;,L,&lt;&gt;), where &lt;&gt; can be substituted for a sequence of 1s with arbitrary finite length. Consider the set of indexes corresponding to each data point — if one dimension is of length 0, w...
python|numpy|multidimensional-array|zero|dimension
3
358,304
63,369,011
Is there a fast way to find negative counterpart duplicates in a Pandas DataFrame?
<p>Hi smart people of Stack Overflow, I'm looking for a fast way to mark all pairs of rows in a 160,000 row Pandas Dataframe that are <strong>each other's negative counterpart</strong>.</p> <p>Example Dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A': ['a','b','c','b','c','d','b'], ...
<p>For your case let do <code>transform</code> sum with <code>filter</code></p> <pre><code>s=df.groupby(['A','B']).C.transform('sum').eq(0) df=df[s] df.groupby(['A','B']).groups.values() Out[32]: dict_values([Int64Index([1, 3], dtype='int64'), Int64Index([2, 4], dtype='int64')]) </code></pre>
python|pandas|duplicates
1
358,305
63,690,977
Remove groups from a DataFrame that contain only a single unique value in one column
<p>I am processing data with Pandas. 'A' is a unique ID column and column 'E' contains either <code>1</code> or <code>0</code>. I want to keep only groups where the value of column E contains both 0 and 1. (I want to delete rows where columns A are 2 and 4 as those groups contain only 1 and 0s respectively, leaving onl...
<p>Use <code>Series.groupby</code> on column <code>E</code> and <code>transform</code> using <code>any</code> to create a boolean mask:</p> <pre><code>m = (df['E'].eq(0).groupby(df['A']).transform('any') &amp; df['E'].eq(1).groupby(df['A']).transform('any')) df1 = df[m] </code></pre> <p>Or another idea if column <...
python|pandas
6
358,306
63,622,437
bad input shape when using labelEncoder
<p>I have a fairly large dataframe with both numerical and categorical values. I'm trying to encode the categorical values but am getting the above error.</p> <p>Here's a simple version of the code:</p> <pre><code>from collections import defaultdict d = defaultdict(LabelEncoder) # Encoding the variable fit = df[catgori...
<p><strong>Update</strong></p> <p>Seems like you are trying to apply the LabelEncoder to multiple columns; While you can <a href="https://stackoverflow.com/questions/24458645/label-encoding-across-multiple-columns-in-scikit-learn">apply the same LabelEncoder to all columns</a>;</p> <pre><code>from sklearn.preprocessing...
python|pandas|scikit-learn
0
358,307
63,343,390
Having trouble with numpy append function
<p>I was doing work for a course today, and the assignment was to create a tic tac toe board. The possibilities method takes a tic tac toe board as an input, and checks if any of the values are &quot;0&quot;, meaning that it's an open space. My plan would be to add the location of the 0 to an array, called locations, a...
<pre><code>In [530]: board = np.random.randint(0,2,(3,3)) In [531]: board Out[531]: array([[0, 0, 0], [1, 0, 1], [0, 1, 0]]) </code></pre> <p>Looks like you are try...
python|arrays|numpy|append
0
358,308
63,623,968
Replacing values in data frame with another data frame based on one of the columns
<p>I have two dataframes, one that contains some information and a shorter dataframe that contains some amendments I want to make to the first. I have tried something similar to that written below.</p> <pre><code>for x in df['var']: if x in df2['var']: df['var2'] == df2['var2'] </code></pre> <p>For example...
<p>Have you tried <code>df.update()</code></p> <pre><code>df.update(df1) num_legs num_wings num_specimen_seen falcon 2.0 2.0 10.0 dog 4.0 0.0 5.0 spider 8.0 0.0 9.0 fish 0.0 0.0 8.0 </code><...
python|pandas|for-loop
0
358,309
63,544,157
How to convert if else condition to numpy in python
<pre><code>TN=FN=FP=TP=0 for j in range(0,len(data)): if((data['y'][j]==0) &amp; (data['proba'][j]==0)): TN+=1 elif((data['y'][j]==0) &amp; (data['proba'][j]==1)): FN+=1 elif((data['y'][j]==1) &amp; (data['proba'][j]==0)): FP+=1 elif((data['y'][j]==1) &amp; (data['proba'][j...
<p>Let's start from the beginning and think about what this code really does:</p> <pre><code>TN=FN=FP=TP=0 </code></pre> <p>OK, so we have four integers.</p> <pre><code>for j in range(0,len(data)): </code></pre> <p>We loop over all the rows. Notice that the next parts are all independent and similar so I'm only going ...
python|numpy
1
358,310
63,700,499
Merge a list of list of dataframe python
<p>I have a list of lists each containing a common column, A, B to be used as indices as follows</p> <pre><code>df_list=[[df1], [df2],[df3], [df4], [df5, df6]] </code></pre> <p>I would like to merge the dataframes into a single dataframe based on the common columns A, B in all dataframes</p> <p>I have tried pd.concat(d...
<p>You need to deliver flat list (or other flat structure) to <code>pd.concat</code> your</p> <pre><code>df_list=[[df1], [df2],[df3], [df4], [df5, df6]] </code></pre> <p>is nested. If you do not have command over filling said <code>df_list</code> you need to flatten it first for example using <code>itertools.chain</cod...
python|pandas|list|dataframe
4
358,311
63,476,642
Appending all values (each containing a list) of a dict to pandas df
<p>I have a column, with each row containing a python dictionary with multiple keys and values. Each value is a list. Index[0] looks like:</p> <pre><code>{'Paradigms': ['Agile Software Development', 'Scrum', 'DevOps', 'Serverless Architecture'], 'Platforms': ['Kubernetes', 'Linux', 'Windows', 'Eclipse', ...
<p>IIUC, you could try with <code>json_normalize</code>:</p> <pre><code>#dictionary given d={'Paradigms': ['Agile Software Development', 'Scrum', 'DevOps', 'Serverless Architecture'], 'Platforms': ['Kubernetes', 'Linux', 'Windows', 'Eclipse', 'PagerDuty', 'Apache2', 'Docker', 'AWS EC2', 'Amazon Web Services (AWS)', 'Sy...
pandas|dictionary
1
358,312
63,325,070
Faster way to calculate distance between two 3D points
<p>I have 4 lists of length 160000 as s, x, y, z. I made a list(points) of 3d array of x,y,z. I need to find the distance between all combinations of points for criteria and match the index of the points to that of list s, so that I get the s value of 2 points which satisfy it. I'm using the code below. Is there any fa...
<p>Idea is to use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow noreferrer">cdist</a> and <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">np.where</a> to vectorize the processing</p> <p><strong>Code</s...
python|numpy
3
358,313
63,596,429
PyQt5 - Problem updating TableView with new pandas DataFrame
<p>I have <code>PyQt5</code> App which generates pandas dataframe to PyQt <code>TableView</code>.Dataframe is generated with function getPageInfo which is calling class which generates pandas dataframe object.</p> <p>Everything works nicely for default value of <code>QLineEdit()</code> which is URL entry for class <cod...
<p><strong>Here is working solution.</strong> @Heike - thank you for tip!</p> <p>pandas data model (<code>self.model</code>) and <code>QTableView()</code> as well both needs to be updated inside function.</p> <pre><code>from PyQt5.QtCore import QUrl import sys from PyQt5.QtWidgets import QApplication, QTableView from ...
python|pandas|pyqt|pyqt5
0
358,314
63,389,987
How to extract excel column data into python list using pandas from merged cell
<p>i'm trying to extract 'Country' column data into python list using pandas. Below the code i used to. Also attached excel sheet and output.</p> <p>code:</p> <pre><code>from pandas import DataFrame import pandas as pd open_file = pd.read_excel('data.xlsx', sheet_name=0) df = list(open_file['Country']) print(df) </code...
<p>Try this</p> <pre><code>df = pd.read_excel('data.xlsx', header[0,1]) df = df.rename(columns=lambda x: x if not 'Unnamed' in str(x) else '') </code></pre> <p>Now the headers are in the form of tuples. For ex, to access <code>Country</code> or Column <code>Gold</code>, you need to write something like below statements...
python|pandas
1
358,315
63,729,941
Pandas - why does it throw ValueError?
<p>Would anyone know why is Pandas throwing the ValueError and how to fix it? I just want to calculate the difference in &quot;Value&quot; column while grouping by &quot;CurveName&quot; and &quot;Tenor&quot;</p> <p><a href="https://i.stack.imgur.com/6HAqN.png" rel="nofollow noreferrer">Example</a></p>
<p>you need to add .agg() method with arguments to groupby object to be able to apply diff and other functions to it. Otherwise it is not clear how exactly you want to aggregate your data. See help and examples on groupby/agg method.</p> <p>here is a simple example:</p> <pre><code>df = pd.DataFrame() df['a'] = np.rando...
python|pandas
0
358,316
63,431,346
how can I add duplicated rows to a Pandas DF?
<p>I appreciate the help in advance!</p> <p>The question may seem weird at first so let me illustrate what I am trying to accomplish:</p> <p>I have this df of cities and abbreviations:</p> <p><a href="https://i.stack.imgur.com/QL0QK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QL0QK.png" alt="ente...
<p>Here is one way, using <code>.explode()</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'City_Name': ['Phoenix', 'Tucson', 'Mesa', 'Los Angeles'], 'State': ['AZ', 'AZ', 'AZ', 'CA']}) # 'Query' is a column of tuples df['Query'] = [('Doc Mgmt', 'Imaging', 'Services')] * len(df.index)...
python|pandas
3
358,317
63,692,255
saving multiple 3D array of size (22,6,2840) as images
<p>I am generating multiple 3D numpy array of size (22,6,2840),each array containing 22 array of size(6,2840).Now I want to save this array (22,6,2840) as images. I don't know if I can do that. I tried to do this using <code>plt.savefig</code> but it didn't work. I am trying for more than 2 weeks to find how I can do i...
<p>try using the <code>PyPNG</code> library. You will have to reshape your array to a 2-D format and then write it as a png. The link to the library is <a href="https://pypng.readthedocs.io/en/latest/ex.html#numpy-array-to-png-writing" rel="nofollow noreferrer">here</a></p> <pre><code> image_2d = numpy.reshape(image...
python|numpy|python-imaging-library
1
358,318
63,474,430
How to drop duplicates memory efficiently?
<p>So I have a coupe of excel files totaling 1.8GB for now and is growing. All excel files have same columns and may have some overlapping rows with other files. Currently I have to read all files in memory (which is slow and soon I will not be able to because of PC RAM limitation). I am using following two methods but...
<p>Here is a Python- and Excel-based approach that will run on your current machine. (I'm assuming that purchasing additional RAM, running on the cloud or using a database are not feasible.)</p> <p>First, create a couple sample data frames for illustration. (If necessary, you could use Excel itself to convert .xlsx ...
python|excel|pandas
0
358,319
63,393,340
Convert dataframe column to datetime only if length of string is not zero
<p>I'd like to convert a dataframe column which has a date string. But in some cases, the date string might be empty due to certain conditions. So I just want all the other rows in that column to be converted to datetime format except the rows in that particular column which might be blank. Is it possible?</p> <p>What ...
<p>Two steps,</p> <p>first lets create a series with your datetimes and coerce the bad values into <code>NaTs</code></p> <pre><code>s = pd.to_datetime(data['etime'],errors='coerce',format='%Y%m%d%H%M%S') </code></pre> <p>second, lets find any values that aren't <code>NaT</code> and replace them with your target formatt...
python|python-3.x|pandas|dataframe|python-datetime
2
358,320
63,539,146
How to perform rolling sum on pandas dataframe with group by for last 365 days only
<p>Trying to calculate a rolling sum on p_id for last 365 days only, creating a new column that contains this rolling sum. The dataframe with new column should look like this:</p> <pre><code>Date p_id points roll_sum 2016-07-29 57 11 11 2016-08-01 ...
<p>you can add it as a series if the index of the dataframe and <code>roll_sum</code> match; here the index includes <code>&quot;p_id&quot;, &quot;Date&quot;</code></p> <pre><code>df[&quot;Date&quot;] = df.Date.astype(&quot;datetime64&quot;) roll_calc = df.groupby(&quot;p_id&quot;).rolling('365D', on=&quot;Date&quot;)[...
python|pandas
1
358,321
63,431,509
Find difference in two rows of string in a pandas dataframe
<p>I have a dataframe with a column that has a string with comma separated items.</p> <pre><code>col1 apple, banana, kiwi apple, banana banana </code></pre> <p>I want to make a second column 'col2' that shows the difference between each row.</p> <p>So I'm trying to turn each row into a set, and subtracting it from the ...
<pre><code>df[&quot;temp&quot;] = df.col1.str.replace(&quot;\s+&quot;, &quot;&quot;).str.split(&quot;,&quot;) </code></pre> <p>Assign value to <code>difference</code> column:</p> <pre><code>df['difference'] = [ &quot;&quot; if isinstance(last, float) or (not set(last).difference(first)) ...
python|pandas
0
358,322
63,668,864
scipy.interpolate.interp2d: do I really have too many data points?
<p>I have a set of elevation measurements that are on a X, Y grid. I'm trying to create a slice through the elevations (under an angle so not perfectly on the grid points). I thought of using the 2D interpolation method from scipy, but I get the error OverflowError: Too many data points to interpolate. I don't have an ...
<p>If you have a regular grid, it is sufficient to provide only 1D arrays for x and y coordinates. This is less computational expensive but I don't know if this is the reason for the error message in the case of the general grid.</p> <pre class="lang-py prettyprint-override"><code> import numpy as np from scipy import ...
python|numpy|scipy|interpolation
1
358,323
63,727,727
Merge certain rows in a DataFrame based on startswith
<p>I have a DataFrame, in which I want to merge certain rows to a single one. It has the following structure (values repeat)</p> <pre><code>Index Value 1 date:xxxx 2 user:xxxx 3 time:xxxx 4 description:xxx1 5 xxx2 6 xxx3 7 billed:xxxx ... </code></pre> <p>Now the problem is, that th...
<pre><code>df = pd.DataFrame.from_dict({'Value': ('date:xxxx', 'user:xxxx', 'time:xxxx', 'description:xxx', 'xxx2', 'xxx3', 'billed:xxxx')}) records = [] description = description_val = None for rec in df.to_dict('records'): # type: dict # if previous description and record startswith previous description value ...
pandas|startswith
0
358,324
63,609,191
What is the datetime equivalent for pandas dayofyear?
<p>I'm looking to get an array of values of day of year from a list of <code>datetimes</code>. I can get the week number, for example, using the method <code>isocalendar</code>. But what's the method for an integer day of year? Using pandas this is <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pan...
<p>Here is a short example of days between dates, using only the Python built-in datetime module:</p> <pre><code>import datetime dates = [ datetime.date(2019, 12, 30), datetime.date(2019, 12, 31), datetime.date(2020, 1, 1), datetime.date(2020, 1, 2) ] for d in dates: base_date = d.replace(month=1, day=1...
python|pandas|numpy|datetime
0
358,325
63,643,976
unexpected SettingWithCopyWarning in pandas even if we use .loc method
<pre><code>workclass = X_train[~X_train['workclass'].isnull()]['workclass'].unique() for dataset in [X_train, X_test]: df = dataset[dataset['workclass'].isnull()].index size = len(df) s = pd.Series([workclass[np.random.randint(0, 8)] for _ in range(size)], index=df, dtype=object) dataset.loc[:, 'workcla...
<p>I think you should have used the <code>train_test_split</code> from <code>sklearn</code> so to split the data before.</p> <p>The pandas will raise the <code>SettingWithCopyWarning</code> warning if it is not sure that the given DataFrame you are changing is either a copy or the original DataFrame.</p> <p>The causes ...
pandas|data-analysis|missing-data
1
358,326
63,660,467
TypeError: unhashable type: 'dict'. Unable to read Parquet file with Dask
<p>Unable to read the parquet file as a dask dataframe. I am able to read with pandas. Please suggest! I couldn't figure out what I am missing out! dask version == 1.0.0, pyarrow version == 0.13.0, pandas version ==0.23.4</p> <p>Sample of Paruet File</p> <pre><code>UniqueReference DateTime Consumption 0 ...
<p>As mentioned in the comments, this was with a very old version of Dask from several years ago. With a modern version this is fine.</p>
python-3.x|pandas|dask|parquet
0
358,327
21,629,919
fsolve problems with the starting point
<p>I'm using fsolve in order to solve a non linear equation. My problem is that, depending on the starting point the solutions change and I am not sure that the ones that I found are the most reasonable. This is the code</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.optimize import fsolv...
<p>The eternal issue with turning non-linear solvers loose is having a really good understanding of your function, your initial guess, the solver itself, and the problem you are trying to address. </p> <p>I note that there are many (a,Phi) combinations where your function does not have real roots. You should do some m...
python|optimization|numpy|simpy
1
358,328
21,617,194
Mode/Median/Mean of a 3d numpy array
<p>I have a 3d numpy array and my goal is to get the mean/mode/median of it.</p> <p>It has a shape of [500,300,3]</p> <p>And I would like to get for example:</p> <p>[430,232,22] As the mode</p> <p>Is there a way to do this? The standard np.mean(array) gives me a very large array.</p> <p>I don't know if this is act...
<p>You want to get the mean/median/mode <strong>along the first two axes</strong>. This should work:</p> <pre><code>data = np.random.randint(1000, size=(500, 300, 3)) &gt;&gt;&gt; np.mean(data, axis=(0, 1)) # in nunpy &gt;= 1.7 array([ 499.06044 , 499.01136 , 498.60614667]) &gt;&gt;&gt; np.mean(np.mean(data, ax...
python|numpy|scipy
6
358,329
21,446,283
how do you find the last column or row in an excel spreadsheet using python pandas
<p>Hi am looking to import part of a spreadsheet as a data frame using pandas but the problem is the spreadsheet changes weekly and the number of rows and columns varies each week.</p> <p>In Excel VBA I can programmatically determine the number of columns and rows in an excel spreadsheet, but how do I determine that i...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html#pandas.DataFrame.fillna" rel="nofollow"><code>fillna</code></a> with method 'ffill'</p> <pre><code>In [71]: df1 = pd.DataFrame({'a':[1,2,3,NaN,NaN,4,5,6], 'b':[1,2,NaN,NaN, 3,NaN,4,5]}) df1 Out[71]: a b 0 1 1 ...
python|excel|pandas
0
358,330
21,484,782
python: slice according to an irregular pattern
<p>Below, you can find an excerpt from a pandas timeseries. I would like to slice the rows set apart by the white space. There is a recurring pattern, i.e. 21 times value X, four different values ABCD, 21 times value Y, four different values EFGH, 21 times value Z etc. In this case, I'm interested in obtaining BCDY, FG...
<p>Can you not just iterate though the lines, adding everything to the current group's list of lines, and then on empty line, change the list you're appending too? This assumes that the missing data would not return an empty string over not creating a new line.</p> <pre><code>x = 1 groups = { 1 : [], 2 : [], 3 : [] } ...
python|pandas
1
358,331
21,887,754
Concatenate two NumPy arrays vertically
<p>I tried the following:</p> <pre><code>&gt;&gt;&gt; a = np.array([1,2,3]) &gt;&gt;&gt; b = np.array([4,5,6]) &gt;&gt;&gt; np.concatenate((a,b), axis=0) array([1, 2, 3, 4, 5, 6]) &gt;&gt;&gt; np.concatenate((a,b), axis=1) array([1, 2, 3, 4, 5, 6]) </code></pre> <p>However, I'd expect at least that one result looks l...
<p>Because both <code>a</code> and <code>b</code> have only one axis, as their shape is <code>(3)</code>, and the axis parameter specifically refers to the axis of the elements to concatenate.</p> <p>this example should clarify what <code>concatenate</code> is doing with axis. Take two vectors with two axis, with shap...
python|arrays|numpy|concatenation
104
358,332
21,494,854
read_csv columns encoding
<p>I am quite new to python.</p> <p>I am trying to automate some data analysis of building energy consumption data using python. I am using <code>python 2.7.3</code>, <code>pandas 0.12</code>, <code>Canopy with qtconsole</code></p> <p>These are the steps I am following:</p> <ol> <li>Paste the data from my simulation...
<p>Ok, If I was doing something like this, </p> <p>1)Get rid of Excel. - Do you need it. Why does your simulation program not dump the data it self? If it can't in stead of pasteing to to Excel, paste it to a txt file and parse it from Python</p> <p>2)Get rid of super script - Do you really need the superscript ? I...
python|csv|encoding|pandas
1
358,333
24,468,624
How to convert all data in dataframe column to dates [Python/Pandas]
<p>I have a long list of dates, currently of dtype object.</p> <pre><code>. . 22/05/2014 22/05/2014 0 22/05/2014 . . </code></pre> <p>I want to plot these dates against some numerical data, in a 3D plot if possible.</p> <p>Whether dates need converting or not it would be nice to know:</p> <ol> <li><p>How can I conv...
<p>I will suggest treating the <code>0</code> as missing values when reading the data, so it will be converted to missing datatime value in the end:</p> <pre><code>In [67]: df=pd.read_clipboard(header=None, na_values=['0']) print df 0 0 22/05/2014 1 22/05/2014 2 NaN 3 22/05/2014 In [68]: pd.to...
python|numpy|matplotlib|pandas
0
358,334
24,576,622
"bucketsort" with pythons multiprocessing
<p>I have a data series with a uniform distribution. I wish to exploit the distribution to sort the data in parallel. For N CPUs, I essentially define N buckets and sort the buckets in parallel. My problem is that, I do not get a speed up.</p> <p>What is wrong?</p> <pre><code>from multiprocessing import Process, Queu...
<p>It looks like your problem is the amount of overhead you're adding when you break the original array into pieces. I took your code, and just removed all usage of <code>multiprocessing</code>:</p> <pre><code>def my_sort(x,y): pass #y.put(x.get().argsort()) def my_par_sort(X,np, starttime): p_list=[] ...
python|sorting|numpy|parallel-processing|multiprocessing
2
358,335
24,563,108
Pandas Dynamic Row-Based Equity Calculation
<p>I've been beating my head against a wall trying to figure out the best approach on this question. I have a SLOW backtester in Excel that I'm trying to port to pandas. I thought I'd be able to leverage the power of python rather than merely recreate the Excel functions in python, but I'm stuck!</p> <p>The key challe...
<p>Just follow the same idea that you do in the <code>Excel</code>, the only difference is that the <code>excel function</code> applied to each row is now expressed as a loop:</p> <pre><code>In [113]: print prices A B C 2000-01-01 20 0 11 2000-01-02 30 0 12 2000-01-03 10 0 20 2000-01-04 ...
python|pandas
1
358,336
24,564,047
Applying function to a single column of a grouped data in pandas
<p>Theres a pandas dataframe like shown below</p> <pre><code> Bank date creationdate 0 JP Morgan 2010-07-22 2010-07-22 12:17:38.187000 1 JP Morgan 2010-07-31 2010-07-31 12:41:57.083000 2 JP Morgan 2010-11-18 2010-11-18 19:24:15.503000 3 JP Morgan 2011-03-08 2011-03-08 18:57...
<p>I think you can do this with <code>.aggregate</code> in one step, rather than trying to get things done in two steps:</p> <pre><code>In [30]: print df_grouped['creationdate'].aggregate(lambda x: (np.diff(x)).mean()) Bank date creationdate 0 JP Morgan 2010-07-22 NaT 1 JP Morgan 201...
python|pandas|dataframe
3
358,337
24,814,397
Find the most frequent element in a masked array
<p>I need to find the most frequent element in a numpy array "label", only if those elements lie inside the mask array. Here is the brute force approach:</p> <pre><code>def getlabel(mask, label): # get majority label assert label.shape == mask.shape tmp = [] for i in range(mask.shape[0]): for ...
<p><code>np.bincount</code> is <strong>not</strong> a general approach.<code>np.bincount</code> will be faster for bounded, low entropy, discrete distributions. However, it will fail:</p> <ul> <li>if the distribution is unbounded, the memory used is unbounded (can be arbitrarily large for an arbitrarily small input ar...
python|algorithm|numpy|data-structures
1
358,338
24,616,079
How to interpolate using nearest neighbours for high dimension numpy python arrays
<p>I am programming in python using scipy and numpy, I have a look up table of data (LUT) that I access like so:</p> <pre><code>self.lut_data[n_iter][m_iter][l_iter][k_iter][j_iter][i_iter] </code></pre> <p>where I get the *_iter index corresponds to an array of values that I keep in a dictionary. for example, the ...
<p>If you have a full array of information to interpolate from, the linear interpolation is not that difficult. It is just slightly time consuming, but if you can fit your array in RAM, it is just a matter of seconds.</p> <p>The trick is that linear interpolation can be done one axis at a time. So, for each axis:</p> ...
python|arrays|numpy|scipy
1
358,339
29,903,025
Count most frequent 100 words from sentences in Dataframe Pandas
<p>I have text reviews in one column in Pandas dataframe and I want to count the N-most frequent words with their frequency counts (in whole column - NOT in single cell). One approach is Counting the words using a counter, by iterating through each row. Is there a better alternative?</p> <p>Representative data.</p> <...
<pre><code>from collections import Counter Counter(&quot; &quot;.join(df[&quot;text&quot;]).split()).most_common(100) </code></pre> <p>I'm pretty sure this would give you what you want. (You might have to remove some non-words from the counter result before calling <code>most_common</code>.)</p>
python|pandas
47
358,340
30,278,833
OpenGL Texturing - some jpg's are being distorted in a strange way
<p>I am trying to draw a textured square using Python, OpenGL and GLFW. Here are all the <a href="http://imgur.com/a/YnU7m" rel="nofollow">images</a> I need to show you.</p> <p>Sorry for the way of posting images, but I don't have enough reputation to post more than 2 links (and I can't even post a photo).</p> <p>I a...
<p>The problem you have there are alignment issues. OpenGL initial alignment setting for "unpacking" images is that each row starts on a 4 byte boundary. This happens if the image width is not a multiple of 4 or if there are not 4 bytes per pixel. But it's easy enough to change this:</p> <pre><code>glPixelStorei(GL_UN...
python|opencv|opengl|numpy|jpeg
4
358,341
29,885,212
Efficiently checking Euclidean distance for a large number of objects in Python
<p>In a route planning algorithm, I'm trying to perform a filter on a list of nodes based on distance to another node. I'm actually pulling the lists from a crude scene graph. I use the term "cell" to refer to a volume within a simple scenegraph from which we've fetched a list of nodes that are close to each other.</p>...
<blockquote> <ol> <li><p>What am I doing wrong with the vectorized distance calculation?</p> <pre><code>distances = numpy.linalg.norm(np_cell[1] - srcPos) </code></pre> <p>vs</p> <pre><code>distances = numpy.linalg.norm(np_cell[1] - srcPos, ord=1, axis=1) </code></pre></li> </ol> </blockquote> <p>Firstly,...
python|numpy|vectorization|computational-geometry
6
358,342
30,063,437
Trouble storing numpy array in sqlite3 with python
<p>I'm trying to follow the example shown as the top answer here: <a href="https://stackoverflow.com/questions/18621513/python-insert-numpy-array-into-sqlite3-database">Python insert numpy array into sqlite3 database</a></p> <p>At first I thought it was my code, but I've tried copying and pasting the answer code exa...
<p>The only problem with unutbu's code is that his <code>adapt_array</code> raises an exception in Python 3:</p> <pre><code>def adapt_array(arr): out = io.BytesIO() np.save(out, arr) out.seek(0) # http://stackoverflow.com/a/3425465/190597 (R. Hill) return buffer(out.read()) </code></pre> <p>That's...
python|numpy|sqlite
2
358,343
30,261,541
Slow Stochastic Implementation in Python Pandas
<p>I am new to pandas and I need a function for calculating slow stochastic. I think it should be possible without much difficulty but I am not familiar with advanced APIs in pandas.</p> <p>My data frame contains, 'open', 'high', 'low' and 'close' prices and it is indexed on dates. This much information should be enou...
<p>You can use the following simple function to handle both slow and fast stochastics. </p> <pre><code>def stochastics( dataframe, low, high, close, k, d ): """ Fast stochastic calculation %K = (Current Close - Lowest Low)/ (Highest High - Lowest Low) * 100 %D = 3-day SMA of %K Slow stochastic...
numpy|pandas|matplotlib
10
358,344
30,089,213
How to take n-th order discrete sum of numpy array (sum equivalent of numpy.diff)
<p>I know that it is possible to take the n-th order discrete difference of a numpy array by using the numpy function <code>numpy.diff()</code>, but is there a way to do the same with the n-th order discrete sum?</p> <p>Let's say we have a numpy array, <code>A = np.arange(10)</code>. The expected result for the 1st or...
<p><code>A[i+1]</code> for <code>for i in range(N-1)</code> would be covered by <code>A[1:]</code> and similarly <code>A[i]</code> for the same iteration means <code>A[:-1]</code>. So, basically you can sum these two versions of the input array to have a vectorized output in <code>B</code>, like so -</p> <pre><code>B ...
python|arrays|numpy|vectorization
6
358,345
29,894,320
Vectorizing a Numpy slice operation
<p>Say I have a Numpy vector,</p> <pre><code>A = zeros(100) </code></pre> <p>and I divide it into subvectors by a list of breakpoints which index into <code>A</code>, for instance,</p> <pre><code>breaks = linspace(0, 100, 11, dtype=int) </code></pre> <p>So the <code>i</code>-th subvector would be lie between the in...
<p>You can use simple <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html" rel="nofollow noreferrer"><code>np.cumsum</code></a> -</p> <pre><code>import numpy as np # Form zeros array of same size as input array and # place ones at positions where intervals change A1 = np.zeros_like(A) A1[br...
python|numpy|vectorization
7
358,346
30,082,621
Solve broadcasting error without for loop, speed up code
<p>I may be misunderstanding how broadcasting works in Python, but I am still running into errors. </p> <p><code>scipy</code> offers a number of "special functions" which take in two arguments, in particular the <code>eval_XX(n, x[,out])</code> functions. See <a href="http://docs.scipy.org/doc/scipy/reference/special....
<p>The documentation for these functions is skimpy, and a lot of the code is compiled, so this is just based on experimentation:</p> <pre><code>special.eval_hermite(n, x, out=None) </code></pre> <p><code>n</code> apparently is a scalar or array of integers. <code>x</code> can be an array of floats.</p> <p><code>spe...
python|for-loop|numpy|matrix|scipy
1
358,347
30,235,414
print surface fit equation in python
<p>I'm trying to fit a surface model to a 3D data-set (x,y,z) using matplotlib.<br> Where <code>z = f(x,y)</code>.<br> So, I'm going for the quadratic fitting with equation: </p> <pre><code>f(x,y) = ax^2+by^2+cxy+dx+ey+f </code></pre> <p>So far, I have successfully plotted the 3d-fitted-surface using least-square m...
<p>According to the documentation of the function scipy.linalg.lstsq <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.linalg.lstsq.html" rel="nofollow noreferrer">http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.linalg.lstsq.html</a> the estimated coefficients should be stored i...
python|numpy|matplotlib|scipy|least-squares
3
358,348
30,140,966
broadcasting a function on a 2-dimensional numpy array
<p>I would like to improve the speed of my code by computing a function once on a <strong>numpy</strong> array instead of a <strong>for loop</strong> is over a function of <a href="https://github.com/GalSim-developers/GalSim" rel="nofollow">this</a> python library. If I have a function as following:</p> <pre><code>imp...
<p>This here should work when <code>pos</code> is an array of shape <code>(n,2)</code></p> <pre><code>import numpy as np def f(pos, z): r=np.sqrt(pos[...,0]**2+pos[...,1]**2) return np.log(r)*(z+1) </code></pre> <p>Example:</p> <pre><code>z = np.arange(10) pos = np.arange(20).reshape(10,2) f(pos,z) # array...
python|numpy|vectorization
2
358,349
53,598,276
Values get changed when numpy int32 array is converted to float32
<p>I'm changing the type of numpy array <code>data_np</code> from int32 to float32 by <code>data_np.dtype = np.float32</code> But it's changing the values from <a href="https://i.stack.imgur.com/i9ZkT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i9ZkT.jpg" alt="enter image description here"></a></...
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.dtype.html" rel="nofollow noreferrer"><code>ndarray.dtype</code></a> is not meant to modify the dtype. I would use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html" rel="nofollow noreferrer"><code>astyp...
python|arrays|python-3.x|numpy|multidimensional-array
1
358,350
53,655,843
Why is Tensorflow sending me this error during the retrain process "can't open file 'tensorflow/examples/image_retraining/retrain.py': "
<p>I'm currently using Tensorflow to make an image classifier and during the retrain process I keep getting an error after entering these lines.</p> <pre><code>python tensorflow/examples/image_retraining/retrain.py \ --bottleneck_dir=/tf_files/bottlenecks \ --how_many_training_steps 500 \ --model_dir=/tf_files/incepti...
<p>It's probably because you don't have that file, try downloading it from <a href="https://github.com/tensorflow/hub/blob/master/examples/image_retraining/retrain.py" rel="nofollow noreferrer">github</a> </p>
python|python-2.7|docker|tensorflow|classification
0
358,351
53,711,463
pandas iterate over 3 data frames element wise into a function
<p>i wrote :</p> <pre><code>def revertcheck(basevalue,first,second): if basevalue==1: return 0 elif basevalue &gt; first and first &gt; second: return -abs(first-second) elif basevalue &lt; first and first &lt; second: return -abs(first-second) else: return abs(first-se...
<p>Let's assume <code>basevalue</code>, <code>first</code> and <code>second</code> are your three dataframes of exactly the same size and structure, then you can do what you want in a vectorised manner:</p> <pre><code>output = abs(first - second) output = output.mask(basevalue == 1, 0) output = output.mask((basevalue ...
pandas|dataframe
1
358,352
53,496,242
Insert values in data-frame's new columns on the right index
<p>I would like to obtain the lower_bound of some datas and insert it into a new column on the relative index. for example:</p> <pre><code>My df: col1 col2 0 1 3 1 2 4 2 5 8 3 1 2 4 8 4 5 6 2 6 4 8 7 8 6 8 ...
<p>Assign output to filtered new column:</p> <pre><code>lower_bound = 0.1 m = df.col1 == 8 df.loc[m, 'newcol'] = df.loc[m, 'col2'].quantile(lower_bound) #another solution #df['newcol'] = np.where(m, df.loc[m, 'col2'].quantile(lower_bound), np.nan) print (df) 0 1 3 NaN 1 2 4 NaN 2 5 8 ...
python|pandas|dataframe
1
358,353
53,373,002
Creating new column based on values of other column (condition on date present in multiple columns) in Python
<p>In the dataset, there are several columns with date as value. I need to create new columns based on certain condition on the date values. Certain date values are replaced by "\N" character, so it appears that entire column is being treated as string.</p> <pre><code>Date 1 Date 2 2012-12-03 2012-12-07 2004-12-...
<p>The column is indeed being treated as string. This happens because, by default, pandas doesn't convert values to date types.</p> <p>After <code>df = read_csv(path)</code>, you can do:</p> <pre class="lang-py prettyprint-override"><code>df['Date 1'] = pd.to_datetime(df['Date 1'], errors='coerce') df['Date 2'] = pd....
python|pandas|numpy|date
0
358,354
53,465,682
Turning masked results into different random numbers
<p>I want to do something like this.</p> <pre><code>import numpy # Create a 10x10 array of random numbers. example_array = numpy.random.random_integers(0, 10, size=(10, 10)) # Locate values that equal 5 and turn them into a new random number. example_array[example_array == 5] = numpy.random.random_integers(0, 10) </...
<p>Use <code>np.random.choice</code> with the number of elements to be masked -</p> <pre><code>import numpy as np mask = example_array == 5 select_nums = np.r_[:5,6:10] # array from which elements are to be picked up # we need to skip number 5, so we are using np.r_ ...
python|arrays|numpy|vectorization|mask
1
358,355
53,705,819
How do I create a Dataframe_new in python from an existing Dataframe_old.
<p>My apologies in advanced if this type of question exists, I am very new to stack overflow, I tried my best to see if this question has been answered already.</p> <p>To give you some context. I have a test with 100 images of hands, each image has the same set of possible answers to select from. eg:</p> <blockquote>...
<p>I would create <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow noreferrer">dummies</a> of the variables and then group the data by <code>question_id</code> and sum up the columns:</p> <pre><code>In [1]: import pandas as pd In [2]: df = pd.read_csv('~/Desktop/s...
python|pandas|for-loop|pivot-table
1
358,356
53,430,914
Python vectorization of matrix-vector operation
<p>I have a Matrix A with shape (2,2,N) and a Matrix V with shape (2,N)</p> <p>I want to vectorize the following:</p> <pre><code>F = np.zeros(N) for k in xrange(N): F[k] = np.dot( A[:,:,k], V[:,k] ).sum() </code></pre> <p>Any way this can be done with either tensordot or any other numpy function without explicit...
<p>With <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a> -</p> <pre><code>F = np.einsum('ijk,jk-&gt;k',A,V) </code></pre> <p>We can optimize it further with <code>optimize</code> flag (check docs) set as <code>True</code>.</p>
python|performance|numpy|vectorization|tensordot
2
358,357
53,595,993
day of Year values starting from a particular date
<p>I have a dataframe with a date column. The duration is 365 days starting from 02/11/2017 and ending at 01/11/2018.</p> <pre><code> Date 02/11/2017 03/11/2017 05/11/2017 . . 01/11/2018 </code></pre> <p>I want to add an adjacent column called Day_Of_Year as follows:</p> <pre><code>Date ...
<p>First convert column <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> and then subtract <code>datetime</code>, convert to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.days.html" rel="nofol...
python-3.x|pandas|datetime|dataframe
4
358,358
53,536,468
CNN image classification: accuracy values shakes greatly
<p>I try 2 class (dog/cat) classification with cnn. But I found its graph of training is strange. Why accuracy values shakes greatly? And is it correct training?</p> <p>optimizer: adam learning rate: 1e-4</p> <p>network: <a href="https://gist.github.com/elect000/130acbdb0a3779910082593db4296254" rel="nofollow norefer...
<p>Likely your learning rate is too high. When the learning rate is too high, the network takes large leaps when changing the weights, and this can cause it to overshoot the local minimum it's approaching.</p> <p>Have a read of this article for a better description, and a nice diagram: <a href="https://www.quora.com/...
tensorflow|deep-learning|classification|conv-neural-network
1
358,359
53,482,228
Load data into pandas dataframe into ms sql python
<p>I'm trying to built a Python model within MS SQL SERVER 2017. I've attempted to use some tutorials but the result was far from expected. I'm wondering what's wrong with this script (loading SQL Table into pandas dataframe):</p> <pre><code>USE PREPRESS_TMP; GO EXEC sp_execute_external_script @language=N'Python'...
<p>You're using Express Edition right? See this: <a href="https://docs.microsoft.com/en-us/sql/sql-server/editions-and-components-of-sql-server-2017?view=sql-server-2017" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/sql/sql-server/editions-and-components-of-sql-server-2017?view=sql-server-2017</a>. There'...
python|sql-server|pandas|dataframe
1
358,360
53,419,474
Pytorch: nn.Dropout vs. F.dropout
<p>There are two ways to perform dropout:</p> <ul> <li><code>torch.nn.Dropout</code></li> <li><code>torch.nn.functional.Dropout</code></li> </ul> <p>I ask:</p> <ul> <li>Is there a difference between them?</li> <li>When should I use one over the other?</li> </ul> <p>I don't see any performance difference when I switched...
<p>The technical differences have already been shown in the other answer. However the main difference is that <code>nn.Dropout</code> is a torch Module itself which bears some convenience:</p> <p>A short example for illustration of some differences: </p> <pre class="lang-py prettyprint-override"><code>import torch im...
python|deep-learning|neural-network|pytorch|dropout
89
358,361
53,484,701
Pyinstaller does not properly include numpy in Mac bundle
<p>If I include numpy in my script the bundle application does not even open. However, if I run the application from the console everything is fine. So:</p> <p><code>pyinstaller -w myScript.spec</code> </p> <p>with <code>import numpy as np</code> in one of the modules does not create a proper executable. However:</p>...
<p>I installed miniconda and then created an environment with numpy 1.15.4, Pyinstaller 3.4 and python3.7.1. Within the environment, I can create the bundle app with no problem.</p> <p>However, the bundle app goes to 600MB. I will start a new question regarding how to reduce the size of the bundle app.</p>
python-3.x|macos|numpy|executable|pyinstaller
0
358,362
53,724,137
How to count the number of times each value in a tensor occurs with Tensorflow.js?
<p>I have a 1D tensor containing integers, for example [3,2,1,2,1,2,3,1,1,], and I wanna count how many times each integer occurs. I want the output represented with another 1D tensor, ie for the tensor above the output would be [0,4,3,2].</p> <p>I know this can be done in the Python API for Tensorflow, for example us...
<p>I found a solution by using tf.oneHot to create tensors with only a 1 at the index given by each element in the 1D tensor and zeros everywhere else, ie of the form [0,0,1,0] for a "2" in the 1D tensor, and then summing the output along the 0th axis. </p> <p>The code is</p> <pre><code> const amounts = tf.tensor1...
javascript|tensorflow|tensorflow.js
3
358,363
53,763,758
Trouble using transforms.FiveCrop()/TenCrop() in PyTorch
<p>I am trying to increase my CNN’s performance and thus i decided to “play” with some transformations in order to see how they affect my model. I read that FiveCrop() and TenCrop() might help because they generate extra data to train on. However, when i try to train the model, using one of the transformations mentione...
<p>Right, your error is coming from <code>transforms.ToTensor()</code>, which is directly downstream of your <code>TenCrop</code> in the composed transformation. It expects an image but gets a tuple of crops instead. You should follow a procedure similar to the one shown in the documentation not only for testing but al...
deep-learning|computer-vision|pytorch
1
358,364
53,363,819
Pandas: Split a Dataframe into separate Dataframes based on certain Column's string values
<p>Haven't found any answers that I could apply to my problem so here it goes:</p> <p>I have an initial dataframe of images that I would like to split into two, based on the description of that image, which is a string in the "Description" column.</p> <p>My problem issue is that not all descriptions are equally writt...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="noreferrer"><code>str.contains</code></a> for boolean mask - then filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="noreferrer"><code>boolean indexing</co...
python|string|pandas|dataframe
8
358,365
53,789,073
Python Adding a Column while using Usecol
<p>I'm hoping this is rather simple to accomplish but I'm having issues since I'm selecting columns from a text file but also want to add part of my file name as the last, or fourth, column. Naturally, I'm getting an error for the "Expected Axis."</p> <p>Below is my code:</p> <pre><code>import pandas as pd files = ('...
<p>IIUC, try:</p> <pre><code> df['Assign Date'] = files[-12:-4] </code></pre> <p>Or if you want datetime dtype:</p> <pre><code>df['Assign Date'] = pd.to_datetime(files[-12:-4]) </code></pre>
python|pandas|parsing|text|substring
1
358,366
53,526,351
How to expand a dataframe whoes rows contains list of values?
<pre><code> c1 c2 c3 0 [1, 2] [[a, b], [c, d, e]] [[aff , bgg], [cff, ddd, edd]] </code></pre> <p>I want the output to be like :</p> <pre><code> c1 c2 c3 0 1 a aff 1 1 b bgg 2 2 c cff 3 2 d ddd 4 2 e edd </code></...
<p>You can use <code>np.repeat()</code> and <code>chain.from_iterable()</code>:</p> <pre><code>df = pd.DataFrame({'c1': np.repeat(df['c1'].values[0], [len(x) for x in (chain.from_iterable(df['c2']))]), 'c2': list(chain.from_iterable(chain.from_iterable(df['c2']))), 'c3': list(chain.from_iterable(chain.from_ite...
python|pandas
2
358,367
53,476,756
ifelse statement in python similar to R
<p>Is there any <code>ifelse</code> statement in python similar to R? I have a pandas.core.series.Series <code>ds</code> of length 64843. I need to take log of each data point of this series. Some of the value in series are 0. In R I could write </p> <pre><code>ifelse(ds==0,0,log(z)) </code></pre> <p>But in python I...
<p>I believe you need <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> generally, but for <code>log</code> is possible add parameter <code>where</code> to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html" r...
python|pandas
2
358,368
53,378,392
How to open, delete columns and save a xls file in python
<p>I need to know how to open a xls file that is already made, I want to delete some columns and then save the file. This is what I have but I get an error when I want to delete the columns. How do I use the DataFrame function to delete columns and then save.</p> <p><strong>Read in excel file</strong></p> <pre><code>...
<p>Without seeing your dataset and error it is hard to tell what is going on. See <a href="http://See%20How%20to%20Ask%20and%20how%20to%20create%20a%20Minimal,%20Complete,%20and%20Verifiable%20example." rel="nofollow noreferrer">How to Ask</a> and <a href="https://stackoverflow.com/help/mcve">how to create a Minimal, C...
python|excel|pandas
0
358,369
53,678,336
Negative dimension size caused by subtracting 3 from 2 for 'maxpool1/MaxPool' (op: 'MaxPool')
<p>I have implemented squeezenet model for image classification in tensorflow like this : </p> <pre><code> net = conv2d(images, 96, [7, 7], stride=2, scope='conv1') net = max_pool2d(net, [3, 3], stride=2, scope='maxpool1') net = fire_module(net, 16, 64, scope='fire2') net = fire_module(net, 16, 64, scop...
<p>I suspect that <code>conv2d</code> is using <code>padding='VALID'</code> (no padding), perhaps you need <code>'SAME'</code> or <code>'same'</code>. Since the value is not given in the code, I just list the possible padding confusions in <code>conv2d</code> and <code>max_pool</code> defined in tensorflow. The default...
python|tensorflow|deep-learning
2
358,370
53,705,051
Fix date strings with days and months interchanged in certain rows
<p>I m trying to upload some data from a csv file and find the values for date and month get interchanged.</p> <p>Given below is how the data looks:</p> <pre><code>id,date 1001,09/10/2018 1002,20/09/2018 1003,09/05/2018 </code></pre> <p>All of the dates are from September but as seen they are interchanged in differe...
<p>I've figured out a neat little trick using <code>str.extract</code> and <code>pd.to_datetime</code> to do this quickly and efficiently:</p> <pre><code>m = df.date.str.extract(r'(?:(09)/(\d+))')[1].astype(int) &gt; 31 df['date'] = [ pd.to_datetime(d, dayfirst=m) for d, m in zip(df.date, m)] id date 0...
python|pandas|datetime
2
358,371
53,356,506
Evaluating logistic regression using cross validation and ROC
<p>I am trying to evaluate logistic regression using the AUROC curve and and cross-validate my scores. When I don't cross-validate I have no issues, but I really want to use cross validation to help decrease bias in my method.</p> <p>Anyway, below is the code and error term I get for the beginning part of my code:</p>...
<p>Please add more details so it can be truly examined. Preferably (and actually required) a piece of code that one can run to see the error.</p> <p>From first view, you take a pandas dataframe and feed it into the model, and that is done incorrect. See the following lines that are correct for retrieving data and feed...
python|scikit-learn|logistic-regression|cross-validation|sklearn-pandas
0
358,372
53,644,942
numpy loadtxt for 2D array
<p>I was loading iris dataset using loadtxt function of numpy and expected the shape of the ndarray so returned to be (150,5), but the shape so returned comes out to be (150,).So apparently the loadtxt method is storing the 2D array as list of rows. How can I make the loadtxt method return the data as 2D array.Please d...
<p>Look at the <code>loadtxt</code> docs for <code>dtype</code>:</p> <pre><code>Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array. In this case, the number of columns used must ma...
python-3.x|numpy|deep-learning|computer-vision
2
358,373
53,644,198
Choosing 3 (or n) observation from given index
<p>I'm trying to take the 3 highest observations for each index. For instance, I have</p> <pre><code>census=pd.Series([2000,4432,5435,43252,63463,423432,3525,54353,6363]) census.index=['AL','AL','AL','AL','AK','AK','AK','AK','AK'] </code></pre> <p>I want to get 3 highest observation for AL and AK and get it as a dif...
<p>You can do <code>census.groupby(level=0).nlargest(3)</code></p> <p>Thanks @coldspeed</p>
python|pandas|indexing
0
358,374
53,491,906
Index error while fitting polynomial to data
<h1>Index error while trying to fit a order&gt;1 polynomial to the data :</h1> <pre><code>import numpy as np from scipy.optimize import curve_fit x = b #1D array for X Axis y = c #1D array for Y Axis def func(x, a, b,c): return ((a*(x**2)) + b*x + c) iniguess = [0,0.038,13.99] param, pcov = curve_fit(func, ...
<p>As @Ben.T pointed out, the problem is that <code>param[3]</code> in your code should be <code>param[2]</code>. When you have a list of arguments like <code>param</code> that you're passing to a function one after the other in order (ie <code>func(..., param[0], param[1], param[2], ...)</code>), you can instead just ...
python-3.x|numpy|scipy|curve-fitting
1
358,375
53,418,151
Update Column A where Column B has Value C in Pandas DataFrame
<p>Good morning, </p> <p>I'm trying to update a DataFrame based on the contents of two columns and am running into issues. </p> <p>Specifically, I have a column called <code>IP</code>, another called <code>VISITTIME</code>. I've added two columns called <code>OLDEST</code> and <code>NEWEST</code> which need to contai...
<p>Depending on your version of pandas (I know in version > 0.22.0), there is a method called <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.update.html" rel="nofollow noreferrer">Dataframe.update</a>.</p> <p>That should provide some examples, but a few warnings:</p> <ul> <li>You ne...
python|pandas|dataframe
0
358,376
53,570,725
Inverse Score in Python
<p>I have a dataframe as follows,</p> <pre><code>import pandas as pd df = pd.DataFrame({'value': [54, 74, 71, 78, 12]}) </code></pre> <p>Expected output,</p> <pre><code>value score 54 scaled value 74 scaled value 71 scaled value 78 50.000 12 600.00 </code></pre> <p>I want to assign a score...
<p>Not sure what you want to achieve, maybe you could provide the exact expected output for this input. But if I understand well, maybe you could try</p> <pre><code>import pandas as pd df = pd.DataFrame({'value': [54, 74, 71, 78, 12]}) min = pd.DataFrame.min(df).value max = pd.DataFrame.max(df).value step = 550 / (m...
python|pandas
2
358,377
53,433,795
Pandas merging two dataframes with different number of multiindices
<p>Welcome, I have a simple question, to which I haven't found a solution.</p> <p>I have two dataframes <code>df1</code> and <code>df2</code>:</p> <ul> <li><code>df1</code> contains several columns and a multiindex as <code>year-month-week</code></li> <li><code>df2</code> contains the multiindex <code>year-week</code> ...
<p>Eventually i solved with with removing the multiindex and doing a good old inner join on the two columns and then recreating the multiindex at the end. Here are the sniplets:</p> <p>df=df.reset_index()</p> <p>df2=df2.reset_index()</p> <p>df['year']=df['year'].apply(int)</p> <p>df2['year']=df2['year'].apply(int)...
python|pandas|dataframe
0
358,378
53,481,961
Contour plot of multivariate distribution
<p>I have a matrix of data (Xa.shape = 100x2) related to class A and another one for class B. I created both using the code below and I want to make a contour plot of the data. But what I tried doesn't work and just creates a blue picture. How do I create a proper contour plot of such data?</p> <pre><code>N = 1000 me...
<p><strong>Input:</strong> two-dimensional data points - <code>Xa</code> is of shape [N, 2]. These are N poins in 2D space.</p> <p><strong>Desired output:</strong> contour plot in two dimensions. <code>countourf</code> is the right tool for that, but take note of the <a href="https://matplotlib.org/api/_as_gen/matplot...
python|numpy|matplotlib|plot|distribution
2
358,379
53,671,706
Different format in pandas date column - data type of column vs. row
<p>I have a pd DataFrame column with date values that are in different Format. Examples are 'YYYY-MM-DD hh:mm:ss' and 'DD.MM.YYYY' or even 'DD.MM.' I'd like to convert them all to one Format (e.g., 'YYYY-MM-DD') and have (among many things) tried </p> <pre><code>df[~df.date.str.contains('(\d{4})-(\d{2})-(\d{2}) (\d{2}...
<pre><code>def findIndex(x): try: pd.to_datetime(x).strftime('%m/%d/%Y') return except: return True df.date.apply(lambda x: findIndex(x)) </code></pre> <p>Now you can get all the index with <strong>weird</strong> formats. Hope this helps.</p>
python|regex|pandas|date|types
1
358,380
53,486,372
How to convert object to datetime Index
<p>I have dataframe with colum <code>date</code>. The values of the <code>Date</code> column is like <code>Index([2011-01-10], dtype='object')</code>. I want to convert to DateTime but I am not able to do this. I have tried <code>df["Date"] = pd.to_datetime(df["Date"])</code> but it did not work. Got an error <code>Typ...
<h3>Setup</h3> <pre><code>df = pd.DataFrame(dict(Date=[pd.Index(['2018-01-01'])] * 2)) df Date 0 Index(['2018-01-01'], dtype='object') 1 Index(['2018-01-01'], dtype='object') </code></pre> <hr> <h3>The Error</h3> <pre><code>df.Date = pd.to_datetime(df.Date) TypeError: &l...
python|pandas|datetime
3
358,381
53,457,004
Python_OSError: [Errno 28] No space left on device
<p>I have the following error while exporting pandas dataframe into csv file. I have enough space on my hard disk.</p> <pre><code>OSError: [Errno 28] No space left on device </code></pre> <p>What can be the reason for this? Many thanks in advance.</p>
<p>Late answer, but maybe usefull.</p> <p>I encountered a similar issue :</p> <pre><code>OSError: [Errno 28] No space left on device: </code></pre> <p>But, I have enough space:</p> <pre><code>$ df -h Sys. de fichiers Taille Utilisé Dispo Uti% Monté sur /dev/dm-0 5,6G 3,2G 2,1G 62% / udev...
python|pandas|out-of-memory
1
358,382
53,663,758
Saving list of many python variables into excel sheet while simultaneously keeping variable types defined?
<p>It's possible with xlsxwriter to save variables to existing excel files and read them after, though the problem is that the variables are stored as strings in my excel file. </p> <p>Let's say I have a list of many different variables with various types (pd.datetimerange, pd.df, np.arrays, etc.), if I save them to t...
<p>As per your comment, you can get <code>eval</code> to correctly process the symbols that are local to some module by passing the appropriate dict of locals into <code>eval</code>, along with your string. Here's a workable solution:</p> <pre><code>import pandas as pd def getlocals(obj, lcls=None): if lcls is No...
python|vba|pandas|parsing|xlsxwriter
5
358,383
17,444,655
Dynamically updating a graphed line in python
<p>I'm plotting a line using matplotlib and would like to update my line data as soon as new values are generated. However, once in the loop, no window appears. Even though the printed line indicates the loop is running.</p> <p>Here's my code:</p> <pre><code>def inteprolate(u,X): ... return XX # generate ini...
<p>You need to call <code>plt.pause</code> in your loop to give the gui a chance to process all of the events you have given it to process. If you do not it can get backed up and never show you your graph.</p> <pre><code># get new values and re-plot plt.ion() # make show non-blocking plt.show() # show the figure whi...
python|numpy|matplotlib
1
358,384
17,283,583
A fast way to fill an dataset with same values of compound data in h5py
<p>I have a large dataset of compound data in a hdf file. The Type of the compound data looks as following:</p> <pre><code> numpy.dtype([('Image', h5py.special_dtype(ref=h5py.Reference)), ('NextLevel', h5py.special_dtype(ref=h5py.Reference))]) </code></pre> <p>With that I create a dataset with re...
<p>You can use either numpy <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">broadcasting</a> or a combination of <code>numpy.repeat</code> and <code>numpy.reshape</code>:</p> <pre><code>my_dtype = numpy.dtype([('Image', h5py.special_dtype(ref=h5py.Reference)), ('Nex...
numpy|hdf5|h5py
0
358,385
17,307,299
Filling missing values using numpy.genfromtxt
<p>Despite the advice from the previous questions:</p> <p><a href="https://stackoverflow.com/questions/12274709/9999-as-missing-value-with-numpy-genfromtxt">-9999 as missing value with numpy.genfromtxt()</a></p> <p><a href="https://stackoverflow.com/questions/3761103/using-genfromtxt-to-import-csv-data-with-missing-v...
<p>Using <a href="http://pandas.pydata.org/" rel="noreferrer">pandas</a>:</p> <pre><code>import pandas as pd df = pd.read_table('data', sep='\s+', header=None) df.fillna(0, inplace=True) print(df) # 0 1 2 # 0 1 2 3 # 1 4 5 6 # 2 7 8 0 </code></pre> <p><code>pandas.read_table</code> replaces missing dat...
python|parsing|numpy|genfromtxt
8
358,386
17,413,624
How to organize values in a numpy array into bins that contain a certain range of values?
<p>I am trying to sort values in an <code>numpy</code> array so that I can store all of the values that are in a certain range (That could probably be phrased better). Anyway ill give an example of what I am trying to do. I have an array called bins that looks like this:</p> <pre><code>bins = array([11,11.5,12,12.5,13...
<p>Numpy has some pretty powerful bin counting functions.</p> <pre><code>&gt;&gt;&gt; binplace = np.digitize(avgs, bins) #Returns which bin an average belongs &gt;&gt;&gt; binplace array([1, 6, 2, 3, 5, 4, 1, 4, 6, 6, 2, 3, 5, 6, 3, 1, 2, 3, 5, 7, 5, 3, 4]) &gt;&gt;&gt; np.where(binplace == 1) (array([ 0, 6, 15]),) ...
python|arrays|numpy|bins
14
358,387
17,352,244
numpy.savetxt without hash mark at beginning of header line
<p>When I try to save a matrix with header, a hash mark and a space (# ) appear on the first line:</p> <p>input:</p> <pre><code>np.savetxt(filename,data, fmt='%i %i %i %i %s',delimiter='\t',header="a\tb\tc\td\te") </code></pre> <p>output:</p> <pre><code># a b c d e 0 0 0 0 bla 0 0 0 0 bla 1 ...
<p>it inserts the # because that line is a comment, and the default character for comments is the symbol #, as you can read in the documentation <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html">here</a>.</p> <p>If you want to get rid of it, pass <code>comments=''</code> as option to sav...
python|numpy
74
358,388
19,955,686
Fit a curve for data made up of two distinct regimes
<p>I'm looking for a way to plot a curve through some experimental data. The data shows a small linear regime with a shallow gradient, followed by a steep linear regime after a threshold value.</p> <p>My data is here: <a href="http://pastebin.com/H4NSbxqr" rel="noreferrer">http://pastebin.com/H4NSbxqr</a><br> <img sr...
<p>If you don't have a particular reason to believe that linear + exponential is the true underlying cause of your data, then I think a fit to two lines makes the most sense. You can do this by making your fitting function the maximum of two lines, for example:</p> <pre><code>import numpy as np import matplotlib.pypl...
python|numpy|matplotlib|scipy|curve-fitting
24
358,389
20,230,384
Find indexes of matching rows in two 2-D arrays
<p>Suppose that I have two 2-D arrays as follows:</p> <pre><code>array([[3, 3, 1, 0], [2, 3, 1, 3], [0, 2, 3, 1], [1, 0, 2, 3], [3, 1, 0, 2]], dtype=int8) array([[0, 3, 3, 1], [0, 2, 3, 1], [1, 0, 2, 3], [3, 1, 0, 2], [3, 3, 1, 0]], dtype=int8) </code></pre> <p...
<p>This is an all <code>numpy</code> solution - not that is necessarily better than an iterative Python one. It still has to look at all combinations.</p> <pre><code>In [53]: np.array(np.all((x[:,None,:]==y[None,:,:]),axis=-1).nonzero()).T.tolist() Out[53]: [[0, 4], [2, 1], [3, 2], [4, 3]] </code></pre> <p>The inter...
python|numpy
9
358,390
20,011,494
Plot Normal distribution with Matplotlib
<p>please help me to plot the normal distribution of the folowing data:</p> <p>DATA:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172, 187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 15...
<ul> <li><strong>Note: This solution is using <code>pylab</code>, not <code>matplotlib.pyplot</code></strong></li> </ul> <p>You may try using <code>hist</code> to put your data info along with the fitted curve as below:</p> <pre><code>import numpy as np import scipy.stats as stats import pylab as pl h = sorted([186, 1...
python|numpy|matplotlib|plot|scipy
97
358,391
20,277,416
Pandas Dataframes: Large # of dict values, way to print?
<p>I'm trying to convert a default dict filled with a large amount of data into a pandas dataframe. When the # of values in the dictionary is small (say, ten), I get something like:</p> <pre><code> Obama Romney dates 0 47.5 41.5 2/01/2011 1 47.5 41.5 2/02/2011 2 47.5 41.5 2/03/201...
<p>Check out the <code>set_option</code> function:</p> <pre><code>import pandas as pd pd.set_option('max_rows', 150) </code></pre>
python|dictionary|pandas
3
358,392
19,917,545
Comparing two pandas dataframes for differences
<p>I've got a script updating 5-10 columns worth of data , but sometimes the start csv will be identical to the end csv so instead of writing an identical csvfile I want it to do nothing... </p> <p>How can I compare two dataframes to check if they're the same or not?</p> <pre><code>csvdata = pandas.read_csv('csvfile....
<p>You also need to be careful to create a copy of the DataFrame, otherwise the csvdata_old will be updated with csvdata (since it points to the same object):</p> <pre><code>csvdata_old = csvdata.copy() </code></pre> <p>To check whether they are equal, you can <a href="https://stackoverflow.com/questions/19322506/pan...
python|python-2.7|pandas
82
358,393
20,291,900
Python -- Matplotlib redrawing lines without previous lines remaining
<p>This class plots a curve in Matplotlib. The user mouse input section changes the <code>set_data()</code> for several <code>x,y</code> coordinates. The <code>P</code> and <code>Q</code> are resetting properly, it seems. However, when the <code>R</code> is not set with calculations using those same methods (<code>s...
<p>I've simplified the problem to its minimum, and by searching <code>set_xdata</code> on SO and following the link provided by <em>tcaswell</em>, I found <a href="https://stackoverflow.com/questions/13106164/update-matplotlib-plot">this subject</a>, that is really clear.</p> <p>Here's the demo code, written in 5 minu...
python|math|python-2.7|numpy|matplotlib
4
358,394
19,967,744
Updating values in a DataFrame
<p>I'm munging some time series data that was stored poorly. </p> <p>There is a column which I have made the index that has time stamps that are mostly every 15 minutes, but some are shorter. There are also <code>start_sec</code> and <code>end_sec</code> columns that give what part of the interval the row is for.</p...
<p>Instead of using your <code>df.index</code> syntax, try this:</p> <pre><code>df.start_sec[i] = df.start_sec[i] * scale df.end_sec[i] = df.end_sec[i] * scale </code></pre> <p>Or even:</p> <pre><code>df.start_sec[i] *= scale df.end_sec[i] *= scale </code></pre> <p>In my tests, the frame is <strong>not</strong> ass...
python|pandas
0
358,395
20,104,522
Using NumPy to convert user/item ratings into 2-D array
<p>With performing some classificion using some user/item/rating data. My issue is how to I convert these 3 columns into a matrix of user(row), item(columns) and the ratings data populating the matrix.</p> <pre><code>User Item ItemRating 1 23 3 2 204 4 1 492 2 3 23 4 </code></pre> <p>and ...
<p>This is pivot, if I get your idea right, with pandas it will be as follows.</p> <p>Load data:</p> <pre><code>import pandas as pd df = pd.read_csv(fname, sep='\s+', header=None) df.columns = ['User','Item','ItemRating'] </code></pre> <p>Pivot it:</p> <pre><code>&gt;&gt;&gt; df User Item ItemRating 0 1 ...
python|numpy|multidimensional-array|pandas
19
358,396
6,794,221
Matlab to Python sparse matrix conversion , overcoming the zero index problem
<p>I have an N x N sparse matrix in Matlab, that has cell values indexed by (r,c) pairs such that r and c are unique id's. </p> <p>The problem is, that after converting this matrix into Python, all of the indices values are decremented by 1. </p> <p>For example:</p> <pre><code>Before After (210...
<p>Thank you all for the good advice. </p> <p>I decided to stick with Python. I do most of my data transfers between Matlab and Python using text files now.</p>
python|numpy|scipy|sparse-matrix
2
358,397
6,915,106
Saving a Numpy array as an image (instructions)
<p>I found my answer in a previous post: <a href="https://stackoverflow.com/questions/902761/saving-a-numpy-array-as-an-image">Saving a Numpy array as an image</a>. The only problem being, there isn't much instruction on using the PyPNG module.</p> <p>There are only a few examples online-- <a href="http://packages.py...
<p>You might be better off using PIL:</p> <pre><code>from PIL import Image import numpy as np data = np.random.random((100,100)) #Rescale to 0-255 and convert to uint8 rescaled = (255.0 / data.max() * (data - data.min())).astype(np.uint8) im = Image.fromarray(rescaled) im.save('test.png') </code></pre>
python|image|numpy
40
358,398
15,915,719
Python on Aptana Studio with Numpy?
<p>I need help setting up aptana studio with python numpy. </p> <p>I already have python configured with the studio. I downloaded the numpy package from <a href="http://www.numpy.org/" rel="nofollow">http://www.numpy.org/</a> . </p> <p>How do I configure my IDE with this API? </p>
<p>So unless I am missing something myself, API would be the wrong term, 'Application programming interface' does not refer to libraries.</p> <p>Once you have numpy properly installed, just telling ipython or your code to 'import numpy' should make it usable in that code. There are also ways of just importing certain ...
python|numpy|configuration|aptana
0
358,399
15,900,755
create an array of shape (N,N)
<p>How do I create an numpy array of shape (120,120), with the first 7 values being 0.924 and the rest of the values being 0.53.I need this for a matrix in matplotlib</p>
<p>The fastest way is probably to create an empty array, fill it with a constant value, and update the few values that need to be updated:</p> <pre><code>&gt;&gt;&gt; x = np.empty((120, 120)) &gt;&gt;&gt; x.fill(0.53) &gt;&gt;&gt; x[0,:7] = 0.924 &gt;&gt;&gt; x array([[ 0.924, 0.924, 0.924, ..., 0.53 , 0.53 , 0.5...
list|numpy
3