« first day (857 days earlier)      last day (1331 days later) » 

12:16 AM
0
Q: Count Inversions Issue - Python

Sandeep I am not what is wrong with this algorithm to count the number of inversions. Please can someone look at this and point the issue def count_inv(nums): l_inv, r_inv = 0, 0 if len(nums) == 1: #print('Noting to do with', nums) return 0 else: mid = len(nums) /...

0
Q: Get values in numpy array either side of a specified value

Nathan ThomasI have a numpy array, provided at random, which for this example looks like: a = [10, 8, 6, 4, 2, 0, -2, -4, -6, -8, -10, 1] ideally, in this example, the values would be between -10 and 10 but this cannot be guaranteed (as above). I want to retrive the 2 values closest to zero, such that: b...

 
12:27 AM
0
Q: 3D numpy array in Theano

AlcuPalaI'm having a 3D NumpyArray which I want to through in a Keras Neural Network. Because of one hot encoding the array became a 3D array. [ [[0,1,0,0], [1,0,0,0]], [[0,0,0,1], [1,1,0,0]], [[0,0,1,0], [0,0,0,1]] ] Since Keras can only compute 2D arrays, my question is, how can...

 
12:44 AM
0
Q: Countdown Timer for Tests

AppleCrazyI created this countdown timer as a tool to count down the remaining time on a test a few months ago. However, I looked at the code today and it looks like it needs some improvement, but I'm not sure what to fix. Some problems I've already identified: It makes a call to a macOS-specific comman...

 
 
1 hour later…
1:58 AM
0
Q: How to remove the adjacent duplicate value in a numpy array?

user5779223Given a numpy array, I wish to remove the adjacent duplicate non-zero value and all the zero value. For instance, for an array like that: [0,0,1,1,1,2,2,0,1,3,3,3], I'd like to transform it to: [1,2,1,3]. Do you know how to do it? I just know arry.uniques but it would remove all the duplicate val...

 
2:10 AM
0
Q: Invoicing Program Python

Tommy#Invoice Entering Program Ebay print("Ebay Invoice Program\n") while True: file = input("Enter 0 to Quit. Enter S to Search The File. Press ENTER to Input new Entries *Case Sensitive*: " ) if file == "0": print("Exiting Program...") break elif file=="S": key...

0
Q: How to convert a column of type Series to datetime weekdays format in python?

AdeI have the following data and python code Time Started Date Submitted Status 10/29/2015 17:34 10/29/2015 17:34 Complete 10/29/2015 17:35 10/29/2015 17:35 Complete 10/29/2015 17:36 10/29/2015 17:37 Complete import pandas as pd from datetime import datetime, timedelta from p...

 
2:42 AM
0
Q: Sequential Matplotlib Animation of Pendulum Dynamics with Randomized Initial Conditions

NBCKLYThis question of generating sequential animations of dynamical systems with random initial conditions and plotting them on the same figure is asked in the context of the pendulum system described in Jake Vanderplas's Matplotlib Animation Tutorial. Suppose that I wanted to simulate 10 or 20 pendu...

 
3:02 AM
0
Q: I/O buffer error in numpy

BaktaawarI have a weight matrix (W) which is of size 400 x 8537. Each cell in W has some numeric value. Now I am trying to create another Y matrix of size 100 X8537 by the following analytical solution implemented in numpy. Here X is a 400 x 100 numeric matrix and P is a 300 x 8537 matrix , therefor...

 
3:27 AM
0
Q: Numpy 3D array arranging and reshaping

motahaI have a 3D numpy array that I need to reshape and arrange. For example, I have x=np.array([np.array([np.array([1,0,1]),np.array([1,1,1]),np.array([0,1,0]),np.array([1,1,0])]),np.array([np.array([0,0,1]),np.array([0,0,0]),np.array([0,1,1]),np.array([1,0,0])]),np.array([np.array([1,0,0]),np.array(...

 
4:01 AM
0
Q: np.ndarray with Periodic Boundary conditions

Alexander McFarlaneProblem To impose np.ndarray periodic boundary conditions as laid out below Details Wrap the indexing of a python np.ndarray around the boundaries in n-dimensions This is a periodic boundary condition forming an n-dimensional torus Wrapping only occurs in the case that the value returned is s...

 
4:56 AM
0
Q: optimize function that includes large matrix operations

bill_eI might do a poor job of explaining this, so I'll use an example somewhat similar to my problem, but here goes: I need to compute a complex operation (repeatedly) that is a function of only a few scalars, say, x1, x2 and x3. Then a matrix whose elements are determined by a function of x1, x2, x...

0
Q: Creating datetime in pandas from year and julian day

user308827 ad_name adl_name year JD 0 united_states_of_america colorado 2000 1 1 united_states_of_america colorado 2000 2 2 united_states_of_america colorado 2000 3 3 united_states_of_america colorado 2000 4 4 united_states_of_america colorado 2000 5 h...

 
5:14 AM
0
Q: Calculate the total counts using pandas pivot table

ProgRI have a dataframe like this, student class subject date status jack class-1 maths 20150101 fail jack class-1 maths 20150205 win jack class-1 maths 20150310 fail jack class-1 maths ...

 
5:35 AM
0
Q: How to change the datetime format in pandas

yomeDOB column sample value is in the format - 1/1/2016 which by default gets converted to object as shown below DOB object Converting to date format df['DOB'] = pd.to_datetime(df['DOB']) Date converts to 2016-01-26 dtype is DOB datetime64[ns] Now I want to convert this date f...

0
Q: Panda: How to pivot one column in rows into columns

samolGiven this dataframe feature score searchTerm 0 a 0.534509 pizza 1 b 0.586020 pizza 2 c 0.588972 pizza 3 a 0.566261 chinese 4 b 0.572405 chinese 5 c 0.489369 chinese 6 a 0.499068 thai 7 b 0.431068 thai 8 c 0.441617 thai Featu...

0
Q: Convert column containing string and NAN to list of integers in Pandas

MichaelI have a data frame that I read from a CSV file, which contains some columns that contain lists. However they end up as a strings in Pandas, like column B in this example. I would like to turn this column into a new column containing a list of integers. A couple of complications. 1) The origi...

0
Q: Caffe OSX boost error

user3543300I've installed all the dependencies to install caffe and followed the instructions online. I even downgraded my boost version to 1.57. However, I'm still getting boost errors that I can't seem to find an explanation for anywhere. Anyone have advice? I've tried boost 1.6 instead but I get similar ...

 
5:53 AM
0
Q: A CNN in Python WITHOUT frameworks

Shiva""" Convolutional Neural Network """ import numpy as np import sklearn.datasets import random import math from skimage.measure import block_reduce from scipy.signal import convolve import time def reLU(z): # activation function return z * (z > 0) """ ----------------------------...

0
Q: how to use pandas drop nan number, not drop all the row

liu gangthank you for watching just delete the nan element ,not delete all the rows. i hava a python dataframe list like : [[2.0, 3.0, 5.0, nan], [1.0, 3.0, 5.0, 6.0], [2.0, 5.0, nan, nan]] how can i use pandas to change it as follow : just delete the nan element [[2.0, 3.0, 5.0], [1.0, 3.0, 5.0,...

 
6:29 AM
0
Q: numpy argmax not getting all values from generator expression

Fabio Dalla LiberaThe output of the following import numpy as np print(np.argmax([i for i in range(0, 10)])) print(np.argmax(i for i in range(0, 10))) is 9 0 Why does argmax reduce the generator expression only once?

 
7:01 AM
-1
Q: Python decision tree exercise,map() function converting the non-numeric values to numbers?

Tejus Ramanuj I tried converting the non-numeric values to numeric values to compute a decision tree. But, the NaN value pops each and every time I call the map() function. Here's the code. x={'BS':1,'MS':2,'CODE CAMP':3,'PHD':4} df['education']=df['education'].map(x) And Here's the o/p I'm getting. Before...

 
7:14 AM
0
Q: "ImportError: cannot import name SkipTest" while importing numpy in python

ObaidI am having problem while importing numpy. Please fin below version information: # cat /etc/redhat-release CentOS release 6.5 (Final) # python -V Python 2.6.6 I have already installed numpy (re-installed several times) using pip. # pip install numpy DEPRECATION: Python 2.6 is no longer supp...

0
Q: Change mean pooling to max pooling in a framework-free CNN implementation with Python

ShivaI've implemented a simple CNN program with Python that can machine learn on the MNIST data set. I've implemented 3 layers: ConvPoolLayer, which convolves and then does mean pooling FullyConnectedLayer, which is a fully connected hidden layer SoftmaxLayer, which basically gives the softmax out...

1
Q: Sharing python modules between applications with git sub modules or svn:externals

Günther JenaIn our company we're using subversion. We have different python modules (own and third party) in different versions in use. The various applications we develop have various dependencies regarding the version of the shared modules. One possibility is using virtualenv installing the modules from ...

 
7:43 AM
0
Q: how to speed up this generator code

David Michael GangI want to speed up the following code, which is from an algorithm class. I get a list of 200000 nodes where every node is a tuple of the length of 24 where every item is either a 1 or 0. These items represent a graph where the distance between them is the hamming distance(number of bits that t...

-1
Q: How to tune the frequency of a sine curve in python?

Ébe IsaacThe objective is to draw a sine curve with a predetermined number of periods for a given range in x. I'm just not sure how to tune the frequency accordingly. This is the minimum working example: import numpy as np import matplotlib.pyplot as plt r = 25 # Range for the x axis peaks = 9 # No...

0
Q: Adjusting mesh xy scale contour plot matplotlib

L.BouwmeesterI'm trying to set up a contour plot but the figure ends up looking like this: fig1. I think it's because the y axis goes from around 10 to 80 units and the x only 4 to 9 units and the mesh is square so each unit is scaled the same on the x and y axis. How can I change the scaling of the x axis to...

0
Q: Pandas: check multiple column indices for existence

Hendrik WieseIs there a more sophisticated way of doing if numpy.all(map(lambda c: c in df.columns, ['Column 1', 'Columns 2'])): do_something()

 
8:18 AM
0
Q: Conversion of NumPy array to Java readable format

user3550694I am trying to convert few numpy arrays to java readable format. Different arrays may have data types as uint8, float16, float32 etc. How do I accomplish such conversion without changing the size of the array, while it is being stored on the disk.

 
8:40 AM
0
Q: Efficient Vectorized Indexed Sum in Numpy

NewmuSay I have 3 arrays a = [1, 1, 1, 1, 1] b = [0, 0, 2, 2] c = [1, 2, 3, 4] I want to vectorize adding to a at b's indexes the values in c for i in range(len(b)): a[b[i]] += c[i] which results in: [4, 1, 8, 1, 1] One way to vectorize is to sum values of c that share the same value of b...

0
Q: python error setting an array element with a sequence

edwinI trying to explore different classifier for this example in scikit-learn website http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html. However, the code below produced an error: ValueError: setting an array element with a sequence. from sklearn.feature_extraction....

0
Q: Plotting vectors of different length - python

beginhI want to plot points of an array 'points' in this manner: points = [[10,15], [20,30],[98,94]] y = np.ones_like(points)*[[0],[1],[2]] plt.plot(points,y,'o') plt.show() How to do it if the vectors in array 'points' were of different length such as here?: points = [[10,15,25],[],[98,94]] y = np...

0
Q: Properties Manager

user110071I'm trying to do a property manager that loads a yaml file and stores all the properties in a db. I'm not sure if this would be the right approach. Any suggestions? # -*- coding: utf-8 -*- """Properties getters. Module to obtain the application properties. """ from ..core import properties, ...

0
Q: How to store list of Pandas data frame for easy access

ProgRI have a list of data frame, df1 = Stock Year Profit CountPercent AAPL 2012 1 38.77 AAPL 2013 1 33.33 df2 = Stock Year Profit CountPercent GOOG 2012 1 43.47 GOOG 2013 1 32.35 df3 = Stock Year Profit CountPerc...

0
Q: Plot 2 boxplots , each from different pandas dataframe in a figure ?

KrishnaI want to plot boxplots for each of the dataframes side by side. Below is an example dataset. data 1 : id,type,activity,feature1 1,A,ACTIVE,12 2,B,INACTIVE,10 3,C,ACTIVE,9 data 2: id,type,activity,feature1 1,A,ACTIVE,13 2,B,INACTIVE,14 3,C,ACTIVE,15 First boxplot should be to plot the feature1...

0
Q: How to plot vectors of different length

eReSI plot array of points in such a way: pts = [[12,25], [28,45],[72,27]] y = np.ones_like(pts)*[[0],[1],[2]] plt.plot(pts,y,'o') plt.show() I would like to plot it if vectors were of different length, eventually empty. In this way: pts = [[12,25, 38],[],[72,27]] y = np.ones_like(pts)*[[0],[1],[...

 
9:16 AM
0
Q: astropy.fits: Manipulating image data from a fits Table? (e.g., 3072R x 2C)

user3125347I'm currently having a little issue with a fits file. The data is in table format, a format I haven't previously used. I'm a python user, and rely heavily on astropy.fits to manipulate fits images. A quick output of the info gives: No. Name Type Cards Dimensions Format 0...

 
9:29 AM
0
Q: Initializing a big matrix with numpy taking way too long

Okabe KimtaroI am working in python and I have encountered a problem: I have to initialize a huge array (21 x 2000 x 4000 matrix) so that I can copy a submatrix on it. The problem is that I want it to be really quick since it is for a real-time application, but when I run numpy.ones((21,2000,4000)), it takes ...

0
Q: Find average mean with condition using python

Arseniy KrupeninI have data, there are a visits of url and time of every visits. I need to find average duration. diff_time - it's the difference between two neigbors dates(in second). diff_time 0 12 44 2 2 13 3 208 2 21 I need write function, that can determine parameters a, b automatically, where for el i...

0
Q: Data construct for machine language

Nijar HossainI am newbie in python.currently i am developing some prediction of data using machine language of Python using technique SVM (Support Vector Machine).But i need a machine language data for system bug's log file to predict the future bug of the system.Every help is much appreciated.thanks in advance

 
9:59 AM
0
Q: How to convert csr matrix to numpy array?

ishpreetI am calculating TF-IDF of a document. I used TfidfVectorizer to obtain the same. The output of vectorizer.fit_transform() function is a scipy.sparse.csr.csr_matrix. I want to store the output in a numpy array or write the output in a file. And vectorizer.fit_transform().toarray() is not working....

 
10:17 AM
0
Q: Determine adjacent regions in numpy array

dv2I am looking for the following. I have a numpy array which is labeled as regions. Each region has its own index number. A simplified version with 3 regions looks like this: x = np.array([[1, 1, 1], [1, 1, 2], [2, 2, 2], [3, 3, 3]], np.int32) output: array([[1, 1, 1], [1, 1, 2], ...

0
Q: Drop pandas dataframe rows based on groupby() condition

Sasha KorekovThere is a pandas dataframe on input: store_id item_id items_sold date 1 1 0 2015-12-28 1 2 1 2015-12-28 1 1 0 2015-12-28 2 2 0 2015-12-28 2 1 1 2015-12-29 2 ...

0
Q: Logical MultiIndexing in Pandas

beginneRIs there a way to extract all values of B for index One where C is greater than zero? So I want to extract the values -0.22 and -1.21. import numpy as np import pandas as pd arrays = [np.array(['One','One','One','Two','Two','Two']),np.array(['A','B','C','A','B','C'])] df = pd.DataFrame(np.random...

0
Q: matplotlib plot of complex valued function

TheguyIn matlab plot of a complex vector will result in a plot of imaginary vs real part. Is there an equivalent function in matplotlib? Obviously this will work: def plotcomplex(c, *args): plot(real(c), imag(c), args) but does it already exist?

0
Q: Pandas error TypeError: data type not understood

elksie5000I've been trying to slice a pandas dataframe using boolean indexing code like: subset[subset.bl.str.contains("Stoke City")] The column bl is of object type. Yet when I run it, I have an error: TypeError: data type not understood How do I go about fixing it?

0
Q: Flatten numpy array without double for loop

BobI have a 2-d matrix. For the purposes of this example, let's say it is a random matrix >>> a = np.random.randn(5, 7) >>> a array([[-0.37279322, 0.28619523, -0.05309901, 0.26010327, 0.1846693 , 0.33112176, 0.75814911], [ 1.57001151, -0.86831693, -0.20576395, 1.46450855, -0.01631132, 3...

 
10:47 AM
0
Q: pylab imports from shell but not when running .py file from cmd

TomsRI am trying to run a *.py file from the cmd which contains an import pylab statement, and I get an import error saying 'No module named pylab', however when running the same statement from the python shell it works fine. What could be wrong?

0
Q: - Ipython -cannot change pyplot.style.use

user1649114I'm using Ipython to graph some metrics. First of all, below are the version i'm using -- version information -- IPython.__version__,pd.__version__, matplotlib.__version__ ('4.0.3', u'0.17.1', '1.5.1') -- end version information What I'm doing is display two figures side-by-side to allow so...

0
Q: Prime number checker python3

Iso1234I have updated my code from the last time it got reviewed (Prime number calculator in Python 3.4.1). If anyone has some more suggestions on how I can improve this and/or make it faster it would be appreciated! def is_prime(num): '''Calculates whether num is a prime number, if it is retur...

0
Q: insert numpy.float64 element in a numpy array

BaRudI am trying to insert a numpy float in a numpy ndarray. The Code and the output is: dos = np.sum(atom[:, :, 1:],axis=0) print("type(dos)") print(type(dos)) print("dos.shape") print(dos.shape) print("dos[15] Before") print(dos[15]) print("type(atom[1,0,0])") print(type(atom[1,0,0])) print("atom[1...

0
Q: Adjusting view in matplotlib figure taking too long

DmanI have plotted a figure in matplotlib and when I open the figure and try to adjust the viewing angle for the figure, there is about one second delay between my mouse movement and the corresponding movement of the figure. Is there a way to reduce this lag?

0
Q: Differences in numba outputs

Mario GonzálezI implemented a basic nearest-neighbors search in my study work. The fact is that the basic numpy implementation is working well, but just adding the '@jit' decorator (compiling in Numba), the outputs are differents (it duplicates some neighbors in the end for some unknown reason...) Here is the...

 
11:18 AM
1
Q: Append existing excel sheet with new dataframe using python pandas

brandogI currently have this code. It works perfectly. It loops through excel files in a folder, removes the first 2 rows, Then saves them out as individual excel files, and it also saves the the files in the loop as an appended file. Currently the appended file overwrites the existing file each time ...

 
11:31 AM
0
Q: Error with connecting to wsdl?

user7172I do : base64string = base64.encodestring('%s:%s' % (userid, passwd)).replace('\n', '') authenticationHeader = { "Authorization" : "Basic %s" % base64string, "Accept-Encoding" :"gzip,deflate", "Content-Length" :"1086", "Host" :"uslugaterytws1test.stat.gov.pl", "Connection" :"Keep-Alive", } ...

 
12:17 PM
1
Q: How to rotate a figure in all directions in matplotlib

DmanI am trying to rotate a figure horizontally in python. With the mouse I am only able to rotate through one degree of freedom as well as being able to spin the figure, for example this is what I can do at the momement: These movements are only vertical. I would like to be able to rotate the fig...

0
Q: Numpy random: getting not independent results

V_ProgrammerI'm coding some things on Python, and I need random numbers. I'm using the Numpy library to generate this random numbers. I have a code for a random move of an entity: def moverse(self, Ltilda, it): self.historia[it] = self.pos chig = abs(np.random.randn()) angulo = np.random.rand(...

 
12:31 PM
0
Q: Create repeated loop to generate neighbours

Valorian85I'm trying to generate a sublist of nieghbours with below criteria: The input would be possible partitions to the list S = [1,2,3,4,5,6] Criteria for Neighbourhood Using Split Operations Criteria 1 – Split largest element in the list. Criteria 2 – Always split the largest element by //2 (e...

0
Q: Pandas: How to plot multiple scatterplots within different locations in the same plot?

ShanZhengYangI often have two pandas dataframes, which I would like to plot within the same plot. Normally these are two samples, and I would like to contrast their properties, as an example: The x axis simply has two locations, the left for the first dataset, and the right for the second dataset. In ma...

0
Q: Pandas Dataframe dropping rows and setting column names

PapieI have a pandas dataframe like this: 1 2 3 0 NaN ingr contr count 2.0 water 0.02 275 3.0 oil 0.23 11 ..... and I would like to transfer it to this: ingr contr count water 0.02 275 oil 0.23 11 .... I tried to use pd.drop and pd.set_index()...

 
12:54 PM
0
Q: How to add colors to each individual face of a cylinder matplotlib

DmanI am trying to color each individual face of a cylinder, however I am not sure how to go about it, I have tried the following: for i in range(10): col.append([]) for i in range(10): for j in range(20): col[i].append(plt.cm.Blues(0.4)) ax.plot_surface(X, Y, Z,facecolors = col...

0
Q: Return C++ integer array in Python using ctypes/ numpy.ctypeslib

user2178117I am attempting to create a C++ function that will return a pointer to an array, which I can then use in numpy. I seem to be stuck at the very basics. When I print out the values of the array I get back, (which in this case should just be the numbers 0 to 99), after 83 I don't get expected result...

0
Q: pandas get the max 3 score rows for each category

liu gangI get a list as follows : cat score a 80 c 88 b 36 b 96 d 99 b 76 d 89 a 50 d 69 b 36 d 59 b 96 b 86 c 98 a 50 a 90 c 83 b 66 how to use pandas can get the max 3 score rows for each cat?

0
Q: How to use selfJoin to reshape duplicate rows in Pandas ?

Kemal DiriI have a duplicates row and I want to concatenate them. They are like : ID Col1 Col2 Col3 ... Col46 ----------------------------------- id1 a1 b1 c1 ... x1 id2 a2 b2 c2 ... x2 id1 a1 b1 c1 ... y1 id3 a3 b3 c3 ... x3 id3 a3 b...

 
1:21 PM
0
Q: Converting time format using Read_sql method

Azhar Khani was trying to convert time format using read sql but it gives error ValueError: cannot cast unit %H:%M:%s data = pd.read_sql('select curtime() as time1 from dual' ,mysql_con,parse_dates={'time1':'%H:%M:%s'})

0
Q: Efficiently label each row in a large dataframe

trenchI have a file containing dates from June 2015 + 365 days. I am using this as a lookup table because there are custom business dates (only certain holidays are observed and there are some no-work dates because of internal reasons). Using the customer business date offsets was just so slow with 3.5...

 
1:32 PM
0
Q: I can't assignment a value to the cell python pandas

Sam RdsI have the following code: for i in range(len(list_sort)): list_sort[i] = list_sort[i].reset_index() classification = 1 list_sort[i].set_value(0, list_column[k], classification) for j in range(len(df))[1::]: if(list_sort[i].ix[j][1] == list_sort[i].ix[j-1][1]): ...

 
1:42 PM
0
Q: importing seaborn changes matplotlib graphs

ysearkaI am trying to use matplotlib and seaborn to perform some data vizualisation (heatmap here). But i realized that the matplotlib heatmap doesn't look the same at all whether I import seaborn or not. I've launched a matplotlib heatmap before importing seaborn: And the same matrix heatmap after ...

0
Q: Unpack the list element of DataFrame

Alexey TrofimovI have this df: l1 = ['a', 'b', 'c'] l2 = ['x', ['y1', 'y2', 'y3'], 'z'] df = pd.DataFrame(list(zip(l1, l2)), columns = ['l1', 'l2']) result: l1 l2 0 a x 1 b [y1, y2, y3] 2 c z What i need is to unpack the inner list in l2 and spread the correspondin...

 
2:17 PM
2
Q: Counting specific values in rows in CSV

Diganta BharaliI have a csv file: A D1 B D2 C D3 E 1 action 0.5 action 0.35 null a 2 0 0.75 0 0.45 action b 3 action 1 action 0.85 action c I want to count the number of 'action' keyword in each row and make a new column giving the output. So the ...

0
Q: adding columns in pandas with different column names

entercaspahey guys pandas problem here, 4 data frames of the last 400 days of 4 different stocks, to be concatenated into one, they are in different indexes as the original pull for each stock from quandl starts with different start dates for the data. each data frame looks similar to this: a ...

0
Q: possible Python integer overflow error

Pradyut VatsaBelow is my code that I'm trying to run to solve for a maximum prioritized product problem i.e. return a maximum value for a product of two numbers in a list. My issue is that the product that is being computed is incorrect when the numbers in the input list are large. I was of the opinion that t...

0
Q: Calculate count of rows matching a condition in a pandas frame

srey123Dataset Description: I have a dataset that looks like this (sorted by key, which also means it is sorted by offset_time_stamp): key offset_time_stamp person 7_sec_count 1 0 A 0 2 0 B 0 3...

0
Q: Matplotlib errorbar plot does not use marker cycling

darthbithIn the following example, the error bar plot does not use the marker cycle specified in the axes rc, although it does use the color cycle. Specifying fmt rather than marker in the cycler throws an AttributeError: Unknown property fmt. How can I use the prop_cycle to specify the markers of an erro...

 
2:40 PM
0
Q: parsing a text file for integers on a given line with python

Brocolli RobI've got this test suite that outputs test results as a text file. Here is a sample: File Opened: Tuesday, June 26, 2016, 10:17:13 AM File Opened: Tuesday, June 26, 2016, 10:17:29 AM Radio Test BER LOOP BACK successful Radio Test PAUSE successful Radio Test BER LOOP BACK successful File Op...

0
Q: Matplotlib Line3DCollection multicolored line smoothend

eotpBased on the matplotlib example code I constructed a 3D version of a multicolored line. However, if you zoom in the multicolored line looks kind of wiggly/unevenly segmented. Any ideas how to smoothen the 3D-multicolored line? import numpy as np import matplotlib.pyplot as plt from matplotlib.c...

0
Q: Python 3.5: Scipy only reading part of an image?

DeeWBeeI'm using Spyder (Python 3.5) and messing around with some image manipulation. I'm using Scipy.ndimage to import a jpeg (shown below). When I print out the array representing the imported image, it seems that I only receive part of the array (code and output below). I'm not sure if I'm only still...

 
3:10 PM
0
Q: sum over selected numpy.ndarray column and write to a file

BaRudI am trying to write the sum of selected numpy array column and write to a file. The following code snippet is working fine: for i in range(int(ldata[2])): s_u.append(dos2[i][1]) s_d.append(dos2[i][2]) p_u.append(np.sum(dos2[i,[3,5,7]])) p_d.append(np.sum(dos2[i,[4,6,8]])) d_...

-1
Q: Defining arrays in function of nested loops

GSELI am wondering what I should put into a in this tentative code: def anal(n, m): a = np.zeros(len(m)) for i in range(len(m)): for j in range(len(n)): a[??] = a[??] + a[i] = a[i] + ((1)**j)*(2*i + 1) return sum1

0
Q: Efficient query pandas dataset

TorenGiven a pandas dataset contains 8 million rows and 20 columns. Program queries the dataset to find an average of certain column. The average based on selections from other columns Need a help to get fast response on bundle of 10k queries and reduce the query execution time Setup : import pan...

0
Q: Sum of values with same month

user6162407data = {'dates': ['2010-01-29', '2011-06-14', '2012-01-18'], 'values': [4, 3, 8]} df = pd.DataFrame(data) df.set_index('dates') df.index = df.index.astype('datetime64[ns]') Having a dataframe where the index is a date, how would I go about adding a new column caled 'Month' that is the sum of al...

0
Q: Pandas Frequency Conversion

Al IvonI'm trying to find if is possible to use data.asfreq(MonthEnd()) with no date_range created data. What I'm trying to achive. I run csv query with the following code: import numpy as np import pandas as pd data = pd.read_csv("https://www.quandl.com/api/v3/datasets/FRED/GDPC1.csv?api_key=", parse_...

0
Q: FloatingPointError in calculating standard deviation?

cjm2671Using pandas/numpy, I'm sometimes getting a floating point error when trying to calculate a standard deviation: FloatingPointError: invalid value encountered in less My code looks something like this: def historical_volatility(p): return p.pct_change().ewm(span=35, min_periods=35).std() ...

 
3:46 PM
0
Q: python convert utf-8 characters to LaTeX ASCII

Flavio SartorettoIn order to solve my problem http://tex.stackexchange.com/q/316802/108917 I implemented after http://stackoverflow.com/a/13089420/5195446 my code below #!`#!/usr/bin/pythonw # -*- coding: utf-8 -*- import sys import re repldict = {'Ω':'\Omega','?<8A><86>':'\subseteq','?<9F>?':'<','?<9F>?':'>'...

1
Q: Google API client (Python): is it possibile to use BatchHttpRequest with ETag caching

superciccio14I'm using YouTube data API v3. Is it possible to make a big BatchHttpRequest (e.g., see here) and also to use ETags for local caching at the httplib2 level (e.g., see here)? ETags work fine for single queries, I don't understand if they are useful also for batch requests.

0
Q: "OSError: cannot write object arrays to a file in binary mode"

Wilmer E. HenaoIt must be one of those days. I have always been able to use function tofile to save data. But for some reason, today it's not working :) import numpy as np blah..... print(type(blist)) npdata = np.array(blist) print(type(npdata)) npdata.tofile('myfile.dat') Gets me the following results: T...

0
Q: How to remove edgecolor in 3d plot while using alpha and facecolors

DmanI am trying to remove the edge color in the plot of a cylinder where I have set an alpha and facecolors. However, if I set alpha to be less than 1, I can still see the edge colors. Here is an example: You can still see the blue edgecolors even tough I have set the edgecolor to None. This is t...

 
4:13 PM
0
Q: Storing multiple objects in an HDFStore group

mgoldwasserI want to store multiple objects in an HDFStore, but I want to organize it by grouping. Something along the lines of: import pandas as pd my_store = pd.HDFStore('my_local_store.h5') my_store._handle.createGroup('/', 'data_source_1') # this works, but I'm not sure what it does my_store['/data_sou...

 
4:25 PM
0
Q: Python decorator for retrying w/exponential backoff

electrometroThis is my first decorator in Python! I found some of it on the internet but have tweaked it to our needs. I am curious to know if the way I am trying to grab the instance is the best way to do so. Any other general improvements appreciated! import logging import time def retry_and_catch(exc...

 
4:49 PM
0
Q: Remove a text pattern from Pandas

PavelI need to remove a specific text pattern from a DataFrame. I have the following df: In[115]:test Out[116]: 0 Aland Islands (Finland) 1 Andorra 2 Austria 3 Belgium 4 ...

0
Q: How to have one legend for multiple subplots?

LWZI have one figure with multiple subplots, and each subplot has the same number of lines (In my case it's 4 lines). How can I have one single legend (say, ['a', 'b', 'c', 'd'] ) on the side for all the subplots? BTW, I plotted the subplot axes using fig, ax_list = plt.subplots(rows, cols) and ...

0
Q: vectorised list.get() solution in numpy/pandas

Philipp_KatsI have a temporal KDF kernel as a list (or numpy array) of values, where value index represents corresponding minute in a week. for each record in data frame, I need to get KDE value using record timestamp and do it as fast as possible. for now, I use .apply(): kde = kde # kernel dencity as a...

0
Q: Multiplying values in a list individually in python

JimI'm trying to perform separate mathematical operations on a python list. As an example: [1000, 0.15, 1150, 0.1, 0.2, 828, 49.68, 877.68, 100, 977.68] I would like to multiply 1000 by 0.15, then take that value and add it to 1000 to give 1150. I would then like to carry out other mathemetical op...

 
5:18 PM
0
Q: How to efficiently find the indexes where a panda (or numpy) array of string changes values?

user189035so suppose we have the following mildly large (10K entries) data set : import pandas pandas.Series(['xxx','xxx','xxx','aaa','aaa','bbb','bbb','bbb']) (the data set is already sorted in the weak sense that similar entries are contiguous) what is a efficient way to find the indexes of all the p...

0
Q: Read .dat file using python

Alejandro Jiménez RicoI've got a simulation involving internal waves and moving particles in the water, using the MITgcm. The output of this looks something like this for each time step: -9999 0.0000000000000000000 %Time step (0.00000000000000 seconds) 1308.2021183321899 -14.999709364517091 % Particle 1 (X...

0
Q: Can I sign an X509 certificate entirely in Python?

Dan O'BoyleI'm working within the Google App Engine (GAE) python 2.7 runtime. I need sign (and potentially also generate) an X509 certificate (.csr) I found several guides, that rely on PyOpenSSL. As I understand it, PyOpenSSL is is wrapper around OpenSSL and not available in App Engine. Pycrypto is avai...

0
Q: Plotting multiple different plots in one figure using Seaborn

Ted PetrouI am attempting to recreate the following plot from the book Introduction to Statistical learning using seaborn I specifically want to recreate this using seaborn's lmplot to create the first two plots and boxplot to create the second. The main problem is that lmplot creates a facetgrid accordi...

 
5:55 PM
0
Q: Best way to pass repeated parameter to a Numpy vectorized function

KartikSo, continuing from the discussion @TheBlackCat and I were having in this answer, I would like to know the best way to pass arguments to a Numpy vectorized function. The function in question is defined thus: vect_dist_funct = np.vectorize(lambda p1, p2: vincenty(p1, p2).meters) where, vincenty...

1
Q: Python 3.5.1 Unable to import numpy after update

SevynsI'm running Python 3.5.1 on a Windows 7 machine. I've been using Anaconda without issue for several months now. This morning, I updated my packages (conda update --all) and now I can't import numpy (version 1.11.0) or pandas(version 0.18.1). The error I get from Python is: Syntax Error: (unicode...

0
Q: Finding an array elements location in a pandas frame column (a.k.a pd.series)

DelosariI have a pandas frame similar to this one: import pandas as pd import numpy as np data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']} df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4']) Col1 Col2 Col3 Col4 R1 ...

0
Q: How to implement pair-wise distance in TensorFlow?

PinocchioI was implementing the squrared pair-wise eucledian distance in tensor flow but wasn't able to match it with sklearn library. I implemented it using: dist(x, y) = dot(x, x) - 2 * dot(x, y) + dot(y, y) but wasn't able to get the functions to match. Does anyone know what might be wrong? Here ...

0
Q: Python binary to decimal converter

ConfettimakerAny ideas how I could improve this? I already know that there is no checking for anything other than a 1, so you can enter a 2 or an a or a b and it will be interpreted as a 0, not interfering with the program's functionality. What I would like to know is if anyone has any suggestions for improvi...

0
Q: How do you print the current date and time as a large number in Python?

user224145I want to print say '280716191040' the '280716' being the date today and the '191040' being the hours, minutes and seconds of the current time. Is this possible? If so, how do you do it?

 
6:29 PM
1
Q: How to change numpy array dtype and reshape?

germI have an array that I read from an HDF5 file, and it is a 1D array of tuples. Its dtype is: [('cycle', '<u2'), ('dxn', 'i1'), ('i (mA)', '<f4'), ('V', '<f4'), ('R(Ohm)', '<f4')] I would like to convert this from an n x 1 array into a (n/5) x 5 array of type np.float. I tried np.astype but t...

 
6:43 PM
0
Q: turn grid into a checkerboard pattern in python?

BmmI have successfully created a grid, but am now trying to turn my grid into a checkerboard pattern, preferably using a variant of the floodfill command. how do I make sure the program recognizes which squares are even and which are odd? currently the IDE is set so m[i][j]= 1 gives blue, while m...

 
7:01 PM
0
Q: generator exit at the very beginning in matplotlib

disccipI found that the first data will be read twice since the generator will exit at the very beginning, and this whole data_gen() function will be called again, then the generator start working. This is so weird. I have posted the function below. Please comment or answer if you have any idea. Really ...

 
7:15 PM
0
Q: How do I count values in a list that match another list

Yared J.I apologize if I'm not making any sense, English is not my native language and I am only one week into python and pandas. So, I have a really long data frame of transcription factors (TF) and long a list of essential genes, and what I've done so far is determine if a gene that is regulated by a ...

0
Q: Exponential plotting in Python

vFlavI have a set of tuples of the form [(a0, b0), (a1, b1), ..., (a_n, b_n)]. The y-values are already calculated based on the x-values - that's how the set of tuples was built. I am trying to plot these data points in an exponential way in order to get an image that justifies the limit as x -> infin...

0
Q: ValueError: setting an array element with a sequence while training KD TRee on TFIDF

user3667569I am trying to train a KD-Tree on TF-IDF of a document corpus but it gives ValueError: setting an array element with a sequence. The code and the error description are below. Can someone help me figure out the problem? Code: t0 = time.time() count_vect = CountVectorizer() X_train_counts = c...

 
7:43 PM
0
Q: How to divide two groupby objects in pandas?

DimsI have the following code: import numpy as np import pandas as pd obs = pd.DataFrame({ 'storm': [1, 1, 1, 1, 0, 0, 0, 0], 'lightning': [1, 1, 0, 0, 1, 1, 0, 0], 'thunder': [1, 0, 1, 0, 1, 0, 1, 0], 'p': [0.20, 0.05, 0.04, 0.36, 0.04, 0.01, 0.03, 0.27] }) g1=...

 
7:55 PM
0
Q: import numpy throws error: SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uXXXX escape

JakubI have installed pyzo and mniconda under windows 10 and installed numpy an matplotlib using "conda install". But when I'm trying to run import numpy as np import matplotlib.pyplot as plt Im getting this error: Traceback (most recent call last): File "", line 3, in import numpy Fil...

 
8:07 PM
0
Q: Using an R Markdown style document (.Rmd) as input for Pweave

kungfujamI'm trying to run a basic R Markdown document (that calls python in code chunks) through Pweave. In the Pweave documentation it states that you can declare code chunks using the style ```{python}. However when I try to compile using, for example, pweave -f pandoc FIR_design.mdw the chunks are not...

 
8:18 PM
0
Q: Element-wise weave of two arrays used with numpy repeat

aphI have two arrays of unequal length val1 and val2 that I am trying to weave together in a specific way that is defined by the equal-length arrays mult1 and mult2. In general, my arrays are very long (~1e6 elements), and this is a performance-critical bottleneck in my calculation, so I cannot affo...

0
Q: Random Sample of a subset of a dataframe in Pandas

WGPSay i have a dataframe with 100,000 entries and want to split it into 100 sections of 1000 entries. How do i take a random sample of say size 50 of just one of the 100 sections. the data set is already ordered such that the first 1000 results are the first section the next section the next and ...

0
Q: Python Visual Studio extension doesn't show errors

user1618465I'm used to use VS to code C++ and Eclipse to code python but lately I have tried VS for both languages. I found something very difficult to understand that while VS autocompletes it doesn't warn you about errors before runtime. There is no warning regarding non existent variables or method...

0
Q: Pandas create Foreign ID column based on Name column

unpairestgoodI have a simple dataframe like this for example: df = pd.DataFrame({'Name': ['John Doe', 'Jane Smith', 'John Doe', 'Jane Smith'] df: Name 0 John Doe 1 Jane Smith 2 John Doe 3 Jane Smith 4 Jack Dawson 5 John Doe I want to add a column ['foreign_key'] ...

 
8:42 PM
0
Q: Return a column which meet two conditions with pandas dataframe

Li ShuweiI am very new to python, and here I have a question I don't know how to fix, please help. Here is the thing: I have a dataframe, and I want to extract a column which meets two different conditions. The columns is as follows: state gender year name births 13299 AK F 2013 ...

-1
Q: Can this one-liner be further improved?

TheguyFinally managed to get the one liner I was banging my head against. This is it: [plot(real(k), imag(k)) for k in fft.fft(eye(31))]; You can change the number 31 to any integer (not too large). I'm curious: Can anyone suggest a more compact way to achieve the same or did I manage to reach a g...

0
Q: Flip and rotate numpy array

cpicancoIs there a faster way of flipping and rotating an array in numpy? For example, rotating one time counter clockwise and then flipping? import numpy as np a = np.arange(0,10) b = np.arange(-11,-1) ar = np.array([a,b]) print ar print ar.shape ar = np.rot90(ar, 3) print np.fliplr(ar) Output:...

0
Q: Using Basemap, import error "import _geoslib"

K. ShoresIt's been about a year since I've had to run a script that uses the Basemap module in Python 2.7. The last time I ran the script, it ran fine. Since then, I think some update to matplotlib or basemap may have messed something up. Here is the error I get anytime I try to from mpl_toolkits.basemap ...

 
9:04 PM
1
Q: UnicodeDecodeError when write to excel using python

ldevyataykinaI try to add_sheet to exccel file with df.groupby('member_id').apply(lambda x: add_xlsx_sheet(x, u'Десктопы полно'.decode('utf-8'), path='{}.xlsx'.format(x.name))) and get error UnicodeDecodeError: 'utf8' codec can't decode byte 0xc4 in position 0: invalid continuation byte Why does it happen?

 
9:26 PM
1
Q: How to count unique combinations of variable in a Pandas Dataframe

Dan BurkhardtI'm using pandas to count unique combinations of sets of variables in a dataframe. I'm currently using the .groupby() function, but I think I'm missing part of it's functionality. Example code: import pandas df = pd.DataFrame([['A','C','G'], ['A','C','H'], ...

0
Q: How to save an animation to mp4 successfully

user4437416I am using the ani=anim.FuncAnimation(fig, animate, interval=1000, frames=20 syntax with an animate function which I then want to save to a file for later viewing. I have tried saving the file with ani.save('plan_evap.mp4', fps=1) but this process of saving seems to be the limiting factor to my w...

0
Q: fit regression of the form y = x ** a with numpy

Alexandre Holden Dalyimport numpy as np import matplotlib.pyplot as plt x_ = np.array([1.0, 2.0, 4.0, 8.0, 16.0, 33.0]) y_ = np.array([0.4, 0.55, 0.62, 0.72, 0.76, 0.8]) I want to fit a regression model of the form y = x ** a where a is estimated. The purpose is to extrapolate to (much) larger, unseen values of x. ...

0
Q: How do I plot a non-linear model using matplotlib?

GuledI recently fit a polynomial model successfully, but I am seeking to visualize my model. I'm a bit lost as to how to proceed to achieve this. Normally with a linear model, when I perform linear regressions, I simply take my training data (x) and and my output data (y) and plot them using matplotli...

 
10:00 PM
-1
Q: round a column in dataframe

StaceyI have a dataframe 'dayData' and I am trying to round a zero decimal places one of the columns (the column is called 'trace') I have tried using the following but with no success: dayData["trace"] = dayData["trace"].round(0) I get the exception: AttributeError: 'numpy.float64' object has no ...

0
Q: Stacked 3d bar chart with matplotlib

Alexi worked on a simple 3d bar chart using the following code: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection = "3d") ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") ax.set_xlim3d(0,10) a...

0
Q: Random Sampling of Pandas data frame (both rows and columns)

BaktaawarI know how to randomly sample few rows from a pandas data frame. Lets say I had a data frame df, then to get a fraction of rows, I can do : df_sample = df.sample(frac=0.007) However what I need is random rows as above AND also random columns from the above data frame. Df is currently 56Kx8.5...

0
Q: pandas function to fill missing values from other dataframe based on matching column?

rossbotSo I have two dataframes: one where certain columns are filled in and one where others are filled in but some from the previous df are missing. Both share some common non-empty columns. DF1: FirstName Uid JoinDate BirthDate Bob 1 20160628 NaN DF2: FirstName Uid JoinDate BirthDat...

 
10:18 PM
0
Q: Python Pandas SettingWithCopyWarning copies vs new objects

SevynsI'm working with a dataframe 'copy' created by sub-setting a previous one - see below: import random import pandas as pd df = pd.DataFrame({'data':list(random.sample(range(10,100),25))}) df_filtered = df.query('data > 20 and data < 80') df_filtered.rename(columns={'data':'observations'},inplace=...

0
Q: Jupyter: Write a custom magic that modifies the contents of the cell it's in

JeremyKunIn a Jupyter notebook there are some built-in magics that change the contents of a notebook cell. For example, the %load magic replaces the contents of the current cell with the contents of a file on the file system. How can I write a custom magic command that does something similar? What I hav...

 
10:29 PM
1
Q: Compare files by name in two folders A and B and delete duplicates from folder A

LernkurveBackground I wrote my very first Python program to answer a Superuser question Question I'm wondering how the application can be rewritten to make it as pythonic as possible. Unittest code import unittest import os import shutil from DeleteDuplicateInFolderA import DeleteDuplicateInFolderA ...

 
11:22 PM
0
Q: Reading no-header CSV to pandas dataframe and parsing date

Rustam AliyevI am trying to read similar to below CSV file to pandas.DataFrame: 2011 1 10 AAPL Buy 1500 2011 1 13 AAPL Sell 1500 2011 1 13 IBM Buy 4000 2011 1 26 GOOG Buy 1000 Data doesn't have column headers. When I read that file I also want to parse fi...

 
11:35 PM
0
Q: Pandas. Replace nan with None

FranGoitiaI'm using Pandas to parse a csv and I'm reading nan values from an excel and I'd like to convert them to None. season_matches = pd.read_csv(io.StringIO(rv.decode('utf-8'))) season_matches = season_matches.replace(np.nan, None) season_matches = season_matches.to_dict() This however returns Type...

 

« first day (857 days earlier)      last day (1331 days later) »