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
350,700
63,663,286
Python aggregate sum Quantity
<p>I have a df like this</p> <pre><code>sale_id brand Qty 1 Toyota 1 1 Toyota 2 2 Honda 1 2 Toyota 1 3 Lexus 3 </code></pre> <p>Is there a function to convert it to:</p> <pre><code>sale_id Toyota Honda Lexus 1 3 0 0 2 1 1 0 3 0 0 1 </co...
<p>Try with</p> <pre><code>s = df.groupby(['sale_id','brand']).Qty.sum().unstack(fill_value=0) Out[223]: brand Honda Lexus Toyota sale_id 1 0 0 3 2 1 0 1 3 0 3 0 </code></pre>
python|pandas
3
350,701
63,589,359
Merging two dataframes based on index
<p>I've been on this all night, and just can't figure it out, even though I know it should be simple. So, my sincerest apologies for the following incantation from a sleep-deprived fellow:</p> <p>So, I have four fields, Employee ID, Name, Station and Shift (ID is non-null integer, the rest are strings or null).</p> <p>...
<p>If I understand your question correctly, this is the thing that you want.</p> <p>For example with this 3 dataframes..</p> <pre><code>In [1]: df1 Out[1]: 0 1 2 0 3.588843 3.566220 6.518865 1 7.585399 4.269357 4.781765 2 9.242681 7.228869 5.680521 3 3.600121 3.931781 4.616634 4 9...
python|pandas|dataframe|merge
0
350,702
63,729,692
Check if Numpy Array is Stored in Shared Memory
<p>In Python 3.8+, is it possible to check whether a numpy array is being stored in shared memory?</p> <p>In the following example, a numpy array <code>sharedArr</code> was created using the buffer of a <code>multiprocessing.shared_memory.SharedMemory</code> object. Will like to know if we can write a function that can...
<p>In this particular case, you can use the <code>base</code> attribute of the shared array. The <a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.base.html?highlight=base#numpy.ndarray.base" rel="noreferrer">attribute</a> is a reference to the underlying object from which this array derives its m...
python|python-3.x|numpy|shared-memory|sysv
5
350,703
63,498,322
Pandas DataFrame partial string match based on a list
<p>I have a <code>DataFrame</code> as the following.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame([['One person has died after two motorbikes crashed in the Bay of Plenty.', 'The crash occurred at 3.15pm on Bell Rd in Nukuhou south of Whakatāne police said.', 'Another person suffered minor i...
<p>Try <code>findall</code> or <code>extractall</code>:</p> <pre><code>df.col1.str.findall(f'({&quot;|&quot;.join(loc_list)})', flags=re.IGNORECASE) </code></pre> <hr /> <pre><code>df.col1.str.extractall(f'({&quot;|&quot;.join(loc_list)})', flags=re.IGNORECASE) </code></pre>
python-3.x|pandas|list|dataframe
1
350,704
63,379,135
Pandas repeat rows for entire month when values for first of month present
<p>I have a dataframe as follows:</p> <pre><code>Month Col1 Col2 1/1/2019 2 ca 2/1/2019 10 bg </code></pre> <p>I want to get the following:</p> <pre><code>Month Col1 Col2 1/1/2019 2 ca 1/2/2019 2 ca ......rest days from 1/3 to 1/30 are here 1/31/2019 2 ca 2/1/2019 10 bg ...
<p>try:</p> <pre><code>from pandas.tseries.offsets import MonthEnd df.Month = pd.to_datetime(df.Month) df = df.set_index(['Month'])[['Col1', 'Col2']] def add_index(s): m = s.name index = pd.date_range(m, m + MonthEnd(n=1)) o = s.to_frame().T.reindex(index) return o.ffill() pd.concat([add_index(s) ...
pandas|python-3.8
1
350,705
63,611,825
average aggregation in pandas groupby while considering unique values of a column
<p>I have te following dataframe:</p> <pre><code>df: S0 S1 V1 V2 V3 V4 A B 1 9 1 4 A B 2 8 1 4 A B 3 7 1 4 A B 4 6 1 4 A B 5 5 1 4 A B 6 4 1 4 A C 7 3 2 3 A C 8 2 2 3 A C 9 1 2 3 A C 9 0 2 3 </code></pre> <p>I am do...
<p>I believe you need grouping by <code>S0</code> and <code>S1</code> with aggregate:</p> <pre><code>df1 = (df.groupby(['S0','S1'], as_index=False) .agg({'V1':'sum','V2':'sum','V3':'mean','V4':'mean'})) print (df1) S0 S1 V1 V2 V3 V4 0 A B 21 39 1 4 1 A C 33 6 2 3 </code></pre>
python|pandas|pandas-groupby
7
350,706
63,518,012
Pandas output different rows between two dataframes excluding certain keywords
<p>I'm trying to track the difference between two dfs. However, for certain keywords, I don't want to compare a column. For example, tracking difference between quantity and price, while excluding &quot;apple&quot;</p> <hr /> <p>df1</p> <pre><code> item quantity price 0 apple 3 3 1 pear 2 ...
<p>Solution if possible compare elementwise - it means each values per rows:</p> <pre><code>df = df2[df1.ne(df2).any(axis=1) &amp; df1.item.ne('apple')] print (df) item quantity price 1 pear 2 1 2 orange 1 2 </code></pre>
python-3.x|pandas
0
350,707
63,519,373
How to convert tokenizer output to train_dataset which is required by Trainer API in Huggingface Transformers?
<p>I tried doing tokenisation using documentation of huggingface transformers</p> <pre><code>from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained('bert-base-cased') encoded_input = tokenizer(batch_of_sequences) </code></pre> <p>Pre Trained Tokenizer gives output of dictionary containing thre...
<p>I guess this solves it:</p> <pre class="lang-py prettyprint-override"><code>from datasets import Dataset dataset = Dataset.from_dict(encoded_inputs) </code></pre> <p>If you want to train the model, you might also want to add the labels. For me:</p> <pre class="lang-py prettyprint-override"><code>encoded_inputs[&quot...
python|huggingface-transformers
1
350,708
63,485,453
Saving previous values of a Tensorflow.js tensor
<p>I have an function which stores all of the values of the tensor and then concatonates it into one matrix. The function looks like this:</p> <pre><code> if (i == 1) { var y_pred1 = y_pred } else if (i == 2) { var y_pred2 = y_pred } else if (i == 3) { var y_pred3 = y_pred } else ...
<p>If every tensors return a result, you probably should use an instance of <code>Array</code>.</p> <p>If the number of tensor if static and you know it in advance:</p> <pre><code>var tf = new Array(number_of_tensors); for (var i = 0; i &lt; number_of_tensors; i++) { var y_pred = /** get the result of your tensor ...
javascript|tensorflow|if-statement|optimization|tensor
2
350,709
63,445,839
Runtime error while executing code from google colab document for creating Deepfakes image animation
<p><a href="https://i.stack.imgur.com/W4REs.jpg" rel="nofollow noreferrer">enter image description here</a>I'm getting runtime error while executing code from google colab document for creating Deepfakes image animation.</p> <pre><code>RuntimeError Traceback (most recent call last) </code><...
<p>You may be running on a colab environment that only has TPU's available and not GPU's in which case you need to utilize XLA with PyTorch. You might find this notebook and repository very helpful if this is the case:</p> <p><a href="https://colab.research.google.com/github/pytorch/xla/blob/master/contrib/colab/resnet...
python|pytorch|gpu|google-colaboratory
1
350,710
63,485,620
Using path-strings as index in pandas
<p>I am trying to create a dataframe with filepaths as index:</p> <pre><code>import os import pandas as pd pathnames = [] for i in range(5): pathnames.append(os.path.join('a',str(i))) print(pathnames) df = pd.DataFrame(index = pathnames) df[pathnames[0]] </code></pre> <p>When using this example I get a key-error a...
<p>Use loc or iloc</p> <pre><code>import os import pandas as pd pathnames = [] for i in range(5): pathnames.append(os.path.join('a',str(i))) print(pathnames) df = pd.DataFrame(index = pathnames) print(df.loc['a/0']) </code></pre>
python|pandas|string|raw
0
350,711
63,591,339
Is there any utility function in Tensorflow.js similar to Python/Keras's to_categorical()?
<p>I've recently began working with tensorflow.js. I've reached a point where I need to one hot encode an output. I found nothing searching the tensorflow.js api (<em>tensorflow api has exactly what i'm searching for as a utility but I'm using javascript</em>) regarding to my case and the only help I found from google ...
<p>Based on 4.Pi.n comment -&gt; <a href="https://js.tensorflow.org/api/latest/#oneHot" rel="nofollow noreferrer">one-hot</a> if anybody else doesn't know how to search the docs the right way.</p>
tensorflow.js
0
350,712
63,379,531
Grouping from dictionary values and elimating duplicates from other groups
<p>I have a dictionary:</p> <pre><code>{'a': ['b','c'], 'b':['e','f'], 'c':['g'], 'h':['m','n']} </code></pre> <p>I want my dictionary to group it according to similarity</p> <p>this is how I want the dictionary to look after processing:</p> <pre><code>{'a':['b','c','e','f','g'], 'h':['m','n'] } </code></pre> <p>is th...
<p>Don't know exactly if its the most efficient way to do it (probably isn't) but you can try the following:</p> <pre><code>def merge_entries(input_dict): to_delete = set() for k,v in input_dict.items(): if k not in to_delete: for x in v: if x in input_dict.keys(): ...
python|pandas|dictionary
0
350,713
63,558,184
ParserError: Expected 2 fields in line 32, saw 4
<p>I'm having trouble parsing a txt file (see here: <a href="https://gigamove.rz.rwth-aachen.de/d/id/Sybc7cvqUuY3wG" rel="nofollow noreferrer">File</a>) Here's my code</p> <pre><code>import pandas as pd objectname = r&quot;path&quot; df = pd.read_csv(objectname, engine = 'python', sep='\t', header=None) </code></pre> ...
<p>Your file has tab separators but is not a TSV. The file is a mixture of metadata, followed by a &quot;standard&quot; TSV, followed by more metadata. Therefore, I found tackling the metadata as a separate task from loading the data to be useful.</p> <p>Here's what I did to extract the metadata lines:</p> <pre><code>w...
python|pandas|windows|csv|parse-error
0
350,714
63,560,114
Error: import CSV file to mongoDB with pymongo (pandas)
<p>I have a little code that I want to use to import data. But I just can't specify the attributes for pd.read_csv. Made based on video on Youtube. Absolutely new to this, if you fix the code, I will be very grateful.</p> <p>My error</p> <pre><code> Collection: Confirmed_global_narrow Traceback (most recent call last)...
<p>You are passing incorrect parameters to <code>read_csv()</code>. If you don't specify the parameter names they are passed in the order <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">as per the documentation</a>.</p> <p>You can likely fix you issue ...
python|pandas|pymongo
2
350,715
63,665,874
Unable to read excel with leading zero in pandas
<p>If I read excel it's read as</p> <pre><code> SKU Code Location Code GIT 123456 100 10 123456 200 20 123456 300 0 </code></pre> <p>but actually my excel data is</p> <pre><code> SKU Code Location Code GIT 123456 0100 10 123456 0200 ...
<p>You can try using an f-string:</p> <pre><code>gitDataDF = pd.read_excel(&quot;filename.xlsx&quot;, sheet_name='Sheet1', inferSchema='true' ,converters={'Location Code': lambda x: f'{x:04}'}) </code></pre>
python|python-3.x|excel|pandas|dataframe
1
350,716
63,605,123
How to flatten a layered dataset in Pandas
<p>Say for example there is dataframe A:</p> <pre><code>A col0 col1 col2 'a0' 'a' 'A' 'b0' 'b' 'A' 'c0' 'c' 'A' 'de0' 'd' 'B' 'sas' 'ef' 'B' </code></pre> <p>How can I get to dataframe B?</p> <pre><code>B col1 col2 'a0' 'A' 'a' 'A' 'b0' 'A' 'b' 'A' 'c0' 'A' 'c' 'A' 'de0''B' 'd' 'B' 'sas''B' 'ef' 'B' <...
<p>If you'd like to keep exact names and order of columns from your example try this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'col0': ('a0', 'b0', 'c0', 'de0', 'sas'), 'col1': ('a', 'b', 'c', 'd', 'ef'), 'col2': ('A', 'A', 'A', 'B', 'B')}) sorted_df = sorted_df = df...
python|pandas|flatten
1
350,717
63,382,595
How to separate text data in pandas data frame in a function
<p>The user inputs the following in a function:</p> <pre><code> 250 1/3/2012 16:00:00 Missing_1 1/4/2012 16:00:00 27.47 1/5/2012 16:00:00 27.728 1/6/2012 16:00:00 28.19 1/9/2012 16:00:00 28.1 1/10/2012 16:00:00 28.15 12/13/2012 16:00:00 27.52 12/14/2012 16:00:00 Missing_2 12/17/2012 16:00:00 27.215 ...
<p>You can try this:</p> <pre><code>import pandas as pd fileName = &quot;file.txt&quot; dataFrame = pd.read_csv(fileName, sep=&quot; &quot;, skipinitialspace=True, names=['date','time','value']) df_new = pd.DataFrame() df_new['timestamp'] = dataFrame['date'].str.cat(dataFrame['time'], sep=&quot; &quot;) df_new['value'...
python|pandas|dataframe
1
350,718
63,350,404
will loop decrease the utilization of the GPU?
<p>In PyTorch, I have a loop in my DeepLearning Pipeline's forward part to normalize the intermediate result.</p> <p>Will it run on CPU and decrease the utilization of the GPU?</p> <p>some snippet as follow:</p> <pre><code>def forward(self): ... for b in range(batch_size): self.points[b] = self.unit_cub...
<p>In Pytorch, whether an operation is done on the GPU or CPU is decided by where the data is. One of the main selling points of Pytorch is that you don't (usually) have to care where the data is; the interface is the same.</p> <p>If the tensor data is on the GPU, then the operation is done on the GPU. If it's on the C...
python|tensorflow|pytorch|gpu
2
350,719
63,514,887
Comparing two DataFrames for partial row equality and output equal rows into a new DataFrame?
<p>I have two existing DataFrames which I have named death and air:</p> <pre><code>County,Death Rate Autauga,859 Baldwin,976 County,AQI Baldwin,51 Clay,45 </code></pre> <p>These datasets were taken from different sources and are of different lengths, the same counties do not appear in each DataFrame.</p> <p>When value...
<p>In this case, you can use the merge function from pandas:</p> <pre><code>import pandas as pd death = {'County': ['Autauga', 'Baldwin'], 'Death Rate': [859, 976]} air = {'County': ['Baldwin', 'Clay'], 'AQI': [51, 45]} death = pd.DataFrame(death) air = pd.DataFrame(air) merged = death.merge(air, how='inner', on='Co...
python|pandas|dataframe|csv|for-loop
0
350,720
63,547,650
How to build a Neural Network with sentence embeding concatenated to pre-trained CNN
<p>I want to build a neural network that will take the feature map from the last layer of a CNN (VGG or resnet for example), concatenate an additional vector (for example , 1X768 bert vector) , and re-train the last layer on classification problem. So the architecture should be like in: <a href="https://i.stack.imgur.c...
<p>I would recommend looking into the <strong>Keras functional API</strong>.</p> <p>Unlike a sequential model (which is usually enough for many introductory problems), the <em>functional API</em> allows you to create any acyclic graph you want. This means that you can have <em>two</em> input branches, one for the CNN (...
python|tensorflow|keras|neural-network|lstm
0
350,721
63,350,093
How does the transpose instance "T" work in a numpy array?
<p>I remember once I was writing a class and while defining the <code>__init__</code> method, I attempted to set an instance belonging to the same class, as in this example:</p> <pre><code>class Complex: def __init__(self, real, imag): self.real = real self.imag = imag self.conjugate = Complex(...
<p>Here's the proper way to define your class, which also happens to be how numpy defines the transpose:</p> <pre><code>class Complex: def __init__(self, real, imag): self.real = real self.imag = imag @property def conjugate(self): return Complex(self.real, -self.imag) </code></pre> <...
python|numpy|class|recursion
1
350,722
63,627,624
Filter pandas index by function
<p>I want to filter a pandas dataframe by a function along the index. I can't seem to find a built-in way of performing this action.</p> <p>So essentially, I have a function that through some arbitrarily complicated means determines whether a particular index should be included, I'll call it <code>filter_func</code> fo...
<p>You can use map instead of filter and then do a boolean indexing:</p> <pre><code>df.loc[map(filter_func,df.index)] </code></pre> <hr /> <pre><code> value 0 12 4 6 7 2 8 35 </code></pre>
python|pandas|filter
3
350,723
63,441,299
Pytorch CUDA OutOfMemory Error while training
<p>I'm trying to train a PyTorch FLAIR model in AWS Sagemaker. While doing so getting the following error:</p> <pre><code>RuntimeError: CUDA out of memory. Tried to allocate 84.00 MiB (GPU 0; 11.17 GiB total capacity; 9.29 GiB already allocated; 7.31 MiB free; 10.80 GiB reserved in total by PyTorch) </code></pre> <p>Fo...
<p>This error is because your GPU ran out of memory. You can try a few things</p> <ol> <li><p>Reduce the size of training data</p> </li> <li><p>Reduce the size of your model i.e. Number of hidden layer or maybe depth</p> </li> <li><p>You can also try to reducing the Batch size</p> </li> </ol>
python|pytorch|torch|amazon-sagemaker|torchvision
1
350,724
63,424,959
.csv file containing solutions of polynomial equation
<p>Let's say that I have a quartic equation of the form:</p> <pre><code>a0x^4+a1x^3+a2x^2+a3x+a4=0 </code></pre> <p>I know I can use <code>numpy</code> roots method to solve for a quartic equations, but I want the coefficients to change according to a rule, let's say that they depend on a parameter <code>x</code>, whic...
<p>Basically the idea is to create a new array and export that. I could think of several ways to do this, here's one that I implemented. This method was chosen because it didn't require additional imports, and because it uses <a href="https://stackoverflow.com/questions/6081008/dump-a-numpy-array-into-a-csv-file">an an...
python|numpy
0
350,725
63,690,654
TypeError: Cannot call a class as a function after deploying to Netlify?
<p>Hello I am trying to deploy a web app to Netlify. It uses the COCO SSD model for object recognition in the frontend, which is purposeful. The web app works perfectly fine on localhost but once I deploy to Netlify I get this error:</p> <pre><code>detector.js:47 TypeError: Cannot call a class as a function at r (c...
<p>It looks like <code>webpack</code> has picked the field (the built file) of <code>@tensorflow/tfjs</code> in case of production mode which ends up the problem.</p> <p>But we can specify this field manually which describes here <a href="https://webpack.js.org/configuration/resolve/#resolvemainfields" rel="nofollow no...
javascript|reactjs|tensorflow|netlify
2
350,726
21,589,583
Speed up loop to fill an array with closest values from another array
<p>I have a block of code that I need to optimize as much as possible since I have to run it several thousand times.</p> <p>What it does is it finds the closest float in a sub-list of a given array for a random float and stores the corresponding float (ie: with the same index) stored in another sub-list of that array....
<p>OK, here's a slightly left-field suggestion. As I understand it, you are just trying to sample uniformally from the elements in <code>a[0]</code> until you have a list whose sum exceeds some limit.</p> <p>Although it will be more costly memory-wise, I think you'll probably find it's much faster to generate a large ...
python|arrays|performance|loops|numpy
4
350,727
21,798,829
plot year over year on 12 month axis
<p>I want to plot 6 years of 12 month period data on one 12 month axis from Dec - Jan.</p> <pre><code>import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt df = pd.Series(np.random.randn(72), index=pd.date_range('1/1/2000', periods=72, freq='M')) # display(df.head()) 2000-01-...
<p>There's probably a better way than this:</p> <pre><code>In [44]: vals = df.groupby(lambda x: (x.year, x.month)).sum() In [45]: vals Out[45]: (2000, 1) -0.235044 (2000, 2) -1.196815 (2000, 3) -0.370850 (2000, 4) 0.719915 (2000, 5) -1.228286 (2000, 6) -0.192108 (2000, 7) -0.337032 (2000, 8) ...
python|matplotlib|pandas
4
350,728
21,698,668
pandas: applying multiple filters
<p>I have a dataframe as follows;</p> <pre><code> WORD1 CAT1 WORD2 CAT2 Val 1 Val 2 Val 3 elephant animal daisy flower 191 138 129 lion animal blackbird flower 171 169 213 tiger animal chimp animal 229 179 482 ...
<p>Does this work? It's not particularly elegant but it should do the job. I've caught <code>lion</code> and <code>giraffe</code> in addition to your list but they seem to match the criteria, unless I've misunderstood.</p> <pre><code>myset = ['flower', 'bird'] df[((df.CAT1 == 'animal') &amp; (df.CAT2.isin(myset))) | (...
python|pandas
1
350,729
21,925,114
Is there an implementation of missingmaps in python's ecosystem?
<p>Missingmaps generates a plot of missing values in a dataframe (more details at <a href="http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/Amelia/html/missmap.html" rel="noreferrer">http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/Amelia/html/missmap.html</a>).</p> <p>Is there anything similar in python's ecosystem...
<p>EDIT: As of June 2016 there's a package for this now: <a href="https://github.com/ResidentMario/missingno" rel="nofollow noreferrer">https://github.com/ResidentMario/missingno</a> Original answer follows:</p> <p>This gets pretty close:</p> <pre><code>ax = missmap(df) </code></pre> <p><img src="https://i.stack.img...
matplotlib|pandas
7
350,730
21,821,432
How to efficiently select a submatrix with Python?
<p>I have an adjacency matrix of size nxn (so matrix is symmetric) and I would like to select a submatrix of size mxm and then get its upper triangle. Currently, I am doing this as follows:</p> <pre><code>from numpy import * am = array([array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype...
<p>This works:</p> <pre><code>w = np.array((0, 1, 2, 5, 22)) n = len(w) rang = np.arange(n, 0, -1) rows = np.repeat(w, rang) col_idx = np.arange(n * (n + 1) // 2) delta = np.repeat(np.concatenate(([0], np.cumsum(rang[1:]))), rang) col_idx -= delta cols = np.take(w, col_idx) </code></pre> <p>And now...
python|performance|numpy|matrix|graph
1
350,731
21,483,799
Configuration of Ipython
<p>I'm new to python and Ipython. I'm following the data analysis with pandas on youtube. <a href="http://www.youtube.com/watch?v=w26x-z-BdWQ" rel="nofollow">the link</a></p> <p>I installed Anaconda and then started to use Ipython on Windows 8.1</p> <p>For several commands, it seems OK</p> <pre><code>In [2]: print ...
<ul> <li>use <code>%pylab inline</code> or <code>%pylab</code> to enable <em>pylab</em> mode. This will alter the event loop either to show plots inline (notebook) or to display them in different window without interfering the code execution (CLI). <ul> <li>Executing <code>%pylab</code> will set ipython to handle matp...
python|pandas|ipython|anaconda
1
350,732
21,508,420
Is there a way to set the order in pandas group boxplots?
<p>Is there a way to sort the x-axis for a grouped box plot in pandas? It seems like it is sorted by an ascending order and I would like it to be ordered based on some other column value.</p>
<p>If you're grouping by a category, set it as an ordered categorical in the desired order.</p> <p>See example below: Here a dataset is created with three categories A, B and C where the mean value of each category is of the order C, B, A. The goal is to plot the categories in order of their mean value.</p> <p>The key ...
pandas
4
350,733
21,482,546
change pandas 0.13.0 "print dataframe" to print dataframe like in earlier versions
<p>In the new version 0.13.0 of pandas, a dataframe df is printed in one long list of numbers using</p> <pre><code>df </code></pre> <p>or</p> <pre><code>print df </code></pre> <p>instead of an overview, like before, which is now only possible using</p> <pre><code>df.info() </code></pre> <p>Is it possible to chang...
<p>Set</p> <pre><code>pd.options.display.large_repr = 'info' </code></pre> <p>The default as of v.0.13 is 'truncate'.</p> <pre><code>In [93]: df = pd.DataFrame(np.arange(4319*2).reshape(4319,2)) In [94]: pd.options.display.large_repr = 'info' In [95]: df Out[95]: &lt;class 'pandas.core.frame.DataFrame'&gt; Int64I...
python|pandas|dataframe
3
350,734
21,661,854
Matlab importdata() function equivalent in Python
<p>There's a function called importdata on matlab that import data from ASCII files and put it in a structure with 2 variables: textdata and data. It automatically identify the format of data (string, float.. etc), headlines and delimiter. This function comes in handy for me so im searching if have something equivalent...
<p>Looks like pandas <a href="http://pandas.pydata.org" rel="nofollow">http://pandas.pydata.org</a> might be the way to go, if you want a really seamless import. I've seen pandas handle all sorts of strange missing/malformed data gracefully. That said, you do have slightly more complicated data structures than you'd ot...
python|matlab|numpy|import|ascii
3
350,735
21,902,080
python pandas not reading first column from csv file
<p>I have a simple 2 column csv file called st1.csv:</p> <pre><code>GRID St1 1457 614 1458 657 1459 679 1460 732 1461 754 1462 811 1463 748 </code></pre> <p>However, when I try to read the csv file, the first column is not loaded:</p> <pre><code>a = pandas.DataFrame.from_csv('...
<p>Judging by your data it looks like the delimiter you're using is a <code> </code>.</p> <p>Try the following:</p> <pre><code>a = pandas.DataFrame.from_csv('st1.csv', sep=' ') </code></pre> <p>The other issue is that it's assuming your first column is an index, which we can also disable:</p> <pre><code>a = pandas.Data...
python|csv|pandas
53
350,736
21,634,480
Convert numpy ndarray to non-numpy datatype
<p>I'm trying to convert an element of an <code>np.ndarray</code> to a native integer type.</p> <pre><code>&gt;&gt;&gt; x = np.array([1, 2, 2.5]) &gt;&gt;&gt; type(x[0]) &lt;type 'numpy.float64'&gt; &gt;&gt;&gt; type(x.astype(int)[0]) &lt;type 'numpy.int64'&gt; </code></pre> <p>What I'd like is:</p> <pre><code>&gt;&...
<p>Based on the comments, it might turn out that you don't need this, but to answer the immediate question, you can use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html" rel="nofollow"><code>item</code></a> method. For example:</p> <pre><code>In [78]: x = np.array([1.0, 2.0, 3....
numpy|pandas|networkx
1
350,737
24,741,559
Type of item in pandas DataFrame bug or feature?
<p>If I have a pandas DataFrame</p> <pre><code>df = read_csv("infile.csv") </code></pre> <p>where infile looks something like</p> <pre><code>i1,i2,f1,f2 3,1,0.1,2.0 2,1,0.3,0.5 </code></pre> <p>i.e. two columns of integers and one of floats.</p> <p>If I query this DataFrame with:</p> <pre><code>print type(df["i1"...
<p>As you note yourself, this is indeed expected behaviour because in <code>df.ix[0]["i1"]</code> you first create a Series for the first row (so all items are upcasted to float to get one dtype), and only then you take the item with label <code>"i1"</code></p> <p>The solution is easy: don't use this chained indexing,...
python|pandas
3
350,738
24,465,352
How to refer another row in row_iterator Pandas?
<p>I have the following code</p> <pre><code>row_iterator = temp.iterrows() for i, row in row_iterator: row['InterE'] = row['xs'] - (row['xs'] - row['InterS']) * exp(-row['ak1']) if row['InterE'][:-1] &lt; 1: row['InterS'] = row['InterE'][:-1] else: row['InterS'] = row['InterE'][:-1] - row['...
<p>You should avoid iterating especially when you can vectorise the operation.</p> <p>So</p> <pre><code># calculate 'InterE' column for entire dataframe temp['InterE'] = temp['xs'] - (temp['xs'] - temp['InterS']) * exp(-temp['ak1']) # now for those values less than 1 assign the previous row value, this is what shift ...
python|pandas
1
350,739
24,521,740
how do i 'update' a df based on the values of another dataframe that shares a common key? python
<p>how do i 'update' a12 based on the values of another dataframe that shares a common key? In the example below, the common key is column a. </p> <p>a12 = </p> <pre><code> a b c 0 1 1 1 na na </code></pre> <p>try10 =</p> <pre><code> a b c 1 1 1 </code></pre> <p>when i use a merge, I get something...
<p>There is an <code>combine_first</code> method that you can use. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow">See here.</a> You'll need to set the desired key in both dataframes as index.</p> <pre><code>In [128]: a12.set_index ('a').combine_first(...
python|pandas
1
350,740
24,913,232
Using Numpy (np.linalg.svd) for Singular Value Decomposition
<p>Im reading Abdi &amp; Williams (2010) "Principal Component Analysis", and I'm trying to redo the SVD to attain values for further PCA.</p> <p>The article states that following SVD:</p> <p>X = P D Q^t</p> <p>I load my data in a np.array X.</p> <pre><code>X = np.array(data) P, D, Q = np.linalg.svd(X, full_matrices...
<p>TL;DR: numpy's SVD computes X = PDQ, so the Q is already transposed.</p> <p>SVD decomposes the matrix <code>X</code> effectively into rotations <code>P</code> and <code>Q</code> and the diagonal matrix <code>D</code>. The version of <code>linalg.svd()</code> I have returns forward rotations for <code>P</code> and ...
python|numpy|pca
31
350,741
24,802,121
Locality Sensitive Hashing of sparse numpy arrays
<p>I have a large sparse numpy/scipy matrix where each row corresponds to a point in high-dimensional space. I want make queries of the following kind:</p> <p>Given a point <strong>P</strong> (a row in the matrix) and a distance <strong>epsilon</strong>, find all points with distance at most <strong>epsilon</strong> f...
<p>If you have very large sparse datasets that are too large to be held in memory in a non-sparse format, I'd try out this LSH implementation that is built around the assumption of Scipy's CSR Sparse Matrices:</p> <p><a href="https://github.com/brandonrobertz/SparseLSH" rel="noreferrer">https://github.com/brandonrober...
python|numpy|scipy|locality-sensitive-hash
7
350,742
24,680,221
while statement giving 'float' object has no attribute '__getitem__' error using numpy
<p>I am trying to calculate the Average True Range of a data series which has been read and parsed from a .csv file. my code is as follows:</p> <pre><code>import datetime import time import matplotlib.pyplot as plt import numpy as np fhand = open('C:\Users\Stuart\Desktop\FX Programming\EURUSD_hour.csv', 'r') for l...
<p>In the code that works, high low and close are all arrays so you can index them by date. For example (I used a list instead of an array, but it's similar):</p> <pre><code>hi = [10, 11, 12] print hi[0] # 10 </code></pre> <p>In your code you're looping over your file, converting these values to float and then discar...
python-2.7|numpy
1
350,743
24,761,220
how to create a dataframe by repeating series multiple times?
<p>Is there any function like the following to create a dataframe with ten columns of Series s?</p> <pre><code>df = pd.DataFrame(s, 10) </code></pre> <p>Thank you!</p>
<p>Use concat:</p> <pre><code>In [57]: s = pd.Series(arange(10)) s Out[57]: 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 dtype: int32 In [59]: pd.concat([s] * 10, axis=1) Out[59]: 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 ...
python|pandas
19
350,744
24,759,397
Split a data frame using groupby and merge the subsets into columns
<p>I have a large <code>pandas.DataFrame</code> that looks something like this:</p> <pre class="lang-python prettyprint-override"><code>test = pandas.DataFrame({"score": numpy.random.randn(10)}) test["name"] = ["A"] * 3 + ["B"] * 3 + ["C"] * 4 test.index = range(3) + range(3) + range(4) </code></pre> <pre> <b>id sco...
<p>The function you look for is <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html" rel="nofollow">unstack</a>. In order for <code>pandas</code> to know, what to unstack for, we will first create a <code>MultiIndex</code> where we add the column as <em>last</em> index. <code>unstack()</code> will then ...
python|pandas|merge|group-by|outer-join
2
350,745
24,791,619
Syntax Error on function definition when using emcee
<p>I'm trying to use the emcee module to recreate a distribution. Here is my code:</p> <pre><code>freq,asd = np.loadtxt('noise.csv',delimiter=',',unpack=True) psd = asd**2 SNRth = 4.5 d = 600 dm = 0.9 #interpolate! S = interpolate.interp1d(freq,psd) def SNR2(chirp,f): return 5*np.pi**(-4/3)*chirp**(5/3)/(9...
<p>Missing a closing <code>)</code> on this line:</p> <pre><code>return np.prod(pp(SNR2(chirp,f),seps)+pm(SNR2(chirp,f),seps))*np.prod(mp(SNR2(chirp,f),seps[:Nnoise])+mm(SNR2(chirp,f),seps[:Nnoise])) # &lt;-- missing here </code></pre> <p>Often the syntax error comes from the line before what is shown in the tracebac...
python|numpy|scipy|emcee
0
350,746
24,893,824
levels parameter in greycomatrix scikit-image python
<p>I'm moving my Matlab image processing algorithms to Python using scikit-image tools, and I'm calculating the gray level co-occurrence matrix (<a href="http://www.fp.ucalgary.ca/mhallbey/the_glcm.htm" rel="nofollow noreferrer">GLCM</a>) using <a href="http://scikit-image.org/docs/dev/api/skimage.feature.html?highligh...
<p>Maybe I'm late to the party but hopefully my answer might be useful for someone else in the future...</p> <p>According to <a href="https://es.mathworks.com/help/images/ref/graycomatrix.html" rel="nofollow noreferrer">Matlab documentation</a> <code>'NumLevels'</code> can be less than <code>max(image(:))</code> becau...
python|numpy|image-processing|scikit-image|glcm
2
350,747
24,935,013
Concatenate Panels with different major indexes in pandas
<p>I have measurement sets that are stored in a dataframe like the following:</p> <pre><code>time cname c1 c2 c3 1 0 1 2 2 3 4 5 3 6 7 8 4 9 10 11 </code></pre> <p>where each col is a different measured signal. Each of the sets is measured at a certain parameter value (sa...
<p>this seems a natural problem to use a multi-level index (index is what you have as items/major_axis) and columns as minor_axis. The levels don't have to be fully populated.</p> <pre><code>In [16]: df1 = pn1.transpose('minor_axis','items','major_axis').to_frame() In [17]: df2 = pn2.transpose('minor_axis','items','m...
python|pandas
0
350,748
24,676,092
Python array get positions of value changes
<p>I'm working with some large arrays where usually values are repeated. Something similar to this:</p> <pre><code>data[0] = 10 data[1] = 10 data[2] = 12 data[3] = 12 data[4] = 13 data[5] = 9 </code></pre> <p>Is there any way to get the positions where values do change. I mean, get something similar to this:</p> <pr...
<p>You can use pandas <code>shift</code> and <code>loc</code> to filter out consecutive duplicates.</p> <pre><code>In [11]: # construct a numpy array of data import pandas as pd import numpy as np # I've added some more values at the end here data = np.array([10,10,12,12,13,9,13,12]) data Out[11]: array([10, 10, 12, 1...
python|arrays|pandas
1
350,749
24,826,483
Pandas: divide each row by another row depending on the index
<p>I have a dataframe that contains the minute ticks of various securities from 930am-4pm every day. It looks like:</p> <pre><code> Date TUA COMDTY FVA COMDTY TYA COMDTY USA COMDTY \ 0 2014-03-14 09:30:00 109.898438 119.523438 123.796875 131.34375 1 2014-03-14 09:31:00 109.898438 119....
<p>I assume you are just doing return since close.</p> <p>I have a hack for this purpose. I resample the array to daily data and join it to my original frame. Then I fill the closing price forward. How about something like this?</p> <pre><code>df_daily = df[df["Date"].hour == 16].copy().shift(1) df = df.join(df_da...
python|pandas
0
350,750
30,242,328
Python Pandas Group by Column A and Sum Contents of Column B
<p>I have a Python panda data frame like:</p> <pre><code> A B 0 aa 4 1 bb 6 3 aa 12 4 bb 2 </code></pre> <p>I want to group by Column A and sum values of column B. I am using the following code:</p> <pre><code>df.groupby(by=['A'])['B'].sum() </code></pre> <p>What I get is:</p> <pre><code> ...
<p>You can use the <code>as_index=False</code> option:</p> <pre><code>In [34]: df.groupby('A', as_index=False)['B'].sum() Out[34]: A B 0 aa 16 1 bb 8 </code></pre> <p>By default, pandas will set the column you use to group by as the index. You can also always so a <code>reset_index</code> afterwards.</p>
python|pandas
2
350,751
30,205,962
Python - Generating random dna sequences with Numpy, ValueError
<p>there are two questions i would like to ask anybody that is familiar with numpy. i have seen very similar questions (and answers) but none of those used numpy which i would like to use since it offers a lot of other options i might want to use within that code in the future. i have tried to generate a list of random...
<p>For the first part of your question, pass <code>a</code> as a list:</p> <pre><code>def random_dna_sequence(length): return ''.join(np.random.choice(list('ACTG')) for _ in range(length)) </code></pre> <p>Or define your bases as a list or tuple:</p> <pre><code>BASES = ('A', 'C', 'T', 'G') def random_dna_sequen...
python|numpy|random
7
350,752
29,846,372
Covariance matrix for 9 arrays using np.cov
<p>I have 9 different numpy arrays that <strong>denote the same quantity, in our case <code>xi</code></strong>. They are of length 19 each, i.e. <strong>they have been binned</strong>. </p> <p>The difference between these 9 arrays is that, they have been calculated using jackknife resampling, i.e. by omitting some el...
<p>As you can see in the Example of the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.cov.html" rel="nofollow">docs</a> the shape of the output equals the number of rows squared. Therefore, when you have 9 rows you get a 9x9 matrix</p> <p>If you expect a 19x19 matrix then you probably mixed your c...
python|numpy|matrix|covariance
1
350,753
29,918,650
Pandas: Cast datetime column as int
<p>I have a column of type datetime64 , which already keep in days</p> <pre><code>In [88]: print df.days.head() 0 756 days 1 262 days 2 72 days 3 173 days 4 12 days Name: days, dtype: timedelta64[ns] </code></pre> <p>I want to cast it as int64, I do the following:</p> <pre><code>df['days'] = df['days'].a...
<p>This is <a href="http://pandas.pydata.org/pandas-docs/stable/timedeltas.html#frequency-conversion" rel="nofollow">frequency conversion</a></p> <pre><code>In [3]: s = Series(pd.to_timedelta(['756 days','2 days', '3 days 5 min'])) In [4]: s Out[4]: 0 756 days 00:00:00 1 2 days 00:00:00 2 3 days 00:05:00 d...
python|datetime|pandas
3
350,754
30,153,268
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any()
<p>Here's my code:</p> <pre><code>from scipy.io import wavfile fName = 'file.wav' fs, signal = wavfile.read(fName) signal = signal / max(abs(signal)) # scale signal assert min(signal) &gt;= -1 and max(signal) &lt;= 1 </code></pre> <p>And the error is:</p> <pre><code>Traceback (most recent call last...
<p>The line that produces the error shouldn't give an error if your signal were 1D (ie, a mono audio file), so you probably have a <strong>stereo wav file</strong> and your signal has the shape <code>(nsamples, 2)</code>. Here's a short example for a stereo signal:</p> <pre><code>In [109]: x = (np.arange(10, dtype=fl...
python-2.7|numpy|machine-learning|speech
1
350,755
30,082,052
Most efficient way to implement numpy.in1d for muliple arrays
<p>What is the best way to implement a function which takes an arbitrary number of 1d arrays and returns a tuple containing the indices of the matching values (if any). </p> <p>Here is some pseudo-code of what I want to do: </p> <pre><code>a = np.array([1, 0, 4, 3, 2]) b = np.array([1, 2, 3, 4, 5]) c = np.array([4, 2...
<p>You can use <code>numpy.intersect1d</code> with <code>reduce</code> for this:</p> <pre><code>def return_equals(*arrays): matched = reduce(np.intersect1d, arrays) return np.array([np.where(np.in1d(array, matched))[0] for array in arrays]) </code></pre> <p><code>reduce</code> may be little slow here because ...
python|arrays|sorting|numpy|indexing
6
350,756
30,200,494
Referencing a numpy arrray without creating an expensive copy
<p>Let's say that I have a function that requires that NumPy <code>ndarray</code> with 2 axes, e.g., a data matrix of rows and columns. If a "column" is sliced from such an array, this function should also work, thus it should do some internal <code>X[:, np.newaxis]</code> for convenience. However, I don't want to crea...
<p>It shouldn't create a copy. For illustration:</p> <pre><code>&gt;&gt;&gt; A = np.ones((50000000,)) &gt;&gt;&gt; B = A[:,np.newaxis] &gt;&gt;&gt; B.flags C_CONTIGUOUS : False F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False </code></pre> <p>Note the <code>OWNDATA...
python|arrays|numpy|reference|slice
7
350,757
30,095,096
How to I add intermediate sum columns to a pandas dataframe?
<p>I have a one column data frame containing a list of "winners" which looks like this:</p> <pre><code>+---+--------+ | | Winner | +---+--------+ | 0 | A | | 1 | C | | 2 | D | | 3 | D | | 4 | A | | 5 | B | +---+--------+ </code></pre> <p>But I'm struggling to add intermediate score col...
<p>Create an initial frame:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame(['A', 'C', 'D', 'D', 'A', 'B'], columns=['Winner']) </code></pre> <p>We will use the unique column names, so stash them:</p> <pre><code>&gt;&gt;&gt; names = ('A', 'B', 'C', 'D') # sorted(df["Winner"].unique().t...
python|pandas
3
350,758
30,085,781
Column extracted from DataFrame has a different index
<p>I'm encountering the following situation:</p> <pre><code>some_df.index #=&gt; Int64Index([0, 1], dtype='int64') some_df['some_column'].index #=&gt; Float64Index([7.0, 5.0], dtype='object') </code></pre> <p>Why is this happening? Does this mean there was something wrong in the way <code>some_df</c...
<p>It's unclear whether this is a bug, though perhaps assigning to the Series index should raise (it may be quite tricky to get this behaviour)... You should definitely not be doing this!</p> <p>To confirm that this is indeed the case:</p> <pre><code>In [11]: df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B']) I...
python|pandas
0
350,759
53,696,544
pandas is exporting previous columns in addition to others
<p>I'm trying to export one specific column from a multi-gigabyte CSV with pandas to another CSV file using .to_csv. However, the output contains two columns, instead of one. Here's a sample output: <code>Case_Number 3 HZ250496 89 HZ250409 197 HZ250503 673 HZ250424 911 HZ250455 1108 HZ2504...
<p>Use parameter <code>usecols</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> if want working only with <code>Case_Number</code> column and then <code>index=False</code> in <a href="http://pandas.pydata.org/pandas-docs/s...
pandas|csv|dataframe
1
350,760
53,488,986
groupby in pandas with function that must keep state
<p>I have the following dataframe</p> <pre><code>df = pd.DataFrame({'a': ['A', 'A', 'A', 'B', 'B', 'B', 'B'], 'b': [ 1, 2, 4, 1, 2, 3, 4]}) </code></pre> <p>I want a function that would output the following dataframe definition:</p> <pre><code>df = pd.DataFrame({'a': [ 'A', 'A', ...
<p>You can find the numeric part of column c using groupby and concat values</p> <pre><code>df['c'] = df.groupby('a').b.apply(lambda x: (x.diff() &gt; 1).cumsum()) df['c'] = df['a'] + '_' + df['c'].astype(str) a b c 0 A 1 A_0 1 A 2 A_0 2 A 4 A_1 3 B 1 B_0 4 B 2 B_0 5 B 3 B...
python|pandas
3
350,761
53,577,770
How to use pandas python3 to get just Middle Initial from Middle name column of CSV and write to new CSV
<p>I need help. I have a CSV file that contains names (First, Middle, Last) I would like to know a way to use pandas to convert Middle Name to just a Middle initial, and save First Name, Middle Init, Last Name to a new csv.</p> <p>Source CSV</p> <pre><code>First Name,Middle Name,Last Name Richard,Dale,Leaphart Jimmy...
<p>You can use the <code>str</code> accessor, which allows you to slice strings like you would in normal Python:</p> <pre><code>df['Middle Name'] = df['Middle Name'].str[0] &gt;&gt;&gt; df First Name Middle Name Last Name 0 Richard D Leaphart 1 Jimmy W Autry 2 Willie H...
python|python-3.x|pandas|csv
1
350,762
53,576,591
Left merge between groupby dataframe and original dataframe brings outer merge
<p>Simple question today, probably something to do with the interaction between a DataFrame and a grouped dataframe that came from it.</p> <p>The thing is I've got a DataFrame that has <code>name</code>, <code>gender</code> and <code>foo</code> variables, like this:</p> <pre><code>name gender foo John M ...
<p>So let us using <code>agg</code> </p> <pre><code>df.groupby('name',as_index=False).agg({'gender':'first','foo':'count'}) name gender foo 0 James M 1 1 Jenny F 1 2 John M 2 </code></pre>
python|pandas|dataframe
2
350,763
53,640,386
Tensorflow: Sampling a tensor according to another tensor?
<p>I have a tensor <code>T</code> of shape <code>Batch_Size x Num_Items x Item_Dimension</code> and another tensor <code>P</code> of shape <code>Batch_Size x Num_Items</code>, where the Num_Items values in each batch of P sum to 1 (a probability distribution of items for each batch). I want to sample without replacemen...
<p>Take a look at <a href="https://github.com/tensorflow/tensorflow/issues/9260" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/9260</a></p> <p>Though note I believe you need logits instead of probs for Gumbel max sampling.</p>
tensorflow|deep-learning|tensorflow-probability
1
350,764
53,422,006
how to do this operation in numpy (chaining of tiling operation)?
<p>I'm trying to do fast generation of numpy array, possibly without passing through python.</p> <p>I want to build an 1D index numpy array that would take this as an input:</p> <p><code>[2,3]</code> and this <code>[2,4]</code> and would return this</p> <pre><code> [0,1,0,1,0,1,2,0,1,2,0,1,2,0,1,2] </code></pre> <p...
<p>Here is a vectorized solution:</p> <pre><code>def cycles(spec): steps = np.repeat(*spec) ps = steps.cumsum() psj = np.zeros(ps[-1], int) psj[ps[:-1]] = steps[:-1] return np.arange(ps[-1]) - psj.cumsum() </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; cycles(((2,3),(2,4))) array([0, 1, 0, 1,...
python|arrays|numpy
3
350,765
53,716,629
what use tensorflow estimator create multi-input
<p>Sorry my English is poor =。=</p> <p>I create a keras model and use <code>tf.keras.estimator.model_to_estimator</code> convert to estimator but the model is multi-input, what can I create Dataset feed the data?</p> <p>Here is my model code:</p> <pre><code>model = VGG19(include_top=False, input_shape=(182, 182 , 3)...
<p>First, name input placeholders:</p> <pre><code>input_image = keras.layers.Input(shape=(182, 182, 3),name='image') input_anchor = keras.layers.Input(shape=(182, 182, 3),name='anchor') </code></pre> <p>If your input data are <code>train_data</code> and shape is <code>[(100000, 182, 182, 3), (100000, 182, 182, 3), (1...
python|tensorflow|keras
0
350,766
53,377,024
To create end of business month data frame from a stock data frame
<p>I’m new to Python and Panda’s. I’m trying to figure out how to create a new data frame from a stock data frame that will contain only the rows for the day of the end of the business month.</p> <p>Here is my Stock Data Frame:</p> <pre><code>apple = pd.read_csv("AppleStock.csv") apple.head(10) Date Open High ...
<p>Convert the dates in your dataframe to datetime.</p> <pre><code>apple.index = pd.to_datetime(apple['Date']) </code></pre> <p>Use your month_index to get desired rows.</p> <pre><code>apple_month = apple.loc[month_index] </code></pre>
python|pandas
0
350,767
53,547,391
Finding the longest string of consecutive positive numbers in a list
<p>I have a series:</p> <pre><code>series = [0,2, 1, -2, 0, 0, 2, 3 ,1, 7] </code></pre> <p>What is the most time efficient way of finding the length of the longest string of consecutive positive numbers? In this example, it must be 4 (length of [2, 3, 1, 7])</p>
<p>You could use <code>itertools.groupby</code> to group positive numbers, then use <code>max</code> to find the longest run of such numbers</p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; max((list(g) for k, g in groupby(series, key=lambda i: i &gt; 0)), key=len) [2, 3, 1, 7] </code></pre>
python|pandas
5
350,768
53,512,618
Assign pandas values from a merge result
<p>Say I have two DataFrames, where one is conceptually a subset of the other. How can I efficiently transfer data from the subset to the superset? Here is some data to work with:</p> <pre><code>import pandas as pd sup = pd.DataFrame({'row': [0, 0, 0, 1, 1, 1, 2, 2], 'col': [0, 1, 2, 0, 1, 2, 1, 2...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> and change values using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> a...
python|pandas|merge|inner-join
1
350,769
53,540,305
Shape error when reading tfrecords with tf.data.TFRecordDataset?
<p>I've created a tfrecords file with my own images, and when I try to read it using tf.data.TFRecordDataset, a shape error comes: <a href="https://i.stack.imgur.com/ZkPpN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZkPpN.png" alt="enter image description here"></a> I created the tfrecords with c...
<p>OK, I solved it. My god. It's about the pictures themselves. The bit depth of one of the pictures is 32. Then its shape would be (224,224,4).</p> <p><a href="https://i.stack.imgur.com/MtkH2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MtkH2.png" alt="enter image description here"></a></p>
python|tensorflow|reshape|tfrecord
0
350,770
53,558,269
Getting user input to select a Pandas object
<p>I wish to get a user to select a pandas object. Each object contains just two columns and may have a number of rows. The objects (for the sake of this question) are object1 and object2.</p> <pre><code>import pandas as pd object1 = pd.read_csv(file1.csv) object2 = pd.read_cdv(file2.csv) def printTable(tableName): ...
<p>Why not store things in a dictionary, like so?</p> <pre><code>import pandas as pd object1 = pd.read_csv(file1.csv) object2 = pd.read_cdv(file2.csv) # This is the dictionary, a key-value mapping # We can lookup the key 'object1' (or whatever table name, in your case) # and return the "table"/DataFrame associated to...
python|pandas
2
350,771
53,561,084
Remove specific character in pandas column based on condition
<p><strong>What I have</strong></p> <p>Pandas frame with the following</p> <pre><code>ID Score 0 50 1 60 2 70.5 3 65.5 4 56.5.6 5 56.5.6.7 6 10. 7 56.0. 8 56.5.0. </code></pre> <p><strong>What I am trying to do</strong></p> <p>In column score, remove the dot if it occurs at the end</p> <...
<p>You should use the <a href="https://docs.python.org/3/library/stdtypes.html#str.rstrip" rel="nofollow noreferrer"><code>rstrip</code></a> method, which removes trailing characters:</p> <pre><code>df['Score'] = df.Score.str.rstrip('.') &gt;&gt;&gt; df ID Score 0 0 50 1 1 60 2 2 70.5 ...
python|pandas
3
350,772
53,680,712
array is not callable in python "'numpy.ndarray' object is not callable"
<p>I am working on a neural network and when i try to shuffle the two numpy.ndarray i get this error. I tried rechecking the shuffle function format and cannot find any faults with that. Please help</p> <pre><code>train_images,train_labels = shuffle(train_images,train_labels) TypeError ...
<p>Have a look at the docs of <a href="https://docs.python.org/3/library/random.html#random.shuffle" rel="nofollow noreferrer">random.shuffle(x[, random])</a></p> <blockquote> <p>The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random()<...
python|numpy-ndarray
1
350,773
53,376,005
How to replace a value in a matrix corresponding to another matrix with some additional limitation?
<p>For example, this is my input matrix</p> <pre><code>a = [['1', '2', '3', '4', '5', '6'],['1', '2', '3', '4', '5', '6'],['1', '2', '3', '4', '5', '6']] b = [[(1, 0.044), (2, 0.042)], [(4, 0.18), (6, 0.023)], [(4, 0.03), (5, 0.023)]] </code></pre> <p>And I want to get</p> <pre><code>c= [[0.044, 0.042, 0, 0, 0, 0]...
<p>One way to do this is to use <code>map</code>, list comprehension, and dictionary with <code>get</code>:</p> <pre><code>c = [] for n, i in enumerate(a): c.append([dict(b[n]).get(i, 0) for i in map(int, a[n])]) c </code></pre> <p>Output:</p> <pre><code>[[0.044, 0.042, 0, 0, 0, 0], [0, 0, 0, 0.18, 0, 0.023], ...
python-3.x|numpy|matrix|replace
0
350,774
53,720,905
Python - Grouping Rows into List
<p>I have a pandas data frame like this:</p> <pre><code>TransactionID ProductID 1 132 1 256 1 985 2 321 3 451 3 219 </code></pre> <p>I want to group by the 'TransactionID' and assign the 'ProductID' to a list, like thi...
<p>the following is not so good but can work.</p> <pre><code>result = [list(i.ProductID) for i in dict(list(df.groupby("TransactionID"))).values()] </code></pre>
python|dataframe|pandas-groupby
0
350,775
53,589,032
Get percentage variation of numbers from two dataframes based on column positioning
<p>I have two dataframes:</p> <pre><code>df1=pd.DataFrame({'Product':("A","B","C"),"Data":(1,2,3)}) df2=pd.DataFrame({'Product':("A","B","C"),"Data":(2,4,6)}) </code></pre> <p>I want to get the percentage variation numbers of the columns.</p> <p>I have tried the below code:</p> <pre><code>data1_i=df1.set_index(["Pr...
<p>You can select columns by position with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a>:</p> <pre><code>df1=pd.DataFrame({'Product':("A","B","C"),"Data":(1,2,3)}) df2=pd.DataFrame({'Product':("A","B","C"),"Data_new":(2,4,6)})...
python|python-3.x|pandas|dataframe
1
350,776
53,477,449
Storing values that are lists into database from dataframe using python
<p>How to store values to mysql database that is a dataframe consisting of lists in every row. Below is the dataframe:</p> <pre><code>0 [Nissan Motor, Carlos Ghosn] 1 [Nissan Motor, Carlos Ghosn] 2 [] 3 [Dav...
<p>Something like this?</p> <pre><code>from sqlalchemy.dialects import postgresql x = [["Nissan Motor", "Carlos Ghosn"], ["Nissan Motor", "Carlos Ghosn"], [], ["David Muir", "Trio"], [], [],[]] df = pd.DataFrame({"data": x}) df.to_sql(con = "connection_string", name = "table_name", schema = "schema_name", if_exists="...
python-3.x|pandas|dataframe
1
350,777
53,600,231
Merge data frames based on column with different rows
<p>I have multiple csv files that I read into individual data frames based on their name in the directory, like so</p> <pre><code># ask user for path path = input('Enter the path for the csv files: ') os.chdir(path) # loop over filenames and read into individual dataframes for fname in os.listdir(path): if fname....
<p>Replace <code>combined = reduce(lambda left,right: pd.merge(left,right,on='Key'), dfs)</code> With: <code>combined=pd.merge(demo,key, how='outer', on='Key')</code> You will have to specificy the 'outer' to join both the full table of Key and Demo</p>
python-3.x|pandas|reduce
1
350,778
53,424,382
Panda lambda TypeError object float no len()
<p>Python Pandas lambda for update column with <code>lambda x: np.nan if x == '0/0' else df['RatioFraction']</code></p> <p>Filter on one column then use lambda to change conditional on <code>np.nan</code> for no vote (0/0).</p> <p>Received</p> <pre><code>TypeError: object of type 'float' has no len() </code></pre> ...
<p>Try this:</p> <pre><code>df['RatioFraction'] = df_ff_reviews['VoteRatio'] df['RatioFraction'].loc[df['RatioFraction'] == '0/0'] = np.nan </code></pre>
python-3.x|pandas|lambda
1
350,779
53,577,084
How to binned filtered pandas data?
<p>All,</p> <p>The head of my dataset looks like following.I filtered my "Age" and "Absenteeism time in hours" column and calculated the Average of hours. Now I would like to bin based on Age column. How can I perform this ? I would like to bin Age as age31-33,age 34-36,Age 37-39</p> <pre><code>{'Age': {0: 33, 2: 38,...
<p>You are looking for the function <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></a>. It can be used as follows on your data:</p> <pre><code>group.groupby(pd.cut(group.index, [31, 33, 36, 39])).mean().fillna(0) </code></pre> <p>Whi...
python|pandas|pandas-groupby
2
350,780
53,524,607
Merging list with another list python without loops
<p>I have 2 pandas series that look like this:</p> <pre><code>import pandas as pd listA = [5,4,3] listB = ["a","b","c"] s = pd.Series(listA) print(s) p = pd.Series(listB) print(p) </code></pre> <p>And I would like to obtain a list of the 2 lists mixed together as strings like this:</p> <pre><code>listTogether = ["a5...
<p>A trick from <code>MultiIndex</code></p> <pre><code>listTogether = pd.MultiIndex.from_product([p,s.astype(str)]).map(''.join).tolist() listTogether Out[242]: ['a5', 'a4', 'a3', 'b5', 'b4', 'b3', 'c5', 'c4', 'c3'] </code></pre>
string|python-3.x|pandas|join|merge
5
350,781
53,584,580
What do "Blas GEMM launch failed" errors from Tensorflow mean?
<p>I'm learning tensorflow reading a korean book. I just copied and pasted code of this book but this code shows me error message. I want to find about this but even I can't see which message I should find about. Can anyone help me please...?</p> <p>Here is the code. (using jupyter notebook)</p> <pre><code>import t...
<p>A few days have passed, there was no answer so I write it down myself. I closed all the notebooks and console prompt window, restarted jupyter notebook and it worked. I think the problem was about connections.</p>
python|python-3.x|tensorflow
0
350,782
53,587,315
Pandas - find specific value in entire dataframe
<p>I have a dataframe and I want to search all columns for values that is text 'Apple'. I know how to do it with one column, but how can I apply this to ALL columns? I want to make it a function, so that next time I can directly use it to search for other values in other dateframes.</p> <p>Thanks.</p>
<p>you can try searching entire dataframe using the below code</p> <pre><code>df[df.eq(&quot;Apple&quot;).any(1)] </code></pre> <p>Using <code>numpy</code> comparison</p> <pre><code>df[(df.values.ravel() == &quot;Apple&quot;).reshape(df.shape).any(1)] </code></pre> <p>Both are faster smaller records but not sure about ...
python|python-3.x|pandas|dataframe
15
350,783
53,756,521
How to convert the columns into rows in a dataframe
<p>i have a csv file with the following data as follows: <a href="https://i.stack.imgur.com/oXl0J.png" rel="nofollow noreferrer">input</a></p> <p>i want to convert the columns into rows: <a href="https://i.stack.imgur.com/95qbb.png" rel="nofollow noreferrer">output</a></p> <p>I have tried the following code:</p> <pr...
<p>Use:</p> <pre><code>df = pd.DataFrame({'title':['p1','p2','p3'], 'score':[1,0.1,2]}) print (df) title score 0 p1 1.0 1 p2 0.1 2 p3 2.0 df1 = pd.DataFrame([df.score.values], columns=df.title.values) </code></pre> <p>Alternative:</p> <pre><code>df1 = df.set_index('title')['s...
python-3.x|pandas
0
350,784
53,725,490
Slice DataFrame using indices from other columns
<p>I have a dataframe like that : </p> <pre><code>index value idxmin idxmax 0 300 nan nan 1 200 nan nan 2 100 nan nan 3 200 0 2 4 300 1 2 5 400 1 3 6 500 2 5 7 600 4 5 8 700 4 ...
<p>This operation is inherently difficult to vectorize because the array is not sorted, and the indices do not seem to represent equally sized ranges. I can suggest turning this into a list comprehension to circumvent the overhead from <code>apply</code>, but you're on your own after that.</p> <pre><code>df['maxvalue'...
python|pandas|python-2.7|dataframe
4
350,785
53,728,734
Mark sudden changes in prices in a dataframe time series and color them
<p>I have a Pandas dataframe of prices for different months and years (timeseries), 80 columns. I want to be able to detect significant changes in prices either up or down and color them differently in a dataframe. Is that possible and what would be the best approach?</p> <pre><code>Jan-2001 Feb-2001 Jan-2002 Feb-2002...
<p>Your question involves 2 problems I can see.</p> <ol> <li><p>Printing the highlighting depends on the output method your trying to get to, be it STDOUT, file, or some program specific. </p></li> <li><p>Identification of outliers based on the Column data. Its hard to interpret if you want it based on the entire data...
python-3.x|pandas
1
350,786
53,781,882
Python - Dot product for matrices doesn't seem to work when using sympy and lambdify
<p>I'm implementing a data processing flow in python. I'm trying to use symbolic calculations (<code>sympy</code> and <code>numpy</code>) as much as possible to have clear documentation consistent with the code. So when I try to get dot product and use it for real matrices (by means of <code>lambdify</code>) I get some...
<p><code>lambdify</code> creates a function that should be used on NumPy arrays. If you pass a SymPy object to this function, the resulting behavior is undefined. If you want to evaluate SymPy expressions on SymPy expressions, just use the SymPy expression, using <code>subs</code> to replace the expression. </p> <pre>...
python|numpy|sympy|lambdify
1
350,787
53,375,422
How does pytorch's parallel method and distributed method work?
<p>I'm not an expert in distributed system and CUDA. But there is one really interesting feature that PyTorch support which is <code>nn.DataParallel</code> and <code>nn.DistributedDataParallel</code>. How are they actually implemented? How do they separate common embeddings and synchronize data?</p> <p>Here is a basic ...
<p>That's a great question.<br /> PyTorch DataParallel paradigm is actually quite simple and the implementation is open-sourced <a href="https://pytorch.org/docs/stable/_modules/torch/nn/parallel/data_parallel.html#DataParallel" rel="nofollow noreferrer">here</a> . Note that his paradigm is not recommended today as it ...
python-3.x|parallel-processing|pytorch|distributed-computing
1
350,788
53,796,783
Find if 2 triangles are perpendicular in 3D space
<p>I have 2 triangles in 3D space made of 3 points.</p> <p>I assume I need to use the dot product but how do I arrange the matrix? </p> <p>I think I have the pieces but need help to arrange it :)</p> <p>Thank you.</p> <p>Current code included below, not convinced it is correct.</p> <pre><code>vx1 = self.vertices[f...
<p>I'll assume here that the triangles do not need to actually intersect to be considered "perpendicular".</p> <p>In that case, the triangles are perpendicular if and only if their normal vectors are perpendicular. To find the normal vector of Triangle 1, take the cross-product of the vectors making the sides. I.e. if...
python|numpy|math|geometry|dot-product
1
350,789
53,482,281
Unknown mathematical error in sympy equation (python)
<p>I am attempting to plot the functions j0,j1 &amp; j10 in the range r(0,20) by converting them to numpy format using lambdify. I used the following code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import sympy as sym from ipywidgets.widgets import interact sym.init_printing(use_latex=&quot;math...
<p>Your problem is caused by a division by zero, which is numerically hard to deal with, even though the limit of <code>r-&gt;0</code> may be finite. I would have two (slightly different) solutions to the problem. </p> <p>1) Replace the problematic point with the mathematical exact result. In your example this would m...
python|numpy|matplotlib|sympy
1
350,790
53,618,937
Transform a dataframe without looping?
<p>I would like to analyse and transform the following DataFrame</p> <pre><code>import random import string import numpy as np import pandas as pd # generate example dataframe df=pd.DataFrame() df['Name']=[str(x) for x in np.random.choice(['a','b','c'],10)] df['Cat1']=[str(x) for x in np.random.choice(['x',''],10)] d...
<p>Try:</p> <pre><code>df.set_index('Name').eq('x')\ .groupby('Name')['Cat1','Cat2','Cat3'].sum()\ .astype(int).reset_index() </code></pre> <p>Output:</p> <pre><code> Name Cat1 Cat2 Cat3 0 a 5 3 4 1 b 1 1 0 2 c 1 1 1 </code></pre>
python|pandas
2
350,791
53,577,505
Get the Minimum value from Consecutive dataframe values
<p>I have a Dataframe in Python Pandas:<br></p> <pre><code>Date Open High Low last Close 11/30/2018 289.5 290 284.8 286.2 285.8 11/29/2018 283.65 289.3 283.45 288.35 287.55 11/28/2018 285.4 287.95 280.8 282.2 282.2 11/27/2018 286.1 286.45 282.8 284.4 284.85 11/26/2018 281.25 286....
<p>Use the <a href="https://pandas.pydata.org/pandas-docs/stable/computation.html?highlight=window#window-functions" rel="nofollow noreferrer">rolling window function</a> with the min <em>statistic</em> shifted up three and subtract the original DataFrame.</p> <pre><code>df - df.rolling(3).min().shift(-3) </code></pre...
python|pandas|dataframe
4
350,792
53,748,877
python 3 for loop "TypeError: 'int' object is not iterable"
<p>I want to change color specific coordinates. I can take all x, y coordinates and change to color in for loop. My code is:</p> <pre><code>import numpy as np import math from PIL import Image from PIL import ImageDraw im = Image.open('harita2.png').convert("RGB") npimage = np.array(im) g1= np.array([93,95,95],dtype=...
<pre><code>count = 12 for i in count: print(i) </code></pre> <blockquote> <p>Output: TypeError: 'int' object is not iterable</p> </blockquote> <p>Answer is to use python function <a href="https://www.freecodecamp.org/news/int-object-is-not-iterable-python-error-solved" rel="nofollow noreferrer">range</a></p> <pre><...
python-3.x|numpy|python-imaging-library
0
350,793
53,801,766
I can't import tensorflow-gpu
<p>I've successfully installed tensorflow with <code>pip install tensorflow</code> and that all works as expected.</p> <p>I can also successfully install tensorflow-gpu with <code>pip install tensorflow-gpu</code> but I can't import it in my python script:</p> <pre><code>import tensorflow-gpu File &quot;&lt;stdin&gt;...
<p>The package on pypi is called tensorflow-gpu but you just import it with "tensorflow"</p> <pre><code> import tensorflow as tf </code></pre>
python|python-3.x|tensorflow
4
350,794
53,787,144
Broadcast mask operation on array
<p>I'm trying to improve the performance of a rather simple masking operation on three arrays given the distance of the elements in one of their columns to the same column of a fourth array. All arrays have the same shape.</p> <p>Can the performance of this operation be improved via broadcasting?</p> <pre><code># Ran...
<p>As an alternative to broadcasting, I get roughly 10x speedup with numba.</p> <pre><code>np.random.seed(0) xs = np.random.uniform(0, 10, (4, 10, 1000)) x1, x2, x3, x4 = xs.copy() from numba import jit @jit(nopython=True) def modified(xs): dist = .01 for i in range(1, 4): for j in range(1000): ...
python|performance|numpy|array-broadcasting
1
350,795
53,703,043
Python dataframe; trouble changing value of column with multiple filters
<p>I have a large dataframe I took off an ODBC database. The Dataframe has multiple columns; I'm trying to change the values of one column by filtering two other. First, I filter my dataframe data_prem with both conditions which gives me the correct rows:</p> <pre><code>data_prem[(data_prem['PRODUCT_NAME']=='ŽZ08') &a...
<p>Given your Boolean <code>mask</code>, you've demonstrated two ways of applying <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow noreferrer">chained indexing</a>. This is the cause of the warning and the reason why you aren't seeing your logic being applied ...
python|pandas|dataframe|filter
0
350,796
53,523,267
Fast Fourier Transform adjust scaling
<p>I'm trying to show trends of my data by doing a FFT. The data I want to perform a FFT on looks like this:</p> <p><a href="https://i.stack.imgur.com/grCG0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/grCG0.png" alt="Raw data"></a></p> <p>Within every year we see a clear trend almost like a sin...
<p>Looking at the original data, I see a very different plot than if I look at the detrended data that you (and the other answers) have used to compute the FFT from.</p> <p>So, starting with this original data:</p> <pre><code>import numpy as np import matplotlib.pyplt as pp # Data y = np.array([4.9163581574416115, 4...
python|numpy|fft
3
350,797
53,603,743
How to rank data, but give the same ranking for data that is equal
<p>I have a csv of daily maximum temperatures. I am trying to assign a "rank" for my data. I first sorted my daily maximum temperature from lowest to highest. I then created a new column called rank.</p> <pre><code>#Sort data smallest to largest ValidFullData_Sorted=ValidFullData.sort_values(by="TMAX") #count total ob...
<pre><code>ValidFullData['TMAXRank'] = ValidFullData[ValidFullData['TMAX'] &lt; 95]['TMAX'].rank(ascending=False, method='dense') </code></pre> <p>Output:</p> <pre><code> Unnamed: 0 TMAX TMIN TMAXRank 17 17 88 14 1.0 16 16 76 12 2.0 15 15 72 11 3.0 ...
python|pandas|csv|rank
0
350,798
53,411,462
Adding categorical columns into the prediction model
<p>I got a dataframe of customers and information about their activity, and I've built a model that predicts if they buy the product or not. my label is a column 'did_buy' which assigns 1 if a customer bought, and 0 if not. my model takes into consideration the numeric columns, but I'd also like to add categorical colu...
<p>you have different choices to convert categorical variables to numerical or binary variables. for example, country column in your data frame has different values(e.g, France,China,,...). one of solutions that you can convert them to numerical variables is: {France:1, China:2, ....} </p> <pre><code>#import libraries...
python|pandas|numpy|scikit-learn|data-science
1
350,799
17,443,202
how to select a portion of a data frame and convert it into an array in pandas?
<p>I have a dataFrame of shape (5,5) and I want to select the values from <strong>columns</strong> 1 through 3 and from that, i want to select <strong>rows</strong> 1 through 3 and convert them to an <strong>array</strong>.</p> <p>for example, if this is the original dataFrame :</p> <p><img src="https://i.stack.imgur...
<p>something like: <code>df.iloc[1:4,1:4].values</code> ?</p>
python|pandas
1