« first day (859 days earlier)      last day (1329 days later) » 

12:11 AM
0
Q: Pandas: How can I check if a pandas dataframe contains a specific value?

AlanHSpecifically, I want to see if my pandas dataframe contains a False. It's an nxn dataframe, where the indices are labels. So if all values were True except for even one cell, then I would want to return False.

 
1:03 AM
0
Q: Replacing Columns from one dataframe with columns from another dataframe in pandas

Guo Xian YauI have two DataFrame, let's call it X and Y, with dimension of X being 2063 x 14 and dimension of Y being 2063 x 8. I want to replace column 4 to 12 of X with Y, can I do that in pandas? The solution I found so far are replacing certain values from a column/multiple columns, but not entire DataF...

 
1:18 AM
0
Q: Basic call-and-response Slack bot

AmandaI'd love thoughts on how to make this more elegant. I'm planning to add some additional functionality, but basically this is just my first pass at creating a pythonic Slack bot from scratch. You need Slack API token to run it. I am deploying to Heroku, so I have it looking for an environment va...

 
1:35 AM
0
Q: Get all columns in a numpy structured array.

ssmI would like to slice a numpy structured array. I have an array >>b >>array([([11.0, 21.0, 31.0, 0.01], [1.0, 2.0, 3.0, 0.0]), ([41.0, 51.0, 61.0, 0.11], [4.0, 5.0, 6.0, 0.1]), ([71.0, 81.0, 91.0, 0.21], [7.0, 8.0, 9.0, 0.2])], dtype=[('fd', '<f8', (4,)), ('av', '<f8', (4...

 
1:49 AM
0
Q: How to Use Global Variable in Python?

Sungyong ChoiAs below Image, I want to use global variable, but class to class don't pass variable. Please let me know useage.

 
2:43 AM
0
Q: multidimensional array of images in python

Anton AliceHow can I in python declare an empty (multidimensional) array, that can store images? I dont want to use something like array.append(image1) array.append(image2) but rather something like array[0,0]=image1 array[0,1]=image2 array[1,1]=image3 . . .

0
Q: How to construc a numpy array with multilple same timestamp?

user5779223I have tried: import numpy as np t = np.full(('2012-12-12'), 10, dtype=np.datetime32) But got such an error: TypeError: an integer is required Do you have any idea? Thanks!

 
3:11 AM
0
Q: The better way to perform subtraction of 3-dimensional array in numpy

ΛlisueI would like to know a better alternative way to perform subtraction on three dimensional array. Currently I'm using np.array([x for x in xs]) to perform subtraction on each first axis like: import numpy as np # ============================================================================= # ...

 
3:36 AM
0
Q: Python : sys.getsizeof vaue of numpy ndarray seems too small

Tomimport sys npArrayList = 20000 * [None] npNdArray = np.random.normal(size = (20000, 4)) for i in xrange(20000): npArrayList[i] = npNdArray[i, ] print 'npArrayList[i].nbytes = ' + str(npArrayList[i].nbytes) break print 'npArrayList size = ' + str(sys.getsizeof(npArrayList)) print 'npN...

 
4:35 AM
0
Q: Why does indexing numpy arrays with brackets and commas differ in behavior?

alavin89I tend to index numpy arrays (matrices) with brackets, but I've noticed when I want to slice an array (matrix) I must use the comma notation. Why is this? For example, >>> x = numpy.array([[1, 2], [3, 4], [5, 6]]) >>> x array([[1, 2], [3, 4], [5, 6]]) >>> x[1][1] 4 ...

 
4:45 AM
0
Q: Training different scikit-learn classifiers on multiple CPUs for each iteration

alvasI have a script that randomly generates a set of data and trains several classifiers to compare them against each other (it's very similar to http://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html): from itertools import product import numpy as np from skle...

0
Q: How to search for rows using an expression in numpy rec array

deepakConsider i have a numpy recarray as below: r = np.rec.array([(1,2.,'Hello'),(2,3.,"World")], \ dtype=[('foo', 'i4'),('bar', 'f4'), ('baz', 'S10')]) Now i want to get all the object that returns 'True' for the following expression stored in dict, expression = {'foo':1,'bar':3....

 
5:40 AM
1
Q: pandas read_csv column dtype is set to decimal but converts to string

user824361I am using pandas (v0.18.1) to import the following data from a file called 'test.csv': a,b,c,d 1,1,1,1.0 I have set the dtype to 'decimal.Decimal' for columns 'c' and 'd' but instead they return as type 'str'. import pandas as pd import decimal as D df = pd.read_csv('test.csv', dtype={'a': ...

0
Q: Pandas - Bar chart with grouped-data, with the order of groups being sorted by data from another list

Joshua LeungRequirements: I'm trying to create a bar graph where, for each condition ("label"), I show the mean task time for each manipulation ("pattern"). So, there will be 8 groups of 3 bars, and one group with a single bar. I need to show error bars (standard error) on each of these bars. I want the or...

 
6:34 AM
-1
Q: How to filter Pandas dataframe using regex pattern

user1128088How to filter pandas dataframe using a regex pattern such that if a match is found, new dataframe is created for the matches. For example: Let's say for a given dataframe df I want to use regex pattern to match all currencies and keywords balance|bal|credited occurring in each row of column text ...

 
6:52 AM
-1
Q: I want to make graph in python of different values of voltage from a text file

Vivek Jaredamy values in the text file look something like this : Voltage:12.69V Voltage:12.22V Voltage:12.19V Voltage:12.17V Voltage:12.17V Voltage:12.17V Voltage:12.17V

 
7:08 AM
0
Q: How does the `level` parameter work for pandas add method

piRSquaredI've seen the level parameter for the pd.DataFrame methods add, sub, div, and mul. Documentation states: level : int or name Broadcast across a level, matching Index values on the passed MultiIndex level I can't seem to understand how this is used appropriately. Consider: import pan...

0
Q: Scraping after login using scrapy

OutOfTheBoxI just finished a scraper in python using scrapy. The scraper logs in to a certain page and then scrapes a list of other pages using the authenticated session. It retrieves the title of these pages and puts it in a list of items together with the page name. Because there are little examples to f...

 
7:55 AM
0
Q: Writing data to json in python

MohanI have np array of 3*10 dimension, each column is vertex with its x, y, z co-ordinate. I want to output this data to JSON file like following. { "v"0 : { "x" : 0.0184074, "y" : 0.354329, "z" : -0.024123 }, "v"1 : { "x" : 0.34662, "y" : 0.338337, "z" : -0.0333459 } #and so on... Here is my pyt...

0
Q: Update pandas DataFrame with .str.replace() vs .replace()

landgeI have a column in my pandas Dataframe df that contains a string with some trailing hex-encoded NULLs (\x00). At least I think that it's that. When I tried to replace them with: df['SOPInstanceUID'] = df['SOPInstanceUID'].replace('\x00', '') the column is not updated. When I do the same with ...

 
8:12 AM
0
Q: OpenCV CalcCovarMatrix vs. Numpy Cov

uoamrowI am porting an image processing algorithm from Python to C++, using OpenCV in both cases. In the Python version, we are using np.cov from Numpy: import numpy as np #Using some dummy data to represent BGR pixels values = [[30, 37, 35], [26, 36, 34], [38, 45, 41], [40, 47, 43], [38, 45, 43], [34...

0
Q: Pandas Python, select columns based on rows conditions

hans glickI'm a pure noob in pandas python so I'm sorry if there is already something about it. I did some searches though but I cannot come up with a solution. import pandas as pd df = pd.DataFrame(np.random.randn(2, 4)) print(df) 0 1 2 3 0 1.489198 ...

 
8:29 AM
0
Q: Creating array of correct content and size

GSELI want to create an array of dim = 3 which holds increasing numbers. E.g.: array = [a, b, c] where a contains numbers from 0 to 5, b goes from 6 to 10, c goes from 11 to 15. Does anyone have a tip on how should I proceed? I also wonder how I can define gridsize, meaning, how to define number ...

0
Q: pandas str contain to return match

KrugerBrPandas str.contains() where evaluated to True in the way below returns the row. But how to return the match instead of the row? In [1]: df language level java programming beginner c/c++ intermediate php beginner In [2]: df[df['language'].str.contains("j...

 
8:52 AM
0
Q: np.where code - ValueError: "cannot set items on DatetimeIndexResampler"

seemoI created a data frame to use when testing the resample features as follows: f = pd.DataFrame(data=np.linspace(50, 100, 200), index=pd.date_range(end='2014-06-18', periods=200), columns=['last']) f Out[63]: last 2013-12-01 50.000000 2013-12-02 50.251256 2013-12-03 50.502513 I then use the r...

0
Q: In Python how do I plot using GMPY2?

TwiffyI'm not new to programming, but I am new to Python and numerical computing, so this may be a newbie question. I'm using GMPY2 to handle computation of extremely large numbers, but I want to use MatPlotLib to graph the results. I currently have import gmpy2 from gmpy2 import mpz, mpq, mpfr, mpc ...

 
9:07 AM
0
Q: append page to existing pdf file using matplotlib

jlarschI would like to append pages to an existing pdf file. Currently, I am using matplotlib pdfpages. however, once the file is closed, saving another figure into it overwrites the existing file rather than appending. from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as p...

0
Q: 3D animation using matplotlib

YutoI want to make 3D animation with matplotlib, but I don't know how to do. Here is my experiment, but don't work. Please teach how to work it. from matplotlib import pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D from matplotlib import animation from math import * fig = ...

0
Q: Replacing a column with a function of itself in Pandas?

draco_alpineI'm currently lost deep inside the pandas documentation. My problem is this: I have a simple dataframe col1 col2 1 A 4 B 5 X My aim is to apply something like: df['col1'] = df['col1'].apply(square) where square is a cleanly defined function. But this operation throws ...

 
9:26 AM
0
Q: use hard drive instead ram in python

alessio palmierii'm using Pydev (with interpreter Python 3.4) on Liclipse with Windows 10, I'd like to know if there's a method or a Python Package that can make me use a large dataset without writing it in RAM. i'm also using pandas for statistical function. I need to have access on the entire dataset becaus...

 
9:39 AM
0
Q: Pandas dataframe: Is there a difference in performance in replacing values by column and row?

ShanZhengYangI have the following pandas DataFrame. import pandas as pd df = pd.read_csv('filename.csv') print(df) dog A B C 0 dog1 0.787575 0.159330 0.053095 1 dog10 0.770698 0.169487 0.059815 2 dog11 0.792689 0.152043 0.055268 3 dog12 0.785...

1
Q: How to perform os.environ join in python?

DuckQueenI have a cofiguration of os.environ with default values (that cover 90% of my needs). I have a spectial application-framework-package for example called SALOME that does not provide package installation into system enviroment and tries to be selfcontained, it also requiers use of special old tech...

 
9:57 AM
0
Q: Pandas Time Series DataFrame Missing Values

Philip O'BrienI have a dataset of Total Sales from 2008-2015. I have an entry for each day, and so I have a created a pandas DataFrame with a DatetimeIndex and a column for sales. So it looks like this The problem is that I am missing data for most of 2010. These missing values are currently represented by 0....

0
Q: Python pandas loop that deletes csv rows until a string appears

JoãoI'm having trouble to create a code that reads a .csv file row by row and keep deleting the rows until it finds a certain string. For instance, I want to keep only the rows after "AH": SG 1 2 3 OH 3 3 UI AH 4 5 5 R3 4 4 4 The code should return only: R3 4 4 4 Can anyone help me with this...

0
Q: pandas caculate the np.var() for each column

liu ganghow to caculate the np.var() for each column , if the np.var()<0.1, then remove the column. Id F M R 7 1 286 907 12 1 286 907 17 1 186 1271 21 1 296 905 30 1 308 908 32 1 267 905 40 2 591 788 41 1 486 874 47 1 686 906 74 1 230 907

 
10:12 AM
0
Q: referencing a value in pandas and testing to see if the item is in a list

A Rob4I'm trying to look up a value in a dataframe using.loc. This should give me a string using variable 'ppi'. I then want to see if that string is already in a list (or actually in a list contained within a dictionary) and if it is not, then append the string. It isn't working, and simply append...

0
Q: Tokenizing words into a new column in a pandas dataframe

user3655574I am trying to go through a list of comments collected on a pandas dataframe and tokenize those words and put those words in a new column in the dataframe but I have having an error running through this, is The error is stating that AttributeError: 'unicode' object has no attribute 'apwords' I...

0
Q: Pivot Table in Pandas Count aggregate()

Vigneshwaran ThenrajI am trying to take the count of 'STAGE' occurrence based on project, I used np.size as aggfunc but it return number of occurrence including the project, My count value become double if expected count is 3 means it return 6 I used the below code df = pd.pivot_table(data_frame, index=['Proje...

0
Q: Generate Pandas DF OHLC data with Numpy

adeleI would like to generate the following test data in my dataframe in a way similar to this: df = pd.DataFrame(data=np.linspace(1800, 100, 400), index=pd.date_range(end='2015-07-02', periods=400), columns=['close']) df close 2014-05-29 1800.000000 2014-05-30 1795.739348 2014-05-31 1791.478...

0
Q: Elegant pair wise scalar product of many vectors in numpy

Julien BernuI have 2 sets of n*m vectors x_ij and y_ij of dimension d stored in two np.ndarray X and Y of shape n*m*d. I want to get the n*m matrix of scalar products x_ij.y_ij. At the moment I do this like that: (X.T.reshape((d,m*n)) * Y.T.reshape((d,n*m))).sum(axis=0)).reshape((m,n)).T It works but feel...

 
10:45 AM
0
Q: pandas box plot for multiple column

user1877600My data frames (pandas's structure) looks like above Now I want to make boxplot for each feature on separate canvas. The separation condition is the first column. I have similar plot for histogram (code below) but I can't make working version for the boxplot. hist_params = {'normed': True, '...

0
Q: How to make plt.savefig() save image for 'maximized' window instead of default size

SalilI know that this question have been raised previously but it didnt solve the problem. I am trying to plot graphs using subplots my problem is same as the question with similar title. I think instead of explaining in words I will show you what is happening and what I want. the first image is the p...

 
11:06 AM
0
Q: 1D function over 2D histogram in matplotlib

Radek PodskubkaI use matplotlib to plot some data in the form of 2D histogram. Typical output of my script looks like this: Histogram The relevant part of the script is here: xbins = 10**np.linspace(-3, 0, 100) ybins = 10**np.linspace(-3, 0, 100) counts, _, _ = np.histogram2d(x1val, x2val, bins=(xbins, ybins...

 
11:22 AM
0
Q: How to write numpy where condition based on indices and not values?

n00bI have a 2d numpy array and I need to extract all elements array[i][j] if the conditions x1range < i < x2range and y1range < j < y2range are satisfied. I do not care about the value of element array[i][j], only of the index positions, i, j. How do I write such conditions? Do I need to use mgr...

0
Q: Multiply nupmy ndarray with every element in another binary ndarray of different size

samer226047I have two ndarrays : a = [[30,40], [60,90]] b = [[0,0,1], [1,0,1], [1,1,1]] please notice that a shape might be larger but always square array (50,50) , (100,100) The wanted result is : Result = [[a*0,a*0,a*1], [[a*1,a*0,a*1], [[a*1,a*1,a*1]] I managed to get...

 
11:55 AM
0
Q: clean up data validation

user3610360I am checking data output in some testing code, and only some fields can be None, but I think this can be better: for key in data[0].keys(): self.assertIn(key, data_model) if data[0][key] is None: self.assertTrue('rate' in key or 'percentage' in key or 'ratio' in key)...

0
Q: catch exception and return empty dataframe

ArchieTigerI query a database and save result as a dataframe which I then transform by factorize with pivot_table. This works fine when database query returns data but it throws an error when no data is returned(this is to be expected). How to catch this exception and return empty dataframe? #When datafra...

 
12:12 PM
0
Q: Loading of text data file

Elmira_bI have a text file in below format id x, y 0[0.0, 1.0] 1[0.0, 2.0] 2[0.1, 2.5] : : I need to load this text file. I have tried: numpy.genfromtxt('FileName', delimiter=",", names=True) but the existence of [ prevents it from reading the file. What can I do?

 
12:30 PM
0
Q: COPY command in psycopg2

trenchI have a process which is reading from 4 databases with 4 tables each. I am consolidating that data into 1 postgres database with 4 tables total. (Each of the original 4 databases have the same 4 tables which need to be consolidated). The way I am doing it now works using pandas. I read one tabl...

 
12:42 PM
0
Q: Custom Python 'Server Status Checker'

Thomas W.I've written a home-grown solution for checking the status of my servers. This is both an exercise for me in learning further about Python, but it's also critical to status-checking critical things on my "network" of servers - both running against both an internal ("home") network against 18 or ...

 
1:03 PM
0
Q: How to nicely measure runs of same-data in a pandas dataframe

user3556757I want to give a function an arbitrary dataframe, dateindex, and column and ask it to return how many continuous preceding rows (including itself) had the same value. I've been able to keep most of my pandas code vectorized. Struggling to think how I can do this cleanly though. Below is a sma...

0
Q: UnicodeDecodeError when add new list to excel using python

ldevyataykinaI try to add new sheet to excel file with def add_xlsx_sheet(df, sheet_name=u'Десктопы кратко', index=True, digits=2, path=None): book = load_workbook(path) writer = pd.ExcelWriter(path, engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) if sheet...

 
1:26 PM
0
Q: Python numpy difference between reshape(v.shape) & reshape(*v.shape)

李德健I found myself struggled in the following two region of codes(which exactly did the same job),can anyone tell me what the difference? Code1: v = np.zeros((2,5)) value_one = np.linspace(-1.4, 1.3, num=v.size).reshape(*v.shape) Code2: v = np.zeros((2,5)) value_two = np.linspace(-1.4, 1.3, num...

 
1:46 PM
0
Q: DASK : IOError: [Errno 13] Permission denied:

NoobieI am using Dask 0.10 with the latest Anaconda distribution and I run into the following error after calling .compute(get=dask.multiprocessing.get) : File "<ipython-input-8-cd6a1c9a02b6>", line 309, in find_matches merged = data.merge(matches, on='url', how='left') File "C:\Users\user\...

-1
Q: Making a object move when pressing a key. Python Tkinter: PONG game

kaspersinoSo I'm trying to do a Pong game but I'm stuck with the "moving of paddle" thing. I've managed to do so that the method "moving" recognizes with i've pressed w or s for up or down commands. But I can't seem to get the paddle to move with the .move command and I can't find what's wrong. Thanks for ...

0
Q: Python - Using Pandas to eliminated curly brackets and output floats

DarthLazarHaving this large csv data set, that essentially has x and y values in each column. "{733.15, 179.5}", "{565.5, 642.5}", "{172.5, 375.5}", "{223.5, 554.5}",.... ...., "{213.5, 666.5}", "{851.5, 323.5}", "{498.5, 638.5}", "{763.5, 102.5}" A column is essentially this set and I can call each p...

0
Q: French animal generator

dogspeedI'm learning Python. I'm making a random animal generator, from 5 txt files. Each file is a list of words for respectively the specie of the animal, an adjective, an origin, and a bodypart with a color. Not all may appear in the description. I also wanted it to be arithmogrammatic. Here is my cod...

0
Q: DataFrame sorting unwanted using Pandas

JrCaspianConsider a basic data frame (using Pandas): testDf = pandas.DataFrame({'c':[1,2],'b':[2,2],'a':[3,4]}) The result gives: a b c 0 3 2 1 1 4 2 2 Instead of: c b a 0 1 2 3 1 2 2 4 Why is it sorted alphabetically? I want the second result.

0
Q: cannot get pip to be recognized as a command

Tyler VeinotI am trying to install matplotlib into python27 but am running into issues with pip. As stated when I try any 'pip' command I get the 'pip' is not recognized as an internal or external command. I checked my path variables and they point to the location of my OSGeo4W Python27 install. get-pip.py w...

 
2:16 PM
0
Q: Pandas filter rows using multiple fields together

lostsoul29I have a pandas DataFrame like this: In [34]: people = pandas.DataFrame({'name' : ['John', 'John', 'Mike', 'Sarah', 'Julie'], 'age' : [28, 18, 18, 2, 69]}) people = people[['name', 'age']] people Out[34]: name age 0 John 28 1 John 18 2 Mike 18 3 Sa...

0
Q: Select rows given 2 columns, if at least one value is below threshold

amcI have a pandas dataframe NAME VALUE A 2 A 1 B 4 A 3 C 2 B 8 I would like to add a column if values in column "Name" contain AT LEAST ONE value in "Values" below 3, corresponding to the name, such that: NAME VALUE BELOW_THRE...

 
2:35 PM
2
Q: 2D fit of a model to an image in Python

HadiMI want to fit a model (here a 2D Gaussian but it could be something else) with an image in Python. Trying to use scipy.optimize.curve_fit I have some questions. See below. Let's start with some functions : import numpy as np from scipy.optimize import curve_fit from scipy.signal import argrel...

0
Q: pandas: how to sort a grouped dataframe by mean amount?

RichardI have a dataframe that looks like this: Speciality Amount Greek 15 Greek 16 Italian 8 Italian 11 Italian 13 I have now aggregated the mean and count for each speciality: df_by_spec_count = df.groupby('Speciality').agg(['mean', 'count']) Now I wan...

0
Q: All indices of each unique element in a list python

LynnseyI'm working with a very large data set (about 75 million entries) and I'm trying to shorten the length of time that running my code takes by a significant margin (with a loop right now it will take a couple days) and keep memory usage extremely low. I have two numpy arrays (clients and units) of...

 
3:04 PM
0
Q: What's the best way to construct a 3D data with numpy for making a contourplot?

lesautresI have a set of data. Each of them is a single spectrum (two columns: energy and intensity) from different positions on the sample. I would like to show them in a contour plot as the following picture. x-axis indicates the energy, y the position and z the intensity. I created the third column and...

 
3:16 PM
1
Q: Strange typecasting when adding int to uint8?

JesseCI am somewhat confused by the way python/numpy work when typecasting unsigned integers. Example: import numpy as np x = np.array([255], dtype=np.uint8) y = x + 1 This gives the result: In[0]: y Out[0]: array([0], dtype=uint8) I understand that uint8 cannot store an integer with a larger v...

-1
Q: How to use groupby to concatenate strings in python pandas?

user3655574I have a dataframe that looks like the below. I currently have dataframe at the top. is there a way to use a groupby function to get another dataframe to group the data and concatenate the words into the format like further below? Thanks [

 
3:28 PM
0
Q: Pandas sorting multindex and reset

polypusI'm trying to go through a dataframe with 2 index levels. I previously removed entries from the dataframe, so often the second level is not ascending. But I want it to be. What's a good way of resetting the second level index to a sorted list? e.g. a = [{'A':1, 'B':2, 'C':3, 'D':4}] b = [{'A':1...

0
Q: Get iterable Tensor without running eval

VendeaIs there a way to make a Tensor iterable without running eval to get its numpy array? I am trying to iterate through two parts of a tensor after using split on it, but it happens within the construction of the hidden layers of my neural network, so it needs to happen before I am able to start a ...

0
Q: Using Pandas resample then populating original dataframe

seemoI am looking into the market stats based on a close price one week and the open price the next week. To do this Im using resample in Pandas. In order to give an example I use pandas DataReader below. from pandas.io.data import DataReader First to get the daily market data: SP = DataReader("^...

 
3:59 PM
2
Q: Python Pandas Unstacking Unique Column Values to Columns Of Their Own

Jaraddf = pd.DataFrame({'Col1': ['label1', 'label1', 'label2', 'label2', 'label3', 'label3', 'label4'], 'Col2': ['a', 'd', 'b', 'e', 'c', 'f', 'q']}, columns=['Col1', 'Col2']) Looks like this Col1 Col2 0 label1 a 1 label1 d 2 label2 b 3 label2 e 4 label3 c 5 lab...

0
Q: Python & Pandas Iteration Criteria

TinkincI am trying to get an itteration of ever state from quandl, however unless i just have the query = X be print(X) it only returns 1 string for abbv instead of listing all 50 states and joining them together. Any reason i am having issues with this? Thanks. for abbv in fiddy_states[0][0][1:]: q...

0
Q: Pycharm debugger, view as array option

Xavier-rpFirst of all, sorry if it's not the place to post this question, I know it is more related to the software I'm using to program than programming itself, but I figured someone here would probably know the answer. I often use PyCharm (currently on version 2016.1.2) and its useful debugger to code ...

0
Q: Search Pandas Column for Substring in other Column

Christopher GoingsI have an example .csv, imported as df.csv, as follows: Ethnicity, Description 0 French, Irish Dance Company 1 Italian, Moroccan/Algerian 2 Danish, Company in Netherlands 3 Dutch, French 4 English, EnglishFrench 5 Irish, Irish-American I'd like to check the pandas test1['Descri...

 
4:26 PM
0
Q: Use both matplotlib inline and qt in jupyter notebook

tcpieI am using Jupyter (with IPython) to analyze research data, as well as export figures. I really like the notebook approach offered by Jupyter: when I revisit an experiment after a long time, I can easily see how the figures correspond to the data. This is of course using the inline backend. Howe...

 
4:46 PM
0
Q: Iterating through a pandas dataframe and inserting new values into an empty column

HarelI'm relatively new to Pandas and am having trouble iterating through the values in a given column in my dataset and finding those cells which contain a specific string. Address,City ['1234 Apple Drive', 'San Francisco', 'CA'],'' ['4678 Bannana Street', 'Austin', 'TX'],'' For this example, I wa...

 
4:56 PM
0
Q: Close all Matplotlib figures

khpeekI frequently use Python with the Atom editor and run scripts using the "atom-runner" extension by pressing the shortcut key Alt+R. These scripts generally create figures which are rendered in separate windows after the "matplotlib.pyplot.show" command. The problem is that every time I press Alt+...

0
Q: Installed matplotlib via cygwin; "no module named matplotlib"?

Jossie CalderonI've previously installed emacs using the command ./setup-x86_64.exe -q --packages=emacs. Running emacs new1.py opens new1.py in an emacs window. I tried doing the same process with ./setup-x86_64.exe -q --packages=matplotlib and with new1.py containing the line and only the line import matplotli...

 
5:20 PM
0
Q: How to make pandas work on AWS Lambda?

banananaLooks pandas is, again, a Python library written with C. So I cannot make it work on AWS Lambda, as all the Python libraries written with C. I installed the pandas package on my Mac, and Lambda says cannot find numpy (although it is already in my package), then I replace the numpy with this versi...

0
Q: Enthought Canopy gives different output on the same instruction in script vs. in iPython shell

Axoren print "sum(yhat == y) * (1.0/len(np.transpose(yhat)))" print sum(yhat == y) * (1.0/len(np.transpose(yhat))) Here, yhat and y are numpy row-vectors. This should give a numeric result. Instead, when run from a script it gives: sum(yhat == y) * (1.0/len(np.transpose(yhat))) [ 0. 0. 0. ...

0
Q: Does returning numpy array always produce a view?

Mali RemorkerI have noticed that , say, this function, def f(x): return(x) would always return a view of the numpy array. Is this generally true? Are there any weird corner-cases I have to take into consideration, or can I rely on the fact that when an array is an argument to the return statement I'm a...

0
Q: Defining a complex-valued, piecewise function

khpeekI'm trying to define a function f(x) which yields 1.0 for x = 0 and 1.0/(2j pi x) otherwise. Here is a 'test' script I'm using: import numpy as np def f(x): return np.piecewise(x,[x==0],[1.0, lambda x: 1.0/(2j*np.pi*x)]) x = np.linspace(-1,1,21) print(x) print(f(x)) If the lambda functi...

0
Q: Pandas - Graphing Unstacked DataFrame with Multiple Columns

DeadCakeI have a DataFrame in Pandas that looks like this when unstacked Unique Sessions Date 2016-06-21 2016-06-29 Name ABCD 995 4,088 EFGH 8 25 OPEF 1 1 How do I get Pandas to plot a stacked bar chart from this DataFrame with th...

0
Q: Pandas Panel Merge

Doug BaldwinWhat is the current, best Pandas recipe for merging panel data, such as the following: p = pd.Panel(np.random.randn(2,5,4), items=['IBM', 'AA'], major_axis=pd.date_range('1/1/2000', periods=5), minor_axis=['Open', 'High', 'Low', 'Close']) dp = pd.Panel(np.random.randn(2,1,1), ite...

1
Q: Python equivalent for matlab's perms

STL93Is there an equivalent method in numpy or scipy for matlab's perms function? In matlab, perms returns a matrix of all possible permutations of the input in reverse lexicographical order.

0
Q: Need examples for numpy basic indexing with `non-ndarray sequence`

nn0pIn numpy doc about basic slicing, there is a situation described as: basic slicing is also initiated if the selection object is any non-ndarray sequence (such as a list) containing slice objects, the Ellipsis object, or the newaxis object, but not for integer arrays or other embedded sequence...

0
Q: Can highly detailed and sharp GUI's be made with Python's tKinter or wxWindows?

spacemonkeyI want to use Kivy but it's not meant for what I need to do. Which is build a multi-window desktop application. This leaves few other modern options for Python. Before I go down the rabbit hole of trial and error, can anyone confirm that it's possible to build a great looking desktop application ...

0
Q: Boolean expression in column indexer (Pandas) 'is' operator not working

Juan DavidWhen I use: df = data2analyse.loc[data2analyse.bool_var1 | data2analyse.bool_var2 | data2analyse.bool_var3, 'some column'] works properly. But if I use df = data2analyse.loc[data2analyse.bool_var1 is True | data2analyse.bool_var2 is True | d...

1
Q: changing size of scattered points in matplotlib

Jabberwock StompI am doing some plotting using cartopy and matplotlib, and I am producing a few images using the same set of points with a different domain size shown in each image. As my domain size gets bigger, the size of each plotted point remains fixed, so eventually as I zoom out, things get scrunched up, ...

0
Q: How to optimize changing a value in a Pandas Data Frame column

puzzlerI'm trying to find how much a stock will change from a given day to n days in the future. The only problem is that it takes about a minute to run this on 1000 lines of data and I have millions of lines. I think the 'lag' is caused by the line: stocks[0][i][string][line[index]] = adjPctChange(l...

0
Q: Python offset column value with previous record value if the record meets a condition

AmberI'm brand new to Python and am stuck on how to conditionally offset values. I've successfully been able to use the shift function when I just need to create a new column. However, this doesn't seem to work with a function. Original df: BEGIN SPEED SPEED_END 322 28 0 341 0 ...

0
Q: Extracting a variable from a netCDF file using python without value repeating

user6534801I am trying to output the precipitation for each year, but when I print precip I get the same value which is 9.969209968386869e+36. import arcpy import numpy import netCDF4 f =netCDF4.Dataset('Y:\\Projects\\ToriW\\NC Files\\TP40Years.nc', 'r',Format='NetCDF4') #The dimensions and variables of ...

0
Q: python: period over period growth, and average of growth

Trexion KamehaI have some stock data EPS data over the past 4 quarters and would like to do 2 things: 1) Calculate the change period over period change 2) Calculate the average of the period over period change. pd_total=pd.DataFrame.from_items([ ('Ticker', ['A','A','A','A','B','B','B','B...

 
6:24 PM
0
Q: dictionary values as column labels in matplotlib

Shan-DesaiI have the following dict: packetsNeeded = { u'hydrogen': 150, u'helium': 143, u'lithium': 122} I am using matplotlib to plot a bar graph for each of the keys and the values of the dictionary above. I have managed to plot the bar chart using the following co...

 
6:38 PM
0
Q: Memoizing decorator with retries, part 2

DannnnoA while ago I asked this question Memoizing decorator that can retry and then promptly forgot about it. I more recently saw Python decorator for retrying w/exponential backoff and wanted to add backoff, but figured I should improve what I already have first. I have taken some of the suggestions o...

0
Q: what's the easiest way to load array data from a file in Python?

aaragonI know Matlab has some nice syntax where you can put into a file array definitions, like A = [[1,2,3],..., and then you can import that file and all those definitions are read automatically. I would like to do something similar in Python. Basically I'm looking for the easiest way to read tabular ...

0
Q: conda version of pandas mismatch

JB LepetitI use the Anaconda suite for python. I do import pandas as pd and then pd.show_versions() it shows pandas: 0.17.1 but if I do !conda list it shows pandas 0.18.1 Why are those different ? Why is the imported pandas version less up to date than the one in con...

3
Q: Multiprocessing with pool in python: About several instances with same name at the same time

CrazyChrisI'm kind of new to multiprocessing. However, assume that we have a program as below. The program seems to work fine. Now to the question. In my opinion we will have 4 instances of SomeKindOfClass with the same name (a) at the same time. How is that possible? Moreover, is there a potential risk wi...

 
6:52 PM
0
Q: How to remove the legend in a seaborn stripplot? AttributeError: Unknown property legend

ShanZhengYangThe seaborn stripplot has a function which allows hue. Using the example from https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.stripplot.html import seaborn as sns sns.set_style("whitegrid") tips = sns.load_dataset("tips") ax = sns.stripplot(x=tips["total_bill"]) ax = sns.strip...

 
7:02 PM
0
Q: Pandas: add column with the most recent values

IlyaI have two pandas dataframes, both index with datetime entries. The df1 has non-unique time indices, whereas df2 has unique ones. I would like to add a column df2.a to df1 in the following way: for every row in df1 with timestamp ts, df1.a should contain the most recent value of df2.a whose times...

0
Q: Sum a matrix along an axis given a weight vector using numpy

RyanDoes numpy provide a built-in way to sum a matrix along an axis given a corresponding weight vector? My goal is to get z as output: q = np.array([[1, 2, 3], [10, 20, 30]]) w = [.3, .4] z = (q[0] * w[0]) + (q[1] * w[1]) print z >> [ 4.3 8.6 12.9] If not, is there an efficient way to perfor...

 
7:21 PM
-3
Q: Select rows given 2 columns, if a value is repeated in another column

amc1 down vote favorite I have a pandas dataframe NAME VALUE A cat A bird B dog A cat C dog B fish I would like to add a column if words in column "Name" contain a value in "Value" that occurs more than once, corresponding to the name...

0
Q: Tornado secure websocket timeout

Sese SchneiderMy server got 2 Ip's (ip1 & ip2) i recently added ip2. When i try to open my tornado websocketserver on ip1 (where apache2 is running) everything is fine, i specify a port e.g. 22000 and can connect to my socket via wss://domain.tld:22000/sub However as soon as i configured tornado to listen on ...

0
Q: Barplot/line plot on same plot, but different axis and line plot in front of barplot

CharlesI'm using pandas to plot some data. If I plot this: import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'a': [100, 200, 150, 175], 'b': [430, 30, 20, 10]}) fig, ax1 = plt.subplots(figsize=(15, 10)) df['b'].plot(kind='bar', color='y') df['a'].plot(kind='li...

0
Q: Same equation gives different values in Matlab and Numpy?

user3769033I'm trying to convert a function from Matlab to Python. The Matlab function is: function [f,df_dr1,df_dr2,g,dg_dr1,dg_dr2] = f_eval_2eq(r1,r2,r3,z1,z2,z3,n1,n2,n3) f = (r1)./sqrt(r1.^2 + z1.^2)... - (n2/n1)*(r2-r1)./sqrt((r2-r1).^2 + z2.^2); df_dr1 = 1./sqrt(r1.^2 + z1.^2)... - r1.^2./(r...

0
Q: Exponential backoff generator

DannnnoExponential backoff in the context of various networking protocols looks something like this: When a collision first occurs, send a “Jamming signal” to prevent further data being sent. Resend a frame after either 0 seconds or 51.2μs, chosen at random. If that fails, resend the frame ...

0
Q: Matplotlib Quiver Arrows not visible

MickI am trying to use Matplotlib's quiver to see if the gradient vectors for the circle are coming out right, but when I display the quiver image over the circle image, I can't see the gradient arrows. I tried to scale the arrows and change the width of the arrows, but still can't see them. Here is...

0
Q: Pylab - Change historgram colors based on RGB axis

nickfrenchyI have a python dictionary I'm using to get a histogram: colors = {(97, 103, 105): 638059, (129, 140, 143): 562526, (55, 58, 62): 431610, (189, 193, 193): 460605} import pylab as pl import numpy as np dict_index = np.arange(len(colors)) pl.bar(dict_index, colors.values(), align='center', width=...

0
Q: How to generate noise with a chosen spatial distribution with numpy?

JulepI want to add noise to an image in a way similar to this : import numpy as np import matplotlib.pyplot as plt myImage = plt.imread('Pikachu.png') noise = np.random.normal(0, 0.1, (myImage.shape[0], myImage.shape[1])) noisyImage = myImage + noise However, I would need the noise to be more int...

0
Q: Making a relatively complex datetime function more pythonic

meeplI'm working on a function that returns a specific set of times for a given timezone and a given frequency; day, week, month. For any given timezone and a frequncy the function will return the unixtime hour start and unixtime hour end of the last full frequency given. For example, the last full ...

0
Q: Matplotlib, I'm making a 2d histogram and I want to a triangular axes extension similar to what is done with colorbars

user6509953Using MATPLOTLIB.PYPLOT I am making a 2d histogram where I want to limit my view to a certain range of y-values but at the same time I want to cluster all values below a certain number at the bottom of the y-axis. What i'm thinking of is similar to how you can make a colorbar have triangular exte...

0
Q: Numpy apply_along_axis not returning ndarray subclass

SnoozerI have an ndarray subclass, with __array_wrap__ properly implemented, np.apply_along_axis isn't returning instances of my subclass, but rather ndarrays. The code below replicates my problem: import numpy as np class MySubClass(np.ndarray): def __new__(cls, input_array, info=None): ...

0
Q: What is the best way to find the longest number of "0"s in an array in python/numpy/any other module in python?

Nabeel EhI have an array with 0's repeating multiple times but I want to find the longest set of 0s. For ex myArray= [[1,0],[2,0],[3,0][4,0][5,1][6,0][7,0][8,0][9,0][10,0][11,0][12,0][13,1][14,2][15,0][16,0][17,0][18,0][19,1][20,0]] So the y coordinate has zeros repeating continuously a few times but I ...

 
8:31 PM
0
Q: Front-End Language Selection given Back-End Languages Tcsh, Gawk, and Matlab

HighEnergyI have written back end code in Tcsh, Gawk, and Matlab. I need to write some front end for this code. I intend to develop a desktop application. Which language should I use for back-end and front-end (can be different): Python, Java, or C++? Mainly, I am asking which of the following works well w...

0
Q: Python - Creates a Kinesis Stream, Firehose, and Lambda Event Source from config file

BlexyI'm in the process of writing a python script for automating a data ingestion pipeline using Amazon Web Service's Kinesis Stream, Firehose and Lambda. This is my first stab at writing python, but I do have some experience with Javascript and Node.js. Scripts are organized as follows: build_pip...

 
8:50 PM
0
Q: "A value is trying to be set on a copy of a slice from a DataFrame" even when .loc is used

Juan DavidI don't understand why this is happening if I'm using .loc to create the another_df dataframe >>> df = DataFrame({'a':range(0,10), 'b':range(10,20), 'c':range(20,30)}, index = range(0,10), columns=['a', 'b', 'c']) >>> df a b c 0 0 10 20 1 1 11 21 2 2 12 22 3 3 13 23 4 4 14 ...

0
Q: Get "Adj Close" using pandas DataReader

Evy555I just switched from pandas.io to pandas_datareader and I'm having difficulties pulling in just Adjusted Close prices. before I could use the following code pd.io.data.get_data_yahoo(stock, start, end)['Adj Close'] now when I try the datareader (imported as web) it does not work. web.get_dat...

0
Q: Pandas: Replacing Non-numeric cells with 0

Hassam SheikhI was have the Pandas Dataframe in this format 0 or LIST requests 1 us-west-2 2 1.125e-05 3 0 4 3.032e-05 5 0 6 7.28e-06 7 or LIST requests 8 3.1e-0...

 
9:13 PM
0
Q: Python Decimal to Binary converter

ConfettimakerThere is no input validation for this, but that aside, I would appreciate it if anyone could help me improve the logic of this script. import math #Input num = input("Enter a whole number: ") #Floors input in case of a non whole number decimal = math.floor(float(num)) #Variables exp = 0 divTwo...

0
Q: Dictionary with values as tuples in pandas

lostsoul29I have a DataFrame as follows: In [23]: df = pandas.DataFrame({'Initial': ['C','A','M'], 'Sex': ['M', 'F', 'F'], 'Age': [49, 39, 19]}) df = df[['Initial', 'Sex', 'Age']] df Out[23]: Initial Sex Age 0 C M 49 1 A F 39 2 M F 19 My goal is to ...

 
9:40 PM
0
Q: Populating pandas dataframe using conditional group from another dataframe

PeppeJeffersonI have two dataframes, one being a list of teams and scores sorted by date, and the second individual players with the date. I have 60 columns of matching stats in these dataframes, and I am trying to have a code that replaces the values in each column in df2 with the average the opponent had in ...

 
9:52 PM
0
Q: Converting a dataframe column to float

StaceyI have a dataframes called historic_price with two columns called 'price' and 'item' that I am trying to multiple together storing the result in a different data-frame called dayData, but I get the exception: TypeError: can't multiply sequence by non-int of type 'float' The 'price' column look...

0
Q: Python's Pandas: Getting values from column name inputted as string (as list/array)

jazz minkI've been using pandas a lot lately, and have run across a slight impasse.. I want to use data contained in a column as a numpy array, usually I do this: array = df.colname.values Which results in an array of length(array) = numberofdatapoints However, I am working with column names as strin...

0
Q: Apache Spark computing on numpy matrix results in UnpicklingError: NEWOBJ class argument has NULL tp_new

GopalaVery strange problem I am running into where using spicy.spacial distance matrix computation works fine, but using a custom function for distance matrix results in a Spark error. My data looks like this: 33.848366,-84.3733852,A,1234 33.848237299999994,-84.37318470000001,A,1234 33.8488057,-84.3...

0
Q: pandas: how to store a list in a dataframe?

AlanHI want to set a cell value as a list. Say for example: df.loc['a']['b'] = ['one', 'two', 'three'] However, I'm unable to do so as I get the following error: ValueError: Must have equal len keys and value when setting with an iterable My dataframe currently is just all zeros and is nxn. Is t...

0
Q: Pandas dataframe fillna() only some columns

SaitI am trying to fill none values in a Pandas dataframe with 0's for only some subset of columns. When I do: import pandas as pd df = pd.DataFrame(data={'a':[1,2,3,None],'b':[4,5,None,6],'c':[None,None,7,8]}) print df df.fillna(value=0, inplace=True) print df The output: a b c 0 1....

0
Q: clustering a given bin of compounds

CodeMAKCould anyone explain to me how one cluster a given set of molecules (given below) as SMILES, and pick one representative structure from each cluster in smiles format using python and or rdkit. thanks

0
Q: Why is my date column showing up as empty?

William I have calculations of a tick data file I get daily that I'm preparing to append to a table daily. The final DataFrame should show the ticker, average spread, max spread, and date. Everything else works fine except for the date column which shows up empty. The tick data itself has a column name...

 
10:38 PM
0
Q: Non-repeatability (plagiarism and time travel)

Jan KuikenI heard/read that writers of texts can be recognized by counting their used words and compare these to previous works. As a code kata I experimented with this a bit and found some disturbing facts. 'Romeo and Juliet' was written by one of the Bronte sisters. Shakespeare plagiarized it from the...

 
11:13 PM
0
Q: Data-frame Object has no Attribute 'Number'

Mouna BelaidI know that this kind of question was asked before and I've checked all the answers and I have tried several times to find a solution but in vain. In fact I call a Dataframe using Pandas. I've uploaded a csv.file. enter image description here When I type data.Country and data.Year, I get the 1st...

0
Q: Pandas: Solving for the threshold of highest values for a time-series dataset

Eternal BlueGivens: I have a set of time-series data for a day, say 96 values. I have a cumulative value, say 101 units over a given period. Problem: I need to find the threshold, X, where all values above that threshold sum up to the given cumulative value, 101. See below chart for visual. (My reputation i...

 
11:30 PM
0
Q: difference between numpy randint and floor of rand

aphnum_draws = int(1e6) arr1 = np.random.randint(0, 10, num_draws) arr2 = np.floor(10*np.random.rand(num_draws)) Could someone with expertise in the internals of numpy.random comment on whether arr2 obeys formally equivalent statistics to arr1? In experiments I have done, the distributions appear ...

 
11:47 PM
1
Q: Line Profiling inner function with Cython

C_Z_I've had pretty good success using this answer to profile my Cython code, but it doesn't seem to work properly with nested functions. In this notebook you can see that the profile doesn't appear when the line profiler is used on a nested function. Is there a way to get this to work?

0
Q: plotting seaborn graphs withoug using maplotlib object

liv2hakI am trying to learn basic data analytics using seaborn.I have the following program. import pandas as pd import seaborn as sns import matplotlib.pyplot as plt df = pd.read_csv('sheep.csv') bp = sns.barplot(x=df.Year, y=df.sheep_pop_1000) bp.set(xlabel='Year', ylabel='Sheep population in Eng...

0
Q: Numpy array vs. C++ vector in memory efficiency

Alexander WhatleyWhich object is generally smaller in memory given the exact same data: a numpy array with dtype int64 or a C++ vector of type int? For example: v = np.array([34, 23]) std::vector<int> v { 34,23 };

 

« first day (859 days earlier)      last day (1329 days later) »