Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
370,400
26,837,998
Pandas Replace NaN with blank/empty string
<p>I have a Pandas Dataframe as shown below:</p> <pre><code> 1 2 3 0 a NaN read 1 b l unread 2 c NaN read </code></pre> <p>I want to remove the NaN values with an empty string so that it looks like so:</p> <pre><code> 1 2 3 0 a "" read 1 b l unread 2 c "" ...
<pre><code>df = df.fillna('') </code></pre> <p>This will fill na's (e.g. NaN's) with <code>''</code>.</p> <p><code>inplace</code> is possible but should be avoided as <a href="https://github.com/pandas-dev/pandas/issues/16529" rel="nofollow noreferrer">it will be deprecated</a>:</p> <pre><code>df.fillna('', inplace=Tru...
python|pandas|dataframe|nan
572
370,401
26,445,582
Cython boolean indexing optimization
<p>What is the best way to convert the following code to <code>cython</code></p> <p>Given the following example:</p> <pre><code>#setup example data Z and A Z = np.random.randn(10,10) A = np.random.randn(10,10) A[0,1] = np.nan A[1,3] = np.nan A[5,3] = np.nan A[3,5] = np.nan B = np.isnan(A).transpose() C = Z[B * B.tr...
<p>The right way to create a buffer which will take <code>np.nan</code> values is using <code>np.float_t</code> or <code>np.double_t</code>. If you try using a integer buffer the following error will raise:</p> <pre><code>ValueError: cannot convert float Nan to integer </code></pre> <p>Then, you could use something l...
python|arrays|numpy|cython|nan
1
370,402
26,456,532
Update columns in Pandas Dataframe rows when criteria in the rest of the row are met (in SQL UPDATE)
<p>The closest I've found to an answer is this: <a href="https://stackoverflow.com/questions/23330654/update-a-dataframe-in-pandas-while-iterating-row-by-row">Update a dataframe in pandas while iterating row by row</a></p> <p>However, it doesn't answer my question. Here's what I want to do:</p> <pre><code>#for each d...
<p>You'll not need to iterate over the rows. This can be done using vectorized methods. Create a boolean mask based on your selection criteria.</p> <pre><code>city_state_mask = (df.city == 'C') &amp; (df.state == 'C') </code></pre> <p>Use that to select the rows and then make the assignment. You need to select the va...
python|python-2.7|pandas
4
370,403
26,433,835
Use np.loadtxt to split a column while reading
<p>Is there any way to use np.loadtxt and the converters argument to split a column into two columns?</p> <p>The lines in my text file looks like this:</p> <pre><code>1 2 A=3;B=4 </code></pre> <p>and I want to read this in as:</p> <pre><code>[1,2,3,4] </code></pre> <p>The file is quite large so reading line by lin...
<p>You can create a generator that calls a parser and pass it to <code>np.genfromtxt</code>:</p> <pre><code>import re import numpy as np def parser(s): for i in re.findall('[a-zA-Z]+', s): s = s.replace(i, '') return s.replace('=', '').replace(';',' ') gen = (parser(line) for line in open('demo.txt'...
python|file-io|numpy|text-files|converters
1
370,404
26,819,295
Splitting list according to criteria (gender)
<p>I'm a beginner in python, just learning how to write functions. I've got a list of weights and gender, and am trying to split it to create two new lists according to the gender criteria. Using for loops, I've been successful so far: </p> <pre><code>df = pd.read_csv('brainweight.csv') w = list(df['Weight']) s = list...
<pre><code>df = pd.read_csv('brainweight.csv') w = list(df['Weight']) s = list(df['Sex']) def list_by_gender(): females = [] males = [] for sex, weight in zip (s, w): if sex == 'f': females.append(weight) else: males.append(weight) return males,females male_list,...
python|list|function|pandas|append
0
370,405
26,476,902
NameError: global name 'imshow' is not defined but Matplotlib is imported
<p>I'm currently writing a python script which plots a numpy matrix containing some data (which I'm not having any difficulty computing). For complicated reasons having to do with how I'm creating that data, I have to go through terminal. I've done problems like this a million times in Spyder using <code>imshow()</code...
<p>To make your life easier you can use</p> <pre><code>from pylab import * </code></pre> <p>This will import the full pylab package, which includes matplotlib and numpy.</p> <p>Cheers</p>
python|numpy|matplotlib|terminal|imshow
1
370,406
26,496,383
Comparing neighbors of each element of an array with for-loop
<p><br></p> <p>I'm a new Python user and I'm finding the combination of Python+Numpy+Matplotlib amazing. I know a little of C and I've been asked to use Python in a work, everything was going well, Numpy has these incredible functions that can do almost everything I need. But I think I stepped on my first stone when I...
<p><code>for</code> inside Python does work in little different way than in C. Running (even in shell) some simple examples could help you a little</p> <pre><code>collection = ["cat", "dog", "horse"] for animal in colection: print animal </code></pre> <p>As you can see <code>for</code> assigns to variable <code>...
python|arrays|for-loop|numpy|indexing
0
370,407
39,359,272
Add new columns to pandas dataframe based on other dataframe
<p>I'm trying to set a new column (two columns in fact) in a pandas dataframe, with the data comes from other dataframe.</p> <p>I have the following two dataframes (they are example for this purpose, the original dataframes are so much bigger):</p> <pre><code>In [116]: df0 Out[116]: A B C 0 0 1 0 1 2 3...
<p>This is a basic application of <code>merge</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="noreferrer">docs</a>):</p> <pre><code>import pandas as pd df2 = pd.merge(df0,df1, left_index=True, right_index=True) </code></pre>
python|pandas|dataframe|machine-learning|data-science
6
370,408
39,177,556
exception when get a subset of a pandas data frame
<p>I want to get the first, 2nd and 4th column of a data frame, which is column <code>c_a,c_b,c_d</code>, what is wrong with my code?</p> <p>I post my code, data (123.csv) and error message,</p> <pre><code>sample = pd.read_csv('123.csv', header=None, skiprows=1, dtype={0:str, 1:str, 2:str, 3:float}) sample.column...
<p>You need to use <code>df.iloc[:, [0, 1, 3]]</code> instead (or <code>df[[0, 1, 3]]</code>).</p> <p>Comma separates the row indexer and the column indexer. </p>
python|python-2.7|pandas|numpy|dataframe
2
370,409
38,998,358
Add a column to a data frame based on percentiles calculated by group
<p>I have a data frame with the following form</p> <pre><code>Group Value A 0.20 A 0.86 A 1.42 A 0.35 B 1.77 B 0.56 B 0.21 . . . . </code></pre> <p>I want to add a column <code>Alert</code> that takes two possible values: </p> <ul> <li>'1' ...
<p>I think....(new to this myself) that the use of <code>.apply</code> means the function is applied to the contents of the 'Name' column. Instead consider...</p> <pre><code>df['Alert'] = df['Value'].apply(your_function) </code></pre>
python-2.7|pandas|pandas-groupby
0
370,410
39,267,614
"CSV file does not exist" for a filename with embedded quotes
<p>I am currently learning Pandas for data analysis and having some issues reading a csv file in Atom editor. </p> <p>When I am running the following code:</p> <pre><code>import pandas as pd df = pd.read_csv("FBI-CRIME11.csv") print(df.head()) </code></pre> <p>I get an error message, which ends with </p> <blockq...
<p>Have you tried?</p> <pre><code>df = pd.read_csv("Users/alekseinabatov/Documents/Python/FBI-CRIME11.csv") </code></pre> <p>or maybe</p> <pre><code>df = pd.read_csv('Users/alekseinabatov/Documents/Python/"FBI-CRIME11.csv"') </code></pre> <p>(If the file name has quotes)</p>
python|csv|pandas|atom-editor
19
370,411
39,191,066
pandas merge columns in same dataframe
<p>I have dataframe with 4 columns. </p> <pre><code> Column1 Column2 Column3 Column4 0 Item1 Value1 Item2 Value2 1 Item3 Value3 Item4 Value4 2 Item5 Value5 Item6 Value6 3 Item7 Value7 Item8 Value8 4 Item9 Value9 Item10 Value10 5...
<p>Okay, maybe this might help:</p> <pre><code>In [571]: df Out[571]: Column1 Column2 Column3 Column4 0 Item1 Value1 Item2 Value2 1 Item3 Value3 Item4 Value4 2 Item5 Value5 Item6 Value6 3 Item7 Value7 Item8 Value8 4 Item9 Value9 Item10 Value10 5 Item11 Value11 Item12 Valu...
python|pandas
2
370,412
39,020,493
Appending a DataFrame to another DataFrame, at a specific MultiIndex
<p>In the following <code>DataFrame</code>, namely <code>df1</code>:</p> <pre><code>In[0]: df1 Out[0]: A B first second bar one 1.764052 0.400157 one 0.978738 2.240893 one 1.867558 -0.977278 two 0.950088 -0.151357 </code></pre> <p>...
<p>If you want to manually insert data into an existing dataframe, you need to decide a couple of things.</p> <ol> <li>Where are you going to insert it? I figure this out by finding the first instance where the index is <code>('bar', 'one')</code>.</li> <li>What are you going to call the data? Put another way, what ...
python-3.x|pandas|dataframe|multi-index
1
370,413
39,132,469
How to interpret `scipy.stats.kstest` and `ks_2samp` to evaluate `fit` of data to a distribution?
<p><strong>I'm trying to evaluate/test how well my data fits a particular distribution.</strong> </p> <p>There are several questions about it and I was told to use either the <code>scipy.stats.kstest</code> or <code>scipy.stats.ks_2samp</code>. It seems straightforward, give it: (A) the data; (2) the distribution; a...
<p>So the null-hypothesis for the KT test is that the distributions are the same. Thus, the lower your p value the greater the statistical evidence you have to reject the null hypothesis and <em>conclude the distributions are different</em>. The test only really lets you speak of your confidence that the distributions ...
python|numpy|machine-learning|scipy|statistics
10
370,414
39,274,824
find and replace using multiple criteria pandas python
<p>I have the following dataframe (df):</p> <pre><code>loc pop_1 source_1 pop_2 source_2 a 99 group_a 77 group_b b 93 group_a 90 group_b c 58 group_a 59 group_b d 47 group_a 62 group_b </code></pre> <p>I create an additional column 'upper_limit':</p> <pre><code>df['upper_limit'] = df[['pop_1',...
<blockquote> <p>I now want to add another column that looks at the values in 'upper_limit', compares them to pop_1 and pop_2 and then selects the text from source_1 or source_2 when they match.</p> </blockquote> <p>You can do it much more simply using <a href="http://docs.scipy.org/doc/numpy/reference/generated/nump...
python|pandas
1
370,415
39,022,527
Pandas, subtract values based on value of another column
<p>In Pandas, I'm trying to figure out how to generate a column that is the difference between the time of the current row and time of the last row in which the value of another column is True:</p> <p>So given the dataframe:</p> <pre><code>df = pd.DataFrame({'Time':[5,10,15,20,25,30,35,40,45,50], 'Event_O...
<p>Using <code>df.Event_Occured.cumsum()</code> gives you distinct groups to <code>groupby</code>. Then applying a function per group that subtracts the first member's value from every member gets you what you want.</p> <pre><code>df['Time_since_last'] = \ df.groupby(df.Event_Occured.cumsum()).Time.apply(lambda x...
python|pandas
3
370,416
39,359,061
Align python arrays with missing data
<p>I have some time series data, say:</p> <pre><code># [ [time] [ data ] ] a = [[0,1,2,3,4],['a','b','c','d','e']] b = [[0,3,4]['f','g','h']] </code></pre> <p>and I would like an output with some filler value, lets say None for now:</p> <pre><code>a_new = [[0,1,2,3,4],['a','b','c','d','e']] b_new = [[0,1,2,3,4],['f'...
<p>How about this? (I'm assuming your definition of <code>b</code> was a typo, and I'm also assuming you know in advance how many entries you want.)</p> <pre><code>&gt;&gt;&gt; b = [[0,3,4], ['f','g','h']] &gt;&gt;&gt; b_new = [list(range(5)), [None] * 5] &gt;&gt;&gt; for index, value in zip(*b): b_new[1][index] = val...
python|numpy
4
370,417
39,339,935
Pandas - dropping rows with missing data not working using .isnull(), notnull(), dropna()
<p>This is really weird. I have tried several ways of dropping rows with missing data from a pandas dataframe, but none of them seem to work. This is the code (I just uncomment one of the methods used - but these are the three that I used in different modifications - this is the latest):</p> <pre><code>import pandas a...
<p>Your example DF has <code>NaN</code> and <code>NaT</code> as strings which <code>.dropna</code>, <code>.notnull</code> and co. won't consider falsey, so given your example you can use...</p> <pre><code>df[~df.isin(['NaN', 'NaT']).any(axis=1)] </code></pre> <p>Which gives you:</p> <pre><code> A B C 0 1 1 1 ...
python|pandas
17
370,418
39,053,734
Improving the performance of repetitive groupby operations
<p>I have a DataFrame with MultiIndex which is basically a binary matrix:</p> <pre><code>day day01 day02 session session1 session2 session3 session1 session2 session3 0 1 0 0 0 0 0 1 0 0 1 1 ...
<p>Assuming a regular data format (equal number of days and sessions across each row), here's a NumPy based approach using <code>np.unique</code> with the output having their indexes in sorted order -</p> <pre><code># Extract array a,b = df.columns.levels arr = df.values.reshape(-1,len(a),len(b)) # Get session counts...
python|pandas|numpy
2
370,419
39,260,010
Setting the day in a pandas frame column, from a string list containing only the hours
<p>I wonder if anyone could please help me with this issue: I have a pandas data frame (generated from a text file) which should have a structure similar to this one:</p> <pre><code>import pandas as pd data = {'Objtype' : ['bias', 'bias', 'flat', 'flat', 'StdStar', 'flat', 'Arc', 'Target1', 'Arc', 'Flat', 'Flat', '...
<p>To find the time delta between 2 rows:</p> <pre><code>df.UT - df.UT.shift() Out[48]: 0 NaT 1 00:05:00 2 00:05:00 3 -1 days +00:05:00 4 00:05:00 5 00:05:00 6 00:05:00 7 00:05:00 Name: UT, dtype: timedelta64[ns] </code></pre> <p>To ...
pandas|numpy|dataframe|datetime64
1
370,420
39,001,856
Convert Tecplot ascii to Python numpy
<p>I want to convert a <em>Tecplot</em> file into an array but I don't know how to do it. Here is an extract of the file:</p> <pre><code>TITLE = "Test" VARIABLES = "x" "y" ZONE I=18, F=BLOCK 0.1294538E-01 0.1299554E-01 0.1303974E-01 0.1311453E-01 0.1313446E-01 0.1319080E-01 0.1322709E-01 0.1323904E-01 0.133175...
<p>Solved it with the last option:</p> <pre><code>arrays = [] with open(file, 'r') as a: for line in a.readlines(): A = re.match(r'TITLE = (.*$)', line, re.M | re.I) B = re.match(r'VARIABLES = (.*$)', line, re.M | re.I) C = re.match(r'ZONE (.*$)', line, re.M | re.I) if A or B or C: ...
python|numpy|io|converter
1
370,421
39,158,062
How to add corresponding elements of 2 multidimensional matrices in python?
<p>I have 2 multidimensional arrays , both of size 128X640X5. 5 is the number of channels for the matrices. I wish to add the respective channel values of both the matrices for every point in the matrices. For eg if we have A and B as 2 matrices, I wish to do an operation something like this: A(x,y,0)+B(x,y,0) =A(x,y,0...
<p>In order to add each corresponding point of a <code>ndarray</code> in numpy you can use numpy's add function (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html" rel="nofollow noreferrer">numpy.add</a>).</p> <p>It will add up each corresponding point of two ndarrays which have the <strong>sa...
python|numpy|image-processing
0
370,422
39,040,250
how to read json file with pandas?
<p>I have scraped a website with scrapy and stored the data in a json file.<br> Link to the json file: <a href="https://drive.google.com/file/d/0B6JCr_BzSFMHLURsTGdORmlPX0E/view?usp=sharing" rel="nofollow">https://drive.google.com/file/d/0B6JCr_BzSFMHLURsTGdORmlPX0E/view?usp=sharing</a></p> <p>But the json isn't stand...
<p>try this:</p> <pre><code>import json with open('data.json') as data_file: data = json.load(data_file) </code></pre> <p>This has the advantage of dealing well with large JSON files that do not fit in memory</p> <p>EDIT: Your data is not valid JSON. Delete the following in the first 3 lines and it will validate...
python|json|list|pandas|scrapy
10
370,423
39,297,284
Is there a faster way to change the 0s in a linespace?
<p>I'm working with Jupyter Notebooks and I need to do some calculations using a <code>linspace</code> which go to <code>b</code> from <code>a</code>, the problem is that I get the Zero Division Error, so I was wondering if there was a faster way to change the 0s in a linespace, instead of going trough each element, ch...
<pre><code>a= numpy.linspace(...) zero_mask = a==0 </code></pre> <p>is that what you mean?</p>
python|numpy
2
370,424
19,618,802
Finding specific values and replacing them by others. Python
<p>I am very new to programming. I have code in matlab:</p> <pre><code>x2(x2&gt;=0)=1; x2(x2&lt;0)=-1; %Find values in x2 which are less than 0 and replace them with -1, %where x2 is an array like 0,000266987932788242 0,000106735120804439 -0,000133516844874253 -0,000534018243439120 </code></pre> <p>I tried to do ...
<p>You can use numpy's ability to index over boolean array.</p> <pre><code>import numpy as np x = np.array([-5.3, -0.4, 0.6, 5.4, 0.0]) not_neg = x &gt;= 0 # creates a boolean array x[not_neg] = 1 # index over boolean array x[~not_neg] = -1 </code></pre> <p>Result:</p> <pre><code>&gt;&gt;&gt; x array([-1., -1., 1...
python|arrays|matlab|for-loop|numpy
1
370,425
19,646,135
Memory Error while calling genfromtxt method
<p>Code : </p> <pre><code>import scipy as sp import matplotlib.pyplot as plt data=sp.genfromtxt("data/train.tsv", delimiter ="\t", dtype="string", comments=None, skip_header=1) x = data[:,0] y = data[:,1] x = x[~sp.isnan(y)] y = x[~sp.isnan(y)] DataOfInterest=x["avglinksize"] EphemeralOrEvergreen=x["label"] plt.sca...
<p>Python runs out of memory because the object you're trying to create is simply to big. The reason is that your data contains some very large strings (noticed this from your previous question).</p> <p>The array <code>data</code> that you create only has a single <code>dtype</code>. The size of this dtype is chosen t...
python|arrays|numpy
0
370,426
19,613,404
numpy.diff() use with pandas DataFrame error
<p>I have a pandas DataFrame, with float64's in the 'mass' column. I use <code>np.diff()</code> to find the first difference of this data.</p> <p>The problem: the size changes if I use data.mass versus, data.mass.values Note, this 'bug' is also seen in the fact that the min, max, and mean are not the same...</p> <pre...
<p>based on @jeff 's comments, using the <code>.diff()</code> method of a pandas DataFrame does give the correct results as shown: So this is clearly just a bad interaction between a numpy method and the current version of pandas. (numpy 1.7.1 for python 2.7 and pandas 0.12.0)</p> <pre><code>import pandas as pd import...
python|numpy|pandas
1
370,427
19,577,673
Arbitrary image slice with python/numpy
<p>I would like to plot a 1D profile of a 2D image along an arbitrary line. The code below loads the image data hosted on github and plots it:</p> <pre><code>import urllib import numpy as np import matplotlib.pyplot as plt url = "https://gist.github.com/andreiberceanu/7141843/raw/0b9d50d3d417b1cbe651560470c098700df5a...
<p>You want to use <code>scipy.ndimage.map_coordinates</code>. You need to build up a 2xn array that is the coordinates at which to sample and then do <code>map_coordinates(im, samples)</code>.</p> <p>I think this is it:</p> <pre><code>def sliceImage(I, a, b, *arg, **kws): from scipy import linspace, asarray ...
python|numpy|matplotlib|scipy
2
370,428
19,597,575
picking out elements based on complement of records in Python pandas
<p>I have a python pandas DataFrame question. There are two DataFrames containing records, <strong>df1</strong> and <strong>df2</strong>. They contain the following values:</p> <pre><code>df1: pkid start end 0 0 2005 2005 1 1 2006 2006 2 2 2007 2007 3 3 2008 2008 4 4 2009 200...
<p>This operation called <a href="http://en.wikipedia.org/wiki/Relational_algebra#Antijoin_.28.E2.96.B7.29" rel="nofollow"><code>antijoin (▷)</code></a> in relational algebra and SQL. I've tried to find native pandas operation for this, but found nothing.</p> <p>But you can do it functional way, don't know about perfo...
python|numpy|pandas
3
370,429
19,802,923
Using Python to Combine CSV Elements From Columns to Rows
<p>(Actual input CSV is comma-delimited as normal; I just showed my ideas as tables for ease of viewing.)</p> <p>Here's an example of what I want to do using Python 2.7 (Pandas if it's better/easier, but I also like learning python logic and pandas skips over a lot, though I may have to learn it for stuff like this):<...
<p>In [252]:</p> <pre><code>import pandas as pd import io f = io.BytesIO("""Price Name Text Number Choice URL Email 40 Foo Stuff 560 Y www.a.com a@a.com 60 Foo Things 280 N www.a.com 20 Foo Other 120 Y www.a.com ...
python|python-2.7|csv|pandas
2
370,430
19,611,729
Getting Google Spreadsheet CSV into A Pandas Dataframe
<p>I uploaded a file to Google spreadsheets (to make a publically accessible example IPython Notebook, with data) I was using the file in it's native form could be read into a Pandas Dataframe. So now I use the following code to read the spreadsheet, works fine but just comes in as string,, and I'm not having any luck ...
<p>Seems to work for me without the <code>StringIO</code>:</p> <pre><code>test = pd.read_csv('https://docs.google.com/spreadsheets/d/' + '0Ak1ecr7i0wotdGJmTURJRnZLYlV3M2daNTRubTdwTXc' + '/export?gid=0&amp;format=csv', # Set first column as rownames in data fram...
python|pandas|google-sheets|google-drive-api|google-apps
71
370,431
12,863,745
Getting started with numpy or scipy?
<p>I went through the descriptions of <code>numpy</code> and <code>scipy</code> as recommended by helpful contributors in the earlier posts. </p> <p>Since I am a beginner in Python, would you please assist me on this: for example, I have a file (<code>stats1.txt</code>) in a folder <code>c:\\programming</code>; this ....
<p>It will take some basic understanding of how python works, it is an object oriented language. So you basically parse the input file, Since you say the file has only one column, you just need to convert the values to numbers</p> <pre><code>with open('stats1.txt') as f: lines=[float(i) for i in f.xreadlines()] ...
python|numpy|python-2.7|scipy
1
370,432
12,867,867
Reducing an axis with numpy
<p>I have an <code>NxMx3</code> numpy array with <code>dtype=object</code>. I also have a function <code>f(a,b,c)</code> which takes the three elements in the last axis of this array and returns a <code>np.int32</code>. My question is how do I apply <code>f</code> to my <code>NxMx3</code> array to yield an <code>NxM<...
<p>You could use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.vectorize.html" rel="nofollow noreferrer"><code>vectorize</code></a>:</p> <pre><code>np.vectorize(f, otypes=[np.int32])(arr[:, :, 0], arr[:, :, 1], arr[:, :, 2]) </code></pre> <p>This can be simplified by axis rolling and iter...
python|numpy
3
370,433
13,191,887
Search numpy array inside numpy array
<p>I need to find if a numpy array is inside other numpy array, but it seems to work different to python lists. I tried to search this question in numpy documentation and internet, but not answer. This is an example:</p> <p><code> import numpy as np</p> <pre><code>m1=np.array([[1,2,3],[5,3,4]]) m2=np.array([5,4,3...
<p>To get the same behavior as <code>in</code> for lists, you could do something like this:</p> <pre><code>any(np.all(row == m2) for row in m1) </code></pre> <p>That does the loop over rows in python, which isn't ideal, but it should work.</p> <p>To understand what's going on with the numpy <code>in</code>, here's a...
arrays|search|numpy
3
370,434
13,219,041
How can I speed up transition matrix creation in Numpy?
<p>The following is the most basic way I know of to count transitions in a markov chain and use it to populate a transition matrix:</p> <pre><code>def increment_counts_in_matrix_from_chain(markov_chain, transition_counts_matrix): for i in xrange(1, len(markov_chain)): old_state = markov_chain[i - 1] ...
<p>Just for kicks, and because I've been wanting to try it out, I applied <a href="http://numba.pydata.org/">Numba</a> to your problem. In code, that involves just adding a decorator (although I've made a direct call so I could test the jit variants that numba provides here):</p> <pre><code>import numpy as np import n...
python|numpy|scipy
8
370,435
13,003,769
Joining Multiple Dataframes with Pandas with overlapping Column Names?
<p>I have multiple (more than 2) dataframes I would like to merge. They all share the same value column:</p> <pre><code>In [431]: [x.head() for x in data] Out[431]: [ AvgStatisticData DateTime 2012-10-14 14:00:00 39.335996 2012-10-14 15:00:00 40.210110 ...
<pre><code>In [65]: pd.concat(data, axis=1) Out[65]: AvgStatisticData AvgStatisticData AvgStatisticData AvgStatisticData 2012-10-14 14:00:00 39.335996 47.854712 54.171233 65.813114 2012-10-14 15:00:00 40.210110 55.041512 48.718387 7...
join|merge|pandas
16
370,436
13,029,029
Getting only those values that fulfill a condition in a numpy array
<p>There must a be a (very) quick and efficient way to get only elements from a numpy array, or even more interestingly from a slice of it. Suppose I have a numpy array:</p> <pre><code>import numpy as np a = np.arange(-10,10) </code></pre> <p>Now if I have a list: </p> <pre><code>s = [9, 12, 13, 14] </code></pre> <...
<p>How about:</p> <pre><code>In [19]: b = a[s] In [20]: b[b &gt; 0] Out[20]: array([2, 3, 4]) </code></pre>
python|arrays|numpy
33
370,437
29,055,256
Access subplot axes returned by pandas.DataFrame.plot()
<p>Is there a way I can access the axes returned by <code>pandas.DataFrame.plot(subplots=True)</code>? I'd like to give each plot a title (and access other attributes), but my current attempts only affect the last subplot.</p> <pre><code>svv[['Flow2 L/s','GWT','DOC mg/L', 'Hgtot ng/L', 'MeHg ng/L']].dropna().plot(subp...
<p>"Returned" means it is the result of the call to <code>plot</code>. You can just store it in a variable:</p> <pre><code>ax = svv[['Flow2 L/s','GWT','DOC mg/L', 'Hgtot ng/L', 'MeHg ng/L']].dropna().plot(subplots=True, figsize=(20, 20)) </code></pre>
python|python-2.7|pandas|matplotlib
2
370,438
29,082,001
how to split a dataset into training and validation set keeping ratio between classes?
<p>I have a multi class classification problem and my dataset is skewed, I have 100 instances of a particular class and say 10 of some different class, so I want to split my dataset keeping ratio between classes, if I have 100 instances of a particular class and I want 30% of records to go in the training set I want to...
<p>You can use sklearn's <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html?highlight=stratified%20k%20fold#sklearn.model_selection.StratifiedKFold" rel="noreferrer"><code>StratifiedKFold</code></a>, from the online docs:</p> <blockquote> <p>Stratified K-Folds cro...
python|numpy|pandas|machine-learning|scikit-learn
19
370,439
28,901,486
Access to pandas dataframe object between requests via session key
<p>I have a pandas dataframe with a loose wrapper class around it that provides metadata for my django/DRF application. The application is basically a user friendly (non programmer) way to do some data analysis and validation. Between requests I want to be able to save the state of the dataframe so I can have a series ...
<p>If you are running your application on a modern server then 100mb is not a huge amount of memory. However if you have more than a couple dozen simultaneous users, each requiring 100mb of cache then this could add up to more memory than your server can handle. Your cache and server should be configured appropriatel...
django|pandas|memcached|django-rest-framework|web-architecture
2
370,440
28,947,323
How to change values in an area of an array?
<pre><code>A = np.array([[1,2,3],[4,1,3],[6,7,1]]) array([[1, 2, 3], [4, 1, 3], [6, 7, 1]]) </code></pre> <p>I need to transform every 1 to a 23 but only on a subset of the array. I want to start at the index 1:1 and stop at 2:2</p> <pre><code>array([[1, 2, 3], [4, 23, 3], [6, 7, 23]]) <...
<pre><code>&gt;&gt;&gt;A = np.array([[1,2,3],[4,1,3],[6,7,1]]) array([[1, 2, 3], [4, 1, 3], [6, 7, 1]]) &gt;&gt;&gt;b = A[1:,1:]==1 &gt;&gt;&gt;A[1:,1:][b]=23 &gt;&gt;&gt;A array([[ 1, 2, 3], [ 4, 23, 3], [ 6, 7, 23]]) </code></pre>
python|numpy
3
370,441
29,253,384
How to read this JSON into dataframe with specfic dataframe format
<p>This is my JSON string, I want to make it read into dataframe in the following tabular format.</p> <p>I have no idea what should I do after <code>pd.Dataframe(json.loads(data))</code></p> <p><img src="https://i.imgur.com/90khJQQ.png" alt=""></p> <h1>JSON data, edited</h1> <pre><code>{ "data":[ ...
<p>That's a somewhat overly nested JSON. But if that's what you have to work with, and assuming your parsed JSON is in <code>jdata</code>:</p> <pre class="lang-py prettyprint-override"><code>datapts = jdata['data'] rownames = ['actual', 'upper_end_of_central_tendency'] colnames = [ item['title'] for item in datapts ] ...
python|pandas
1
370,442
29,102,632
how to find numeric values for distinct words in text file using python
<p>I have a text file and i want to find numeric values corresponding to all the distinct words present in that file.By numeric value, I mean that I want to assign a unique integer value( not the times of occurrence value ) to it so that I can use that numeric data in weka for text analysis.</p> <p>Can anyone suggest ...
<p>First you need tokenize your corpus, then simply count the instances:</p> <pre><code>from collections import Counter from nltk import word_tokenize with open('yourfile.txt', 'r') as fin: dictionary = Counter(word_tokenize(fin.read()) for word, count in dictionary.most_common(): print word, count </code></pre...
python-3.x|numpy|nltk
0
370,443
28,898,858
Python apply_along_axis of multiple arrays
<p>If I have a function, f(x) which takes a single 1d-array as argument and produces a 1d-array as output, I can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html#numpy.apply_along_axis">numpy.apply_along_axis</a> to apply the function, to each row of a 2d-array X whose rows a...
<p>Looking at the code for <code>numpy.apply_along_axis</code> I see that it just iterates over the other dimensions, applying your function to each 'row'. There's extra code that allows for dimensions about 2. But for 2d <code>X</code> it boils down to:</p> <pre><code>result = np.empty_like(X) for i, x in enumerate...
python|numpy
12
370,444
28,922,481
Python Pandas GroupBy().Sum() Having Clause
<p>So I have this DataFrame with 3 columns 'Order ID, 'Order Qty' and 'Fill Qty'</p> <p>I want to sum the Fill Qty per order then compare it to Order Qty, Ideally I will return only a dataframe that gives me Order ID whenever aggregate Fill Qty is greater than Order Qty.</p> <p>In SQL I think what I'm looking for is ...
<p>View original dataframe:</p> <pre><code>In [57]: print original_df Order Id Fill Qty Order Qty 0 1 419 334 1 2 392 152 2 3 167 469 3 4 470 359 4 5 447 441 5 6 154 190 6 ...
python|pandas|aggregate|dataframe
2
370,445
29,049,985
Pandas Time-Series: Find previous value for each ID based on year and semester
<p>I realize this is a fairly basic question, but I couldn't find what I'm looking for through searching (partly because I'm not sure how to summarize what I want). In any case:</p> <p>I have a dataframe that has the following columns:<br> * ID (each one represents a specific college course)<br> * Year<br> * Term (0 =...
<p>I think there are two critical points: (1) sorting by Year and Term so that the order corresponds to temporal order; and (2) using <code>groupby</code> to collect on IDs before selecting and shifting the Rating. So, from a frame like</p> <pre><code>&gt;&gt;&gt; df ID Year Term Rating 0 1 2010 0 ...
python|pandas|time-series
6
370,446
33,663,980
How to run tensor flow seq2seq demo
<p>I tensor flow installed and successfully went through the MNIST demo. Now, I am trying to run the <a href="http://www.tensorflow.org/tutorials/seq2seq/index.md#" rel="nofollow noreferrer">seq2seq demo</a>, but this is not working for me. </p> <p>I cloned a version of their github repo and attempted to run some of t...
<p>There are two ways to run the script:</p> <p>1) separate the script arguments with -- as part of bazel run</p> <pre><code>bazel run -c opt //tensorflow/models/rnn/translate:translate -- \ --data_dir ./data_dir --train_dir ./checkpoints_directory \ --en_vocab_size=40000 --fr_vocab_size=40000 </code></pre> <p>2) bu...
tensorflow
4
370,447
33,833,832
Building multi-regression model throws error: `Pandas data cast to numpy dtype of object. Check input data with np.asarray(data).`
<p>I have pandas dataframe with some categorical predictors (i.e. variables) as 0 &amp; 1, and some numeric variables. When I fit that to a stasmodel like:</p> <pre><code>est = sm.OLS(y, X).fit() </code></pre> <p>It throws:</p> <pre><code>Pandas data cast to numpy dtype of object. Check input data with np.asarray(da...
<p>If X is your dataframe, try using the <code>.astype</code> method to convert to float when running the model:</p> <pre><code>est = sm.OLS(y, X.astype(float)).fit() </code></pre>
python|numpy|pandas|statsmodels
51
370,448
33,810,485
Reading in repeated blocks of data using pandas and python
<p>I have a file with the following data:</p> <pre><code> 2008 1 1 ATMOS CO2 = 382. ppm SOIL LAYER NO 1 1 2 3 4 TOT DEPTH(m) 0.01 0.10 0.33 0.64 ...
<p>You have to process file line by line and then use <a href="https://docs.python.org/2/library/stringio.html" rel="nofollow">StringIO</a> as input of function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">read_csv</a>.</p> <pre><code>import pandas as pd import nu...
python|pandas
3
370,449
33,850,831
Years to Decades
<p>I have a df called 'va' with a column 'contest_id' that contains a year value. For example, a record in the years column would say 73hod34 with the year being 1973. I would like to make a column that takes the first character so I can code my data in terms of decades rather than years. </p> <p>Additionally I have a...
<p>Since you have the year's column, I don't think there is a need to subset the string of contest_id, but here are two solutions to create a decade's column.<br> Since you need to represent the year with some int value, you could convert it to a category(factor) instead: This will yield the column with entire year na...
python|pandas|ipython
1
370,450
33,588,838
Python ScikitLearn GridSearchCV issues with TFIDF - JobLibValueError?
<p>so I have a corpus of words I'm running TFIDF on and then trying to classify using Logistic Regression and GridSearch.</p> <p>But I'm getting a huge error when I run the GridSearch.. the error is this (it's longer, but I just copy and pasted a little bit):</p> <pre><code>An unexpected error occurred while tokenizi...
<p>I stumbled upon similar problem. First set n_jobs to 1 then run the code, as a result you will get true error message, fix the error and go back with n_jobs = -1</p>
python|numpy|scikit-learn|tf-idf|grid-search
2
370,451
33,771,195
Putting a Linear regression solution together
<p><a href="https://gist.github.com/marcelcaraciolo/1321585" rel="nofollow">https://gist.github.com/marcelcaraciolo/1321585</a></p> <p>From this code, I am attempting to find the theta coefficients to a data set that I currently possess in a numpy array. I have saved the training array to a csv called 'foo.csv'. I tr...
<p>You should consider designing your code using Classes. You could make you file look something like this (partial code taken from your question):</p> <pre><code>from numpy import loadtxt, zeros, ones, array, genfromtxt, linspace, logspace, mean, std, arange from mpl_toolkits.mplot3d import Axes3D import matplotlib.p...
python|arrays|csv|numpy|pandas
0
370,452
33,873,139
Add zeros as prefix to a calculated value based on the number of digits
<p>I have written an expression which will ask for a user input. Based on the user input, it will calculate a value. If the calculated value is say 1, then I want the value to be converted to 0001. Same thing applies when the calculated value is 2 and 3 digits long. </p> <p>If the calculated value is 4 or 5 digits lon...
<p>You may use zfill() string method:</p> <pre><code>str(timestep).zfill(4) </code></pre>
python|numpy
1
370,453
23,818,450
Cumulative sum within a group
<p>Say I have the following multi-index dataframe:</p> <pre><code> A H1 one 1 two 0 three 1 four 2 H2 one 1 two 4 </code></pre> <p>I would like to compute on a new column the rolling <strong>cumulative sum</strong> within the group so that the output is:...
<p>I think all you need to do is use the <code>level</code> argument with <code>groupby</code> (as described in the <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#groupby-with-multiindex" rel="noreferrer">groupby with multiindex</a> part of the tutorial):</p> <pre><code>&gt;&gt;&gt; df["sum"] = df.g...
python|pandas
5
370,454
23,557,592
Pandas Panel : How To Iterate Over the Minor Axis?
<p>What is the preferred way to iterate over all the items (which are dataframes) in a Panel's Minor Axis?</p> <p>At the moment I am using</p> <pre><code>pnl = pd.Panel( ... ) for key, df in pnl.transpose(2,1,0).iteritems(): print( key ) </code></pre> <p>but it looks ugly and unpythonic.</p>
<pre><code>In [27]: for key in pnl.minor_axis : ....: print key ....: print pnl.minor_xs (key) </code></pre>
python|python-3.x|pandas
4
370,455
23,808,327
Unexpected Exception in numpy.isfinite()
<p>I get this exception for a reason I do not understand. It is quite complicated, where my np.array v comes from, but here is the code when the exception occurs:</p> <pre><code>print v, type(v) for val in v: print val, type(val) print "use isfinte() with astype(float64): " np.isfinite(v.astype("float64")) prin...
<p><code>H_estim.values</code> is a numpy array with the data type <code>object</code> (take a look at <code>H_estim.values.dtype</code>):</p> <pre><code>In [62]: H_estim.values Out[62]: array([[3.4000000000000004, 3.6000000000000005, 2.7999999999999998, 3.0], [3.9000000000000004, 4.3000000000000007, 2.6999999...
python|numpy
13
370,456
23,838,241
Cython says buffer types only allowed as function local variables even for ndarray.copy()
<p>I am new to Cython and encountered this code snippet:</p> <pre><code>import numpy as np cimport numpy as np testarray = np.arange(5) cdef np.ndarray[np.int_t, ndim=1] testarray1 = testarray.copy() cdef np.ndarray[np.float_t, ndim=1] testarray2 = testarray.astype(np.float) </code></pre> <p>During compilation, it s...
<p>When you define an array in cython using <code>np.ndarray[Type, dim]</code>, that is accessing the python buffer interface, and those can't be set as module level variables. This is a separate issue from views vs copies of numpy array data. </p> <p>Typically if I want to have an array as a module level variable (i....
python|numpy|cython
16
370,457
23,569,485
Why NumPy arrays over standard library arrays?
<p>If I only need 1D arrays, what are the performance and size-in-memory benefits of using NumPy arrays over Python standard library arrays? Or are there any?</p> <p>Let's say I have arrays of at least thousands of elements, and I want: fast direct access-by-index times and I want the smallest memory footprint possib...
<p><code>numpy</code> is great for its fancy indexing, broadcasting, masking, flexible view on data in memory, many of its numerical methods and more. If you just want a container to hold data, then use an <code>array.array</code> or why not even a simple <code>list</code>?</p> <p>I suggest taking a look at the <a hre...
python|arrays|python-2.7|numpy
4
370,458
23,513,050
Flatten and create new columns in Pandas
<p>I have the following table:</p> <pre><code>UserID Course 1 ENGLISH 1 MATH 2 ENGLISH 2 PHILOSOPHY 3 MATH </code></pre> <p>I would like to have the following table:</p> <pre><code>UserID Course1 Course2 Course3 1 ENGLISH MATH 2 ENGLISH PHILOSOPHY 3 MATH </code></p...
<p>You can add a column containing the 'Course number' (per user) and then pivot it.</p> <pre><code>df['CourseNr'] = df.groupby('UserID').cumcount().apply(lambda x: 'Course%i' % (x+1)) </code></pre> <p>Gives:</p> <pre><code> UserID Course CourseNr 0 1 ENGLISH Course1 1 1 MATH Course2...
python|pandas
3
370,459
23,490,626
How to avoid axis values with 1e7 in pandas and matplotlib
<p>Using the code below it produce a plot where y-axis is 0.0 to 2.5 1e7. How is it possible to avoid values with 1e7?</p> <pre><code> import pandas as pd import matplotlib.pyplot as plt a = {'Test1': {1: 21867186, 4: 20145576, 10: 18018537}, 'Test2': {1: 23256313, 4: 21668216, 10: 19795367}} ...
<p>Use <code>ticklabel_format(style = 'plain')</code> as in the following example.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt a = {'Test1': {1: 21867186, 4: 20145576, 10: 18018537}, 'Test2': {1: 23256313, 4: 21668216, 10: 19795367}} d = pd.DataFrame(a).T #print d f = plt.figure() plt.ti...
python|matplotlib|pandas
11
370,460
23,829,097
python/numpy fastest method for 2d kernel rank filtering on masked arrays (and/or selective ranking)
<p>Given a 2D numpy array</p> <pre><code>MyArray = np.array([[ 8.02, 9.54, 0.82, 7.56, 2.26, 9.47], [ 2.68, 7.3 , 2.74, 3.03, 2.25, 8.84], [ 2.21, 3.62, 0.55, 2.94, 5.77, 0.21], [ 5.78, 5.72, 8.85, 0.24, 5.37, 9.9 ], [ 9.1 , 7.21, 4.14, 9.95, 6.73, 6...
<p>One way is to sacrifice RAM usage to forego the Python loops. I.e. we blow up the original array so that we can apply the filter on all sub-arrays at once. Which is kind of similar to <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">Numpy broadcasting.</a></p> <p>For an array o...
python|numpy|scipy|median
3
370,461
23,879,851
Pandas GroupBy object is not 'serializable' by Plot.ly
<p>I'm trying to create a boxplot using Plotly and I get an error when attempting to use a Pandas DataFrame that's been grouped. Some initial digging produced this chunk of code to convert Pandas to Plotly interface:</p> <pre><code>def df_to_iplot(df): ''' Coverting a Pandas Data Frame to Plotly interface ''' x = df....
<p>If I understand right, you want something like this:</p> <pre><code>data = Data([Box(y=v.values) for k, v in g]) </code></pre> <p>(where <code>g</code> is your grouped object). Then you can use <code>py.plot</code> on that.</p> <p>Like I said in the comments, I know nothing about plotly; I'm just going based off...
python|pandas|plotly
1
370,462
22,668,100
Multiplying specific dimension matrices
<p>Say I have matrices A and B.</p> <p>A is a three dimensional array/tensor(?).</p> <pre><code>[1,2,3,4] [5,6,7,8] [1,2,3,4] [5,6,7,8] </code></pre> <p>There are say 4 DIFFERENT 2d matrices like the one above across the third dimension.</p> <p>B is a matrix.</p> <pre><code>[1,2,3,4] </code></pre> <p>There are al...
<p>You may want to look into <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>. As an example:</p> <pre><code>&gt;&gt;&gt; mat = np.arange(80).reshape(4, 4, 5) &gt;&gt;&gt; vec = np.arange(12).reshape(3, 4) &gt;&gt;&gt; np.einsum('ij,jkl,ik-&gt;il...
python|numpy|matrix
2
370,463
22,764,580
Is it possible to change the type of just one column in a numpy array created from genfromtxt?
<p>I'm creating a numpy array which then will be exported into a django model. As dtype attribute I have a None, but I have one column which should be an integer which admits NULL values. Now, when in the csv a 'NULL' string is found, the type of that column is changed in bool, which doesn't admit a None.</p> <p>Now, ...
<p>Assuming you are talking about genfromtxt, you can set the dtype using the dtype parameter:</p> <p>e.g.</p> <p>If your file contains</p> <pre><code>1.0 2.0 3.0 4.0 1.0 2.0 3.0 4.0 1.0 2.0 3.0 4.0 1.0 2.0 3.0 hello </code></pre> <p>Then </p> <pre><code>a=np.genfromtxt('vlen.txt',dtype=[('col0', 'i4'), ('col1', '...
python|django|numpy|types|genfromtxt
0
370,464
22,701,870
Replacing a column with another predefined column
<p>Currently I have a very simple question. I'm using Python 2.7 and have the following.</p> <pre><code>from pylab import * import numpy as np Nbod = 55800 Nsteps = 7 r = zeros(shape=(Nbod, Nsteps)) r_i = np.random.uniform(60.4,275,Nbod) r[1:Nbod][0] = r_i </code></pre> <p>I'm trying to replace the first column <c...
<p>I think you want this:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; Nbod = 55800 &gt;&gt;&gt; Nsteps = 7 &gt;&gt;&gt; r = np.zeros(shape=(Nbod, Nsteps)) &gt;&gt;&gt; r_i = np.random.uniform(60.4,275,Nbod)^C #Notice that we slice the 2nd column and replace it with r_i &gt;&gt;&gt; r[:,1] = r_i #Exam...
python|arrays|numpy
1
370,465
22,860,988
Concatenating within a groupby in pandas
<p>Let's say I have the following data of user stays at a hotel:</p> <pre><code> end start uid 0 2014-01-02 00:00:00 2014-01-01 00:00:00 1 1 2014-01-04 00:00:00 2014-01-02 00:00:00 1 2 2014-02-02 00:00:00 2014-02-01 00:00:00 1 3 2014-01-02 00:00:00 2014-01-01 00:00:00 3 </co...
<p>So, this is how I solved this, without using any vectorization or special panda features. Also, this assumes the data is sorted on start,end.</p> <pre><code>data["discard"] = False grouped = data.groupby("uid") uids = data.uid.unique() maxdiff = 24 * 60 * 60 parts = [] for uid in uids: group = grouped.get_grou...
python|pandas|group-by
0
370,466
22,590,066
Pandas panelnd vs dataframe with hierarchical index
<p>I was wondering when and why I should prefer a panel(nd) over a dataframe with hierarchical index, and vice versa. In my very brief experience, I would say that the former is more convenient for slicing, while the latter for mathematical operations. My particular need would be to interactively manipulate 3-5 dimensi...
<p>Generally stick with a multi-indexed frame as they are more fully supported.</p> <p>A <code>panelnd</code> is like a generalized n-dim Panel, good mainly for single-dtyped data. It does work like a Panel, but has some quirks and missing features (its why its experimental). </p> <p>Their <em>are</em> ways to apply ...
pandas
1
370,467
22,737,092
numpy loadtext and savetxt multiple files?
<p>I hope to read, calculate, and print out multiple files of same format. </p> <pre><code>filenames2 = ["AAA", "BBB", "CCC", "DDD", "EEE"] for filename2 in filenames2: with loadtxt (filename2, float) as data: a1 = data[:,0] b1 = data[:,3] c1 = data[:,4] d1 = data[:,5] e1 = data[:,6] ...
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html" rel="nofollow">numpy.loadtxt</a> takes a filename(string) and returns a numpy array. So you don't need the <code>with</code> clause:</p> <pre><code>filenames2 = ["AAA", "BBB", "CCC", "DDD", "EEE"] for filename2 in filenames2: data ...
python|numpy
2
370,468
22,638,557
using numpy percentile on binned data
<p>Suppose house sale figures are presented for a town in ranges:</p> <pre><code>&lt; $100,000 204 $100,000 - $199,999 1651 $200,000 - $299,999 2405 $300,000 - $399,999 1972 $400,000 - $500,000 872 &gt; $500,000 1455 </code></pre> <p>I want to know which house-price bin a given p...
<p>You were almost there:</p> <pre><code>cs = np.cumsum(a) bin_idx = np.searchsorted(cs, np.percentile(cs, 75)) </code></pre> <p>At least for this case (and a couple others with larger <code>a</code> arrays), it's not any faster, though:</p> <pre><code>In [9]: %%timeit ...: b = np.cumsum(a)/np.sum(a) * 100 ......
python|numpy
2
370,469
22,873,622
Input format for AffinityPropagation clustering
<p>I was using <code>scipy.cluster.hierarchy.linkage</code> method using a precomputed affinity matrix:</p> <p>Here is the code generating that upper triangular matrix:</p> <pre><code>distances = np.zeros((len(reprs), len(reprs))) * -1 for i, j in it.combinations(range(len(reprs)), 2): distances[i][j] = (reprs[i]...
<p>You need to pass a square, symmetric matrix. <code>array [n_samples, n_samples]</code> should be read <code>array of shape (n_samples, n_samples)</code>. I'll fix the docs in a minute.</p>
python|numpy|scipy|scikit-learn
3
370,470
22,545,191
Pandas row manipulation
<p>I'm trying to replace a row in a dataframe with the row of another dataframe only if they share a common column. Here is the first dataframe:</p> <pre><code>index no foo 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 </code></pre> <p>and the second dataframe:</p> <pre...
<p>This should work as well</p> <pre><code>df1['foo'] = pd.merge(df1, df2, on='no', how='left').apply(lambda r: r['foo_y'] if r['foo_y'] == r['foo_y'] else r['foo_x'], axis=1) </code></pre>
python|pandas
2
370,471
22,888,721
Python: appending array index to list (.append)
<p>Thanks ahead of time for the help. I am having trouble with appending an array index to a list. I Have an array counterStack which contains the starting point (1366, 1264) I run a neighborhood search on that starting point and for every new index that satisfies the conditions set the index should be appended to the ...
<p>You're setting <code>counterStack = [(1366, 1264)]</code> in each iteration of the <code>for</code> loop but stack is only set to the base index once.</p> <p>Move <code>counterStack = [(1366, 1264)]</code> to right below the line <code>stack = [(1366, 1264)]</code> and you should see what you want.</p> <p>Also as ...
python|arrays|numpy
1
370,472
22,929,297
Numpy, masking and sklearn clustering
<p>I am having an issue with modifying 3D to 2D in order to supply it to Bandwidth function for mean shift calculation. Originally I query the DB for the data in 1D array of values and set of IDś that belong to these values - this will help me later to identify the sources. Prior to calculation I add one more dimensio...
<p>You could first convert to a numpy array:</p> <pre><code>h=[(2.819999933242798, 0.0, 16383), (3.75, 0.0, 16384) , (3.75, 0.0, 16385)] a=np.array(h) </code></pre> <p>and then get the columns you want:</p> <pre><code>a[:,0:2] </code></pre> <p>gives:</p> <pre><code>array([[ 2.81999993, 0. ], [ 3.75 ...
python|arrays|numpy|matrix
1
370,473
22,852,479
Beginner Matplotlib, how to make random data for graph
<p>I'm playing around with matplotlib trying to learn its features but one problem I am struggling with is making it randomly produce data to test my graph. Can anyone tell me what I am doing incorrectly here?</p> <pre><code>import numpy as np labels = numpy.random.random_integers(0, high=1, size=10000) x = numpy.ran...
<p>If you want to generate samples from meaningful distributions, many are supplied, for example:</p> <pre><code>x = np.random.exponential(2, 10000) </code></pre> <p>Many more are in <code>scipy.stats</code>:</p> <pre><code>from scipy import stats stats.gausshyper.rvs(a, b, c, z, size=10000) </code></pre> <p>To do ...
python|python-2.7|random|numpy|matplotlib
2
370,474
22,459,870
Vectorizing a nested for-loop in python for index-dependent function
<p>I'm currently porting a C++ program to Python using Numpy arrays. I'm looking for a way to implement, if possible, the following loops in a more Pythonic way:</p> <pre><code>for (int j = start_y; j &lt; end_y; j++) { for (int i = start_x; i &lt; end_x; i++) { plasmaFreq[i][j] = plas...
<p>You'll need an array <code>i</code>,</p> <pre><code>i = np.arange(start_x, end_x) plasmaFreq[start_x:end_x, start_y: end_y] = plasmaFreq_0 *(np.tanh((i - 50)/10) - np.tanh((i - (nx - 50))/10))/2.0 </code></pre> <p>I think that broadcasting should take it from there.</p> <hr> <p>Note that your original code is qu...
python|c++|arrays|numpy
3
370,475
22,742,951
Solve an equation using a python numerical solver in numpy
<p>I have an equation, as follows:</p> <p><code>R - ((1.0 - np.exp(-tau))/(1.0 - np.exp(-a*tau))) = 0</code>.</p> <p>I want to solve for <code>tau</code> in this equation using a numerical solver available within numpy. What is the best way to go about this? </p> <p>The values for <code>R</code> and <code>a</code> i...
<p>In conventional mathematical notation, your equation is</p> <p><img src="https://i.stack.imgur.com/KcFPu.png" alt="$$ R = \frac{1 - e^{-\tau}}{1 - e^{-a\cdot\tau}}$$"></p> <p>The SciPy <code>fsolve</code> function searches for a point at which a given expression equals zero (a "zero" or "root" of the expression). ...
python-2.7|numpy|equation|solver
52
370,476
22,715,746
Plot 3d cartesian grid with python
<p>I have just started to learn python and I encounter a problem while trying to produce a figure.</p> <p>I have a large set of points (~ 42000) with X-Y-Z coordinates and with several variable associated (temperature, water content ...) I would like to plot all this stuff in one graph but it appears to be impossible ...
<p>This is complicated data to view, so I think you'll need a tool designed to make viewing of 3D data easy, and <a href="http://docs.enthought.com/mayavi/mayavi/" rel="noreferrer">MayaVi</a> is an excellent option for this.</p> <p>Here's an example,</p> <p><img src="https://i.stack.imgur.com/YjzK0.png" alt="enter im...
python|numpy
9
370,477
15,053,346
SciPy interp2d(linear) results are different than MatLab interp2(linear)
<p>I'm converting a MatLab program to Python, and I'm having problems understanding why scipy.interpolate.interp2d(linear) is giving different results than MatLab interp2(linear). i know scipy.interpolate.rectbivariatespline is giving same result than matlab interp2(cubic).but in linear method is giving diffrent result...
<p>I don't have an answer to this (sorry, not enough reputation to post a comment) but, when I run your Python code I get the following warning:<br/></p> <pre><code>Warning: No more knots can be added because the number of B-spline coefficients already exceeds the number of data points m. Probably causes: eith...
python|numpy|scipy|linear-interpolation
1
370,478
13,736,988
how can I get a clear x-axis in pandas
<p>I try to read-in a file by pandas like this:</p> <pre><code>df=read_csv('C:\Python27\mm.txt',skiprows=7,index_col=[0,1],names=['Date','Time','temp']) </code></pre> <p>then I can get below DataFrame:</p> <pre><code>Date Time celsius 2012-04-12 16:13:09 20.6 2012-04-13 00:13:09 20.6 ... .... </code...
<p>method:</p> <pre><code>def parse(datet): dt=datetime.strptime(datet[0:10],'%Y-%m-%d') delta=timedelta(hours=int(datet[11:13]),minutes=int(datet[14:17])) return dt+delta df=read_csv('c:/py/mimi',skiprows=7,parse_date={'datet':[0,1]},index_col='datet',date_parser=parse) </code></pre>
python|pandas
0
370,479
13,260,907
Iterate over files in a folder to create numpy array
<p>this is my first posting and I am really new to programming - I have a folder with some files that I want to process and then create a numpy array with the values I need I do:</p> <pre><code>listing = os.listdir(datapath) my_array=np.zeros(shape=(0,5)) for infile in listing: dataset = open(infile).readlines()[...
<p>Here is what you need to do to read all files in a numpy array from a specific folder. I have a folder <code>test</code> containing only <code>.txt</code> files. My following <code>file.py</code> is in the same <code>test</code> folder along with all <code>.txt</code> files. Each <code>.txt</code> file contains a 4x...
arrays|file|text|numpy
2
370,480
13,567,089
Scale the real part of complex numpy array
<p>I have a vector of complex numbers (the result of a FFT) and I would like to scale only the real part of the complex numbers by factors in another vector.</p> <h3>Example</h3> <pre><code>cplxarr= np.array([1+2j, 3+1j, 7-2j]) factarr= np.array([.5, .6, .2]) # desired result of cplxarr * factarr : # np.array([.5+2j 1....
<p>This'll do it:</p> <pre><code>&gt;&gt;&gt; factarr*cplxarr.real + (1j)*cplxarr.imag array([ 0.5+2.j, 1.8+1.j, 1.4-2.j]) </code></pre> <p>Not sure if it's the best way though.</p> <hr> <p>It turns out that for me at least (OS-X 10.5.8, python 2.7.3, numpy 1.6.2) This version is about twice as fast as the other ...
python|numpy|complex-numbers
8
370,481
13,630,295
how to (simply) build a integer and float mixed numpy array
<p>I would simply like to create a numpy array of size(N,m) that has just the first column made of integer, and the rest by default float. So that, if initialized to zero it should be results:</p> <pre><code>array([[ 0, 0., 0., 0., 0.], [ 0, 0., 0., 0., 0.], [ 0, 0., 0., 0., 0.], [ 0,...
<p>You could use an array with <code>dtype = object</code>:</p> <pre><code>&gt;&gt;&gt; arr = np.ndarray((10,4),dtype = object) &gt;&gt;&gt; arr[:,0] = int(10) &gt;&gt;&gt; arr[:,1:] = float(10) &gt;&gt;&gt; arr array([[10, 10.0, 10.0, 10.0], [10, 10.0, 10.0, 10.0], [10, 10.0, 10.0, 10.0], [10, 10...
python|multidimensional-array|numpy
18
370,482
29,708,840
Rotate meshgrid with numpy
<p>I am wanting to produce a meshgrid whose coordinates have been rotated. I have to do the rotation in a double loop and I'm sure there is a better way to vectorize it. The code goes as so:</p> <pre><code># Define the range for x and y in the unrotated matrix xspan = linspace(-2*pi, 2*pi, 101) yspan = linspace(-2*p...
<p>Maybe I misunderstand the question, but I usually just...</p> <pre><code>import numpy as np pi = np.pi x = np.linspace(-2.*pi, 2.*pi, 1001) y = x.copy() X, Y = np.meshgrid(x, y) Xr = np.cos(rot)*X + np.sin(rot)*Y # "cloclwise" Yr = -np.sin(rot)*X + np.cos(rot)*Y z = np.sin(Xr) + np.cos(Yr) </code></pre> ...
python|numpy|rotation|vectorization
5
370,483
29,550,686
Numpy: use dtype from genfromtxt() when exporting with savetxt()
<p><code>numpy.genfromtxt(infile, dtype=None)</code> does a pretty good job of determining the number formats in each column of my input files. How can we use those same already determined types when saving the data file with <code>numpy.savetxt()</code>? Savetxt uses a very different format syntax.</p> <pre><code>ind...
<p><code>fmt</code> is supposed to a format string, or list of strings. See the examples in <code>savetxt</code> documentation. It is not a <code>dtype</code>.</p> <pre><code>np.savetxt('test.csv',data, fmt='%10s') </code></pre> <p>gets 90% of the way there:</p> <pre><code> 1000 254092.5 1630087.5 9144.0 ...
python|numpy
1
370,484
29,645,332
pandas groupby by different key and merge
<p>I have a transaction data main containing three variables: user_id/item_id/type, one user_id have more than one item_id and type_id ,the type_id is in (1,2,3,4)</p> <pre><code>data=DataFrame({'user_id':['a','a','a','b','b','c'],'item_id':['1','3','3','2','4','1'],'type_id':['1','2','2','3','4','4']}) ui=data.groupb...
<p>Your question is difficult to answer but here is one solution:</p> <pre><code>import pandas as pd data= pd.DataFrame({'user_id':['a','a','a','b','b','c'],'item_id':['1','3','3','2','4','1'],'type_id':['1','2','2','3','4','4']}) ui = data.copy() ui.drop('item_id',axis=1,inplace=True) ui = data.groupby('user_id').t...
pandas
0
370,485
29,516,084
'gcc' failed during pandas build on AWS Elastic Beanstalk
<p>Getting the following error when trying to install Pandas (0.16.0), which is in my requirements.txt file, on AWS Elastic Beanstalk EC2 instance:</p> <pre><code> building 'pandas.msgpack' extension gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param...
<p>For pandas being compiled on Elastic Beanstalk, make sure to have both packages: <code>gcc-c++</code> <em>and</em> <code>python-devel</code></p> <pre><code>packages: yum: gcc-c++: [] python-devel: [] </code></pre>
python|amazon-web-services|pandas|amazon-ec2|amazon-elastic-beanstalk
20
370,486
29,365,367
FFT doesn't return correct amplitude
<p>I am trying to use simple FFT to make Fourier transform of some function, but apparently the <code>numpy</code> and <code>scipy</code> FFT doesn't work so well even for 1024 points.</p> <p>For example, suppose I want to make FFT of <code>sin(50x)+cos(80x)</code>. Then, at <code>k=50</code> point should be purely im...
<p>For ideal, infinite-length signals it would be <code>0-1j</code> and <code>1+0j</code>. However, this is a finite-length, digital signal. Due to windowing and the limitations in representing floating-point numbers on a computer, it is never going to perfectly match the ideal case.</p>
python|numpy|fft
2
370,487
29,515,512
Replace array values from the reference list
<p>I want to replace the values of 'data' array using 'ref' list:</p> <pre><code>import numpy as np data = np.array([[1, 1 , 0 , 0 , 0 , 0 , 1 , 0], [1, 1 , 1 , 1 , 9 , 1 , 1 , 0], [1, 1 , 1 , 1 , 1 , 1 , 1 , 0], [0, 0 , 1 , 1 , 1 , 1 , 1 , 0], [0, 0...
<p>Iterating through a numpy array is very slow, order of magnitude slower than iterating through a Python list.</p> <p>With the following construct you keep it all within numpy, using the <code>numpy.in1d()</code> method (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html">http://docs.scipy....
python|numpy
5
370,488
62,076,280
Creating columns based on individual values in rows pandas
<p>Looking to simplify a huge dataset via pandas which has four columns,</p> <pre><code> Time A B C 27/5/2020 1:30 -90 -12 0 2 3 5 6 27/5/2020 1:35 -90 -11 0 2 3 4 6 7 8 27/5/2020 1:40 -80 -12 2 4 5 6 9 12 15 </code></pre> <p>I want to create a new dataframe which can give me all th...
<p>Let us try <code>get_dummies</code></p> <pre><code>df=df.join(df.C.str.get_dummies(' ').add_prefix('col')) </code></pre>
python|pandas
0
370,489
62,419,766
Paired difference of columns in dataframe to generate dataframe with 1.3 million columns
<p>I have a dataframe with 1600 columns.</p> <p>The dataframe <code>df</code> looks like where the column names are <code>1, 3 , 2</code>:</p> <pre><code>Row Labels 1 3 2 41730Type1 9 6 5 41730Type2 14 12 20 41731Type1 2 15 5 41731Type2 3 20 12 41732Type1 8 10 5 41732Type2 8 18 16 </code>...
<p>We can do <code>combinations</code> for the column , then create the <code>dict</code> and <code>concat</code> it back </p> <pre><code>import itertools l=itertools.combinations(df.columns,2) d={'{0[0]}|{0[1]}'.format(x) : df[x[0]]-df[x[1]] for x in [*l] } newdf=pd.concat(d,axis=1) 1|3 1|2 3|2 RowLabe...
pandas|dataframe|python-3.8
1
370,490
62,198,092
how to get column total without resetting indexes in panda
<p><a href="https://i.stack.imgur.com/MP1eC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MP1eC.png" alt="This is the dataframe "></a> and the way I want to display it is something like this</p> <pre><code> ComoQty DocDate ImportType ForeignType April Export ...
<p>To filter for export/import and compute the sums, assuming the dataframe is called <code>df</code>:</p> <pre><code>difference = df[df.ImportType=='Export'].ComoQty.sum()\ -df[df.ImportType=='Import'].ComoQty.sum() </code></pre> <p>and accordingly with <code>+</code> for the total.</p>
python|python-3.x|pandas|dataframe|pandas-groupby
1
370,491
62,387,401
Getting count of every word in the list by seperating
<p>I have the following list and want to get the count of each word</p> <pre><code>t_series=['Chinese, Italian, Fast Food', 'North Indian, Chinese, South Indian, Fast Food, Biryani, Street Food, Beverages', 'South Indian, North Indian, Chinese, Biryani, Street Food, Sandwich, Beverages', 'Bakery, Fast F...
<p>Use <code>split</code> by <code>,</code>:</p> <pre><code>list_sep = [st for row in t_series for st in row.split(', ')] print (list_sep) ['Chinese', 'Italian', 'Fast Food', 'North Indian', 'Chinese', 'South Indian', 'Fast Food', 'Biryani', 'Street Food', 'Beverages', 'South Indian', 'North Indian', 'Chinese', 'Bi...
python-3.x|pandas|data-science
1
370,492
62,150,775
How to assign data from pandas groupby function to a variable?
<p>I have a question regarding Pandas. I grouped data by column (Districts)<br></p> <pre><code>GroupByDistrict = df.groupby(['District']) </code></pre> <p>and then I want to get data</p> <pre><code>print(GroupByDistrict['Price'].agg(['median','mean'])) </code></pre> <p>Output of this command shows average prices in...
<p>You can do that as:</p> <pre><code>district_prices = df.groupby('District').agg({'Price': [ 'median', 'mean']}).apply(list).to_dict() print(district_prices) </code></pre>
python|pandas|pandas-groupby
1
370,493
62,291,303
PyTorch: Loading word vectors into Field vocabulary vs. Embedding layer
<p>I'm coming from Keras to PyTorch. <strong>I would like to create a PyTorch Embedding layer</strong> (a matrix of size <code>V x D</code>, where <code>V</code> is over vocabulary word indices and <code>D</code> is the embedding vector dimension) with GloVe vectors but am confused by the needed steps.</p> <p>In Keras...
<p>When <code>torchtext</code> builds the vocabulary, it aligns the the token indices with the embedding. If your vocabulary doesn't have the same size and ordering as the pre-trained embeddings, the indices wouldn't be guaranteed to match, therefore you might look up incorrect embeddings. <code>build_vocab()</code> cr...
python|machine-learning|pytorch|word-embedding
8
370,494
62,117,456
pandas: how to get the sum of rows by grouping inside a DataFrame?
<p>I am new to Data Science and I am currently using the Pandas library on the Jupyter notebook. Sorry for my poor English. </p> <pre><code>A,1,5,9 B,2,6,3 A,3,7,2 B,4,8,1 </code></pre> <p>How to group the above CSV values also adding the contents after creating the DataFrame? I want the output something like this.</...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html" rel="nofollow noreferrer"><code>df.pivot_table</code></a></p> <pre><code>df 0 1 2 3 0 A 1 5 9 1 B 2 6 3 2 A 3 7 2 3 B 4 8 1 df.pivot_table(columns=0,aggfunc='sum').rename_axis(columns=None...
python|pandas|pandas-groupby
1
370,495
62,096,595
Using pandas, what is the best way to go through a column in a dataframe while comparing each successive value to the previous value
<p>For example lets say I have the following data set which goes on for 20,000 rows (large data set).</p> <pre><code>time velocity 0.000000 2.36949 0.005217 2.36169 0.010434 2.35677 0.015651 2.35299 0.020869 2.35015 </code></pre> <p>I would want to take the second value in 'velocity' and subtra...
<p>Do the <code>diff</code> then with <code>np.where</code> </p> <pre><code>s=df.velocity.diff() df['new']=np.where(s.abs()&gt;0.005,s/value,s) </code></pre>
python|pandas|dataframe|iteration|data-science
5
370,496
62,401,170
Unable to upload csv dataset correctly on keras DNN
<p>I am using the [Kaggle dataset][1] for mnist sign language. There are 785 columns in total including the one column with the labels for CSV dataset. Also is it a good idea to use CSV for images rather than real images</p> <p>The following code is running fine until mode.fit() gives an error</p> <pre><code>"""CSV_M...
<p>When you use </p> <blockquote> <p>loss='categorical_crossentropy'</p> </blockquote> <p>you have to encode label first(one hot encoding) by use</p> <blockquote> <p>keras.utils.to_categorical(Y)</p> </blockquote> <p>or you can change your loss function to</p> <blockquote> <p>loss='sparse_categorical_crossen...
python|numpy|csv|keras|deep-learning
0
370,497
62,048,428
Problems with converting column from object to float
<p>After scraping the website, I have a column Price.</p> <pre><code>5 € 9.500,00 7 € 2.950,00 8 € 5.750,00 11 € 64.718,00 14 € 4.800,00 ... 3050 € 8.099,00 3051 € 12.500,00 3052 € 16.900,00 3054 € 699,00 3059 € 6.500,00 dtype: object </code></pre> <...
<p>You can try this:</p> <pre><code>df['amount'] = df['amount'].str.replace(r'€|\.', '').str.replace(',', '.') df['amount'] = df['amount'].astype(float) print(df) amount 0 9500.0 1 2950.0 2 5750.0 3 64718.0 4 4800.0 5 8099.0 6 12500.0 7 16900.0 8 699.0 9 6500.0 </code></pre>
python|pandas
1
370,498
62,280,681
PySpark: Concat two dataframes with columns sums
<p>I have two PySpark dataframes which I would like to left join</p> <pre><code>Prev_table: | user_id | earnings | start_date | end_date | |---------|--------|------------|------------| | 1 | 10 | 2020-06-01 | 2020-06-10 | | 2 | 20 | 2020-06-01 | 2020-06-10 | | 3 | 30 | 2020-06-01 | 202...
<p>There can be a better way but one approach is , rename the <code>profit</code> to <code>earnings</code>, then fill missing columns in df2 , then <code>union</code> and groupby with <code>agg</code>:</p> <p>Assuming <code>Prev_table</code> is <code>df1</code> and <code>New_table</code> is <code>df2</code></p> <pre>...
pandas|pyspark
4
370,499
62,291,989
Convert categorical features with and without unique seperators using pd.get_dummies in pandas
<p><strong>Details about the goal</strong></p> <p>I am trying to use pd.get_dummies in pandas to convert the categorical features to data frames with dummy/indicator variables for each of three different genres, demographics, and prices separately. </p> <p><strong>Additional details</strong></p> <p>Two have a separa...
<p>Fix your output with</p> <pre><code>artist1_features = pd.concat([artist1['genre'].str.get_dummies(sep="| "), artist1['demo'].str.get_dummies(sep=","), pd.crosstab(artist1.index, artist1['price']),axis = 1) </code></pre>
python|pandas|dataframe|nlp|data-manipulation
1