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
12,000
34,551,942
How to write summaries for multiple runs in Tensorflow
<p>If you look at the Tensorboard <a href="https://www.tensorflow.org/tensorboard/cifar.html">dashboard</a> for the cifar10 demo, it shows data for multiple runs. I am having trouble finding a good example showing how to set the graph up to output data in this fashion. I am currently doing something similar to <a href=...
<p>The solution turned out to be simple (and probably a bit obvious), but I'll answer anyway. The writer is instantiated like this:</p> <pre class="lang-py prettyprint-override"><code>writer = tf.train.SummaryWriter(FLAGS.log_dir, sess.graph_def) </code></pre> <p>The events for the current run are written to the spec...
tensorflow|tensorboard
31
12,001
34,827,850
align timeseries in pandas
<p>I have 2 time series. </p> <pre><code>df=pd.DataFrame([ ['1/10/12',10], ['1/11/12',11], ['1/12/12',13], ['1/14/12',12], ], columns=['Time','n']) df.index=pd.to_datetime(df['Time']) df1=pd.DataFrame([ ['1/13/12',88], ],columns=['Time','n'] ) df...
<p>Here is what you need:</p> <pre><code>df.append(df1).sort().reset_index(drop=True) </code></pre> <p>If you need to compile more pieces together, it is more efficient to use <code>pd.concat(&lt;names of all your dataframes as a list&gt;)</code>.</p> <p>P.S. You code is a bit redundant: you don't need to cast <code...
python|pandas
1
12,002
60,271,049
How to implement a neural network to play an endless runner game?
<p>After learning the basics of neural networks I want to create a small but an unique project (something more difficult than handwritten digits etc). I chose to implement an endless runner game, record my moves and train a neural network with the collected data.</p> <p><strong>Game looks like this:</strong></p> <p>...
<p>Ok, thank you. I will try to do this with reinforcment learning. </p>
python|tensorflow|machine-learning|neural-network
0
12,003
60,197,200
Analyzing data from multiple .txt files in pandas
<p>I have 1000+ text files. Each has dates ( which I have made the index) and stock prices (which are column 0). I have created the code to find an individual file's price's moving average, and rolling difference between the price and the moving average. I would like to create code to do this for every file. I have to ...
<p>If you are looking to just iterate over all of your input files in a given folder, you might want to try <code>os.listdir()</code> to get a list of filenames, which you can then process sequentially. If your files are spread over layers of folder, you could use <code>os.walk()</code> to traverse the directories. You...
python|python-3.x|pandas|matplotlib|finance
1
12,004
65,293,600
Count characters in a pandas column
<p>is there a way to explicitly count characters in a pandas column for Strings and group them by their respective word?</p> <pre><code>df[&quot;text&quot;]=[[&quot;Hello how are you?&quot;],[&quot;I am fine&quot;]] Then the counter should be df[&quot;count&quot;]= [[0-4 6-8 10-12 14-16 17],[0 2-3 5-8]] </code></pre>
<p>As far as I know there is no pandas functionality for what you ask, but you can do:</p> <pre><code>import re import pandas as pd # setup df = pd.DataFrame(data=[[&quot;Hello how are you?&quot;], [&quot;I am fine&quot;]], columns=['text']) def extract_spans(m): &quot;&quot;&quot;Convert span to required string...
python|pandas
1
12,005
50,151,585
How to use a saved model in Keras to predict and classify an image?
<p>I trained a model hand position classifier with Keras and I ended up saving the model with the code (model.save('model.h5') ) now i'm traying to predict an image using this model is it doable? if yes could you give me some examples please ? PS:my data is provided as a CSV file</p>
<p>First of all, you have to import the saved model using <code>load_model</code> function.</p> <pre><code>from keras.models import load_model model = load_model('model.h5') </code></pre> <p>Before you will predict the result for a new given input you have to invoke <code>compile</code> method.</p> <pre><code>classi...
python|tensorflow|machine-learning|keras|artificial-intelligence
4
12,006
50,162,727
Variable Partial Array Summation in Python
<p>I'm looking for a solution to sum per column in a 2D array ("a" in the example below) and starting from a cell position as defined in a different 1D array ("ref" in the example below).</p> <p>I have tried the following:</p> <pre><code>import numpy as np a = np.arange(20).reshape(5, 4) print(a) ...
<p>A basic solution based on np.cumsum:</p> <pre><code>In [1]: a = np.arange(15).reshape(5, 3) In [2]: res = np.array([0, 2, 3]) In [3]: b = np.cumsum(a, axis=0) In [4]: b Out[4]: array([[ 0, 1, 2], [ 3, 5, 7], [ 9, 12, 15], [18, 22, 26], [30, 35, 40]]) In [5]: a Out[5]: array([[ ...
python|arrays|numpy|sum
1
12,007
50,109,629
Image classification with Keras: "expected activation_1 to have shape (2,) but got array with (1,)"
<p>I'm training an image classifier to distinguish cats and dogs, from the Kaggle set.</p> <p>Here's my relevant code:</p> <pre><code>FINAL_ACTIVATION = "softmax" OPTIMIZER = keras.optimizers.Adamax() STRIDES = (2, 2) DROPOUT = 0.5 model = Sequential() model.add(Conv2D(32, (3, 3), input_shape = INPUT_SHAPE)) model.a...
<blockquote> <p>Due to the large number of training files, there's no testing set.</p> </blockquote> <p>While this is not your question, I feel this should be addressed: I understand there are some groups following a very different approach and not keeping valid/test sets, but this sounds very unorthodox and uncerta...
python|tensorflow|neural-network|keras|convolutional-neural-network
1
12,008
50,138,622
python pivot table - columns are dates and should be sorted correctly
<p>My objective in the following dataframe is to count how many cars were sold in a specific location for a given month. You will note that the pivot result are correct BUT the columns (dates) are inconsistent. The reason why it's inconsistent is because I'm aggregating the month as a string (if a car was sold on 9-Oct...
<p>You can do the following:</p> <p>First, extract the month from the date:</p> <pre><code>df.SALE_DATE = pd.to_datetime(df.SALE_DATE).dt.month </code></pre> <p>Now pivot:</p> <pre><code>df = df.pivot_table(values="CAR", index="LOCATION", columns='SALE_DATE', aggfunc='count').fillna(0) </code></pre> <p>Sort by the...
python|pandas|pivot|pivot-table
1
12,009
63,821,633
pandas version is not updated after installing a new version on databricks
<p>I am trying to solve a problem of pandas when I run python3.7 code on databricks.</p> <p>The error is:</p> <pre><code> ImportError: cannot import name 'roperator' from 'pandas.core.ops' (/databricks/python/lib/python3.7/site-packages/pandas/core/ops.py) </code></pre> <p>the pandas version:</p> <pre><code>pd.__versio...
<p>It's really recommended to install libraries via <a href="https://docs.databricks.com/clusters/init-scripts.html" rel="nofollow noreferrer">cluster initialization script</a>. The <code>%sh</code> command is executed only on the driver node, but not on the executor nodes. And it also doesn't affect Python instance t...
python|python-3.x|pandas|databricks
2
12,010
64,100,466
How to use tf.Dataset in Keras model.fit without specifying targets?
<p>I want to use an AutoEncoder model with Keras functional API. Also I want to use <code>tf.data.Dataset</code> as an input pipeline for the model. However, there is limitation that I can pass the dataset to the <code>keras.model.fit</code> only with tuple <code>(inputs, targets)</code> accroding to the <a href="https...
<p>In TensorFlow 2.4, I've got a dataset that returns a tuple of one element, ie <code>(inputs,)</code>, which is training just fine. The only caveat is of course that you cannot pass a loss or metrics to <code>model.compile</code>, but must instead use the <code>add_loss</code> and <code>add_metric</code> APIs somewhe...
python|tensorflow|keras|deep-learning|unsupervised-learning
0
12,011
63,995,521
Pandas : Add 2 time columns and create a new column
<p>I am new to Pandas and was wondering if this is possible.</p> <p>I have two columns one with epoch time and another with milliseconds count. I want to create a 3rd column, that has time in milliseconds using both of these as single time column that has time in ms, so that I can easily select data frame between given...
<p><code>pd.to_datetime</code> will convert your epoch time to a date (specify <strong>s</strong>econds for the unit), then use <code>pd.to_timedelta</code> to add the milliseconds.</p> <pre><code>df['datetime'] = (pd.to_datetime(df['my_time'], unit='s') + pd.to_timedelta(df['my_ms_counts'], unit='ms...
python|pandas|numpy
5
12,012
63,852,130
Reading in SQL files into Pandas Table
<p>I have a SQL file titled &quot;DreamMarket2017_product.sql&quot;. I believe it's MySQL.</p> <p>How do I read this file into a Jupyter Notebook using PyMySQL? Or, should I use Psycopg2?</p> <p>I'm much more familiar w/ Psycopg2 than PyMySQL.</p> <p>Both PyMySQL and Psycopg request a database name. There is no databas...
<p>Yes, u need to create a database and load data into table or import table backup u have</p> <pre class="lang-py prettyprint-override"><code>connection = psycopg2.connect(user = &quot;dummy&quot;,password = &quot;1234&quot;,host = &quot;any&quot;,port = &quot;1234&quot;,database = &quot;demo&quot;) </code></pre>
python|mysql|pandas|dataframe
1
12,013
63,820,810
How to add each entries of multiple pandas dataframes. Python
<p>I'm trying to take a new set of values in dataframe and add it to an existing one. But the addition I want is a 1 to 1. So the first entry in the dataframe adds to its respective entry in the 2nd dataframe, and so on. I can easily do this if I was using numpy, but with pandas, this is been quite difficult. I'm also...
<p>Never mind. It's much easier to just convert the dataframe into numpy, and do the same exact thing I did above.</p> <pre><code>values = ts.value </code></pre>
python|pandas|numpy
0
12,014
64,155,524
Python Pandas cumsum with shift of n
<p>I would like to know if there is an efficient way (avoiding for loops) of doing a <code>serie.cumsum()</code> but with a <strong>shift of n</strong>.</p> <p>The same way you can see <code>serie.cumsum()</code> like the inverse of <code>serie.diff(1)</code> I am looking for an inverse of <code>diff(n)</code> (I know ...
<p>You can use the pandas method <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.window.rolling.Rolling.sum.html" rel="nofollow noreferrer">rolling.sum()</a> among with sum:</p> <pre><code>s.rolling(shift).sum() </code></pre> <p>However you may want to fill the NaN values until the shift...
python|python-3.x|pandas
1
12,015
33,053,269
Trying to generate a rolling_sum with Pandas
<p>I have a simple <code>dataFrame</code> with regular samples:</p> <pre><code>dates = pd.date_range('20150101', periods=6) df = pd.DataFrame([1,2,3,4,5,6], index=dates, columns=list('A')) df.loc[:,'B'] = 0 df.iloc[0,1] =10 df Out[119]: A B 2015-01-01 1 10 2015-01-02 2 0 2015-01-03 3 0 2015-01...
<p>Try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.expanding_sum.html" rel="nofollow"><code>expanding_sum</code></a>:</p> <pre><code>In [15]: df Out[15]: A B 2015-01-01 1 10 2015-01-02 2 0 2015-01-03 3 0 2015-01-04 4 0 2015-01-05 5 0 2015-01-06 6 0 In [16]: df...
python|pandas
2
12,016
32,734,967
multiple boxplots from Pandas dataframe
<p>I'm trying to plot a panelplot with multiple boxplots from data in pandas dataframe. The columns of dataframe look like this:</p> <pre><code> data.columns Index([u'SiteId', u'obs1', u'obs2', u'obs3', u'obs4', u'obs5', u'obs6', u'date', u'area'] </code></pre> <p>I want to create a panel of 9 different plots (sinc...
<p>Does this do what you want?</p> <pre><code>fig, axs = plt.subplots(len(areas), 1, figsize=(5,45)) for ax,area in zip(axs,areas): df2 = df.loc[(df.area==area)] df2.boxplot(column=['obs1'], by=df2.index.month, showmeans=True, ax=ax) </code></pre>
python|pandas|matplotlib
3
12,017
32,868,352
Combine two pandas dataframes adding corresponding values
<p>I have two dataframes like these:</p> <pre><code>df1 = pd.DataFrame({'A': [1,0,3], 'B':[0,0,1], 'C':[0,2,2]}, index =['a','b','c']) df2 = pd.DataFrame({'A': [0,0], 'B':[2,1]}, index =['a','c']) </code></pre> <p>df1 and df2:</p> <pre><code> | A | B | C | | A | B | ---|---|---|---| ---|---|---|...
<p>Going by the idea in the answer for this question - <a href="https://stackoverflow.com/questions/16583668/merge-2-dataframes-in-pandas-join-on-some-columns-sum-up-others">merge 2 dataframes in Pandas: join on some columns, sum up others</a></p> <p>Since in your case, the indexes are the ones that are common, you ca...
python|pandas|data-analysis
8
12,018
38,618,414
Precision Difference: NumPy Object Array vs. Float Array
<p>I understand that the precision of a NumPy float array's element is limited by the machine epsilon.</p> <p>However, I'm struggling to understand why specifying the array's datatype as a Python object, instead of as the default float, results in the array storing the precise value I feed it. Can someone please expla...
<p>That's just a matter of display formatting you're seeing. You're not actually getting a more precise number either way; it's just that the <code>precision=64</code> display setting you set doesn't apply to object arrays. It only applies to arrays of floating-point dtype.</p> <p>If you print more digits of the conte...
python|numpy|precision|eps
3
12,019
38,549,491
running python code on distributed cluster
<p>I need to run some numpy computation on 5000 files in parallel using python. I have the sequential single machine version implemented already. What would be the easiest way to run the code in parallel (say using an ec2 cluster)? Should I write my own task scheduler and job distribution code?</p>
<p>You can have a look <a href="https://github.com/parashardhapola/pscheduler" rel="nofollow noreferrer">pscheduler</a> Python module. It will allow you to queue up your jobs and run them sequentially. The number of concurrent processes will depend upon the available CPU cores. This program can easily scale up and subm...
python|numpy
1
12,020
38,596,519
Removing certain rows in Pandas Dataframe by string format
<p>I have a Pandas dataframe with a column called Zip Code. The column is an object data type and some rows are not in proper zip code format. I would like to remove rows that do not contain ##### format zipcode. </p> <pre><code> Subscriber Type Zip Code 0 Subscriber 94040 1 Customer 11231...
<p>try this:</p> <pre><code>In [23]: df = df[df['Zip Code'].str.contains(r'^\d{5}$')] In [24]: df Out[24]: Subscriber Type Zip Code 0 Subscriber 94040 1 Customer 11231 2 Customer 11231 </code></pre> <p>Explanation:</p> <pre><code>In [22]: df['Zip Code'].str.contains(r'^\d{5}$') Out[22]...
python|pandas|dataframe
5
12,021
63,044,059
Add total row to the top of dataframe
<p>I've been trying to find how to add the 'total' row to the top of the dataframe, rather than the bottom, but haven't managed to - I need to reference the row by a label rather than by using iloc or a numerical index since the index is qualitative and the number of rows will vary.</p> <p>I've appended the row to the ...
<p>Try <code>append</code></p> <pre><code>df.sum(axis=0).to_frame('Total').T.append(df) </code></pre>
python|pandas|dataframe|aggregate
2
12,022
62,899,393
Creating a new column based on condition on other columns
<p>I am trying to create a column based on a condition in other columns.</p> <p>There are 5 Individuals Age in a house. I need to count no of individuals in that house by different gender and Age-groups.</p> <p>Code I have written is not working</p> <pre><code>from pandas import DataFrame df1 = pd.DataFrame({'member':...
<p>You could do:</p> <pre><code>df1['M_20_to_30'] = (df1 .iloc[:,df1.columns.str.startswith('M')] .apply(lambda x: sum(x.ge(20) &amp; x.le(30))), 1)) member M1 M2 M3 M4 M5 G1 G2 G3 G4 G5 M_20_to_30 0 1 20 27 77 20 0 M M M M 0 3 1 2 35...
python|pandas|dataframe|if-statement|countif
0
12,023
63,228,335
Rename Columns in Pandas Using Lambda Function Rather Than a Function
<p>I'm trying to rename column headings in my dataframe in pandas using <code>.rename()</code>.</p> <p>Basically, the headings are :</p> <pre><code>column 1: &quot;Country name[9]&quot; column 2: &quot;Official state name[5]&quot; #etc. </code></pre> <p>I need to remove <code>[number]</code>.</p> <p>I can do that with...
<p>First you would have to create function which returns new or old value - never <code>None</code>.</p> <pre><code>def column(name): if '[' in name: return name[:name.index('[')] # new - with change else: return name # old - without change </code></pre> <p>and then you can use it as</p> <pre>...
python|pandas
1
12,024
63,099,243
Faster way to find which lists share elements
<p>I have a pandas dataframe of shape (142000, 1) with a column named keywords where each cell contains a list of keywords.</p> <p>I want to check which rows have at least one equal keyword.</p> <pre><code>for i in combinations(list(range(len(df.index))), 2): if set(df['keywords'][i[0]]) &amp; set(df['keywords'][i[...
<p>Create an index from keywords to a set of all indices at which that keyword appears (I'm not super familiar with Pandas so you may need to fix some things):</p> <pre><code>keyword_index = defaultdict(set) for i, keywords in enumerate(df['keywords']): for keyword in keywords: keyword_index[keyword].add(i)...
python|pandas
1
12,025
67,808,557
Input 0 is incompatible with layer model_1: expected shape=(None, 244, 720, 3), found shape=(None, 720, 3)
<p>I wanted to test my model by uploading an image but I got this error. And I think I got the error somewhere in these lines, I'm just not sure how to fix.</p> <pre><code>IMAGE_SIZE = [244,720] inception = InceptionV3(input_shape=IMAGE_SIZE + [3], weights='imagenet',include_top=False) </code></pre> <p>Also here's the ...
<p>This is mostly because you didn't prepare your input (its dimension) for your inception model. Here is one possible solution.</p> <hr /> <p><strong>Model</strong></p> <pre><code>from tensorflow.keras.applications import * IMAGE_SIZE = [244,720] inception = InceptionV3(input_shape=IMAGE_SIZE + [3], ...
tensorflow|machine-learning|keras|deep-learning|conv-neural-network
0
12,026
67,998,630
For loop charts - changing xtick frequency dynamically for each chart
<p>I'm trying to increase the number of xticks for each chart in the dataframe.</p> <pre><code>for c in df: fig = plt.figure(figsize=[10,5]); ax = df[c].plot(kind='hist', color=(0.2,0.4,0.6,0.6), bins=30); </code></pre> <p><a href="https://i.stack.imgur.com/it4nO.png" rel="nofollow noreferrer"><img src="https://i...
<p>the function doesn't understand the c in min (and I guess it is max(c) too. it works this way:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=[10,5]) for c in df: ax = df[c].plot(kind='hist', color=(0.2,0.4,0.6,0.6), bins=30) plt.xticks(np.arange(mi...
python|pandas|matplotlib
0
12,027
68,001,377
Python Shift values in one column based on Nan or boolean in other column
<p>Thank you so much for your help! It is great to have access to such a great community :) <strong>edited</strong></p> <p>I'm desperately trying to solve this for two days now, so I really hope to get some help from you all.</p> <p>I have a table that looks like this:</p> <div class="s-table-container"> <table class="...
<p>You are using <code>ColumnA</code> as the subject of your logical statement. There is an easier approach to this:</p> <ol> <li>If <code>ColumnB</code> is null, use the row below it. If not, keep its original value.</li> <li>If <code>ColumnA</code> is 'not_translated', keep null in <code>ColumnB</code>.</li> <li>Drop...
python|pandas|numpy|boolean|nan
2
12,028
67,771,110
Is there a way to find value of a row on the bases of the last n rows in another column in a pandas Dataframe?
<p>I want to find the value of a new column dev for each row of a dataframe such that:</p> <pre><code>n=100 slope=0.8 inv=3 for i in range(0,n): dev += math.pow(src[i] - (slope * (n - i) + inv), 2) </code></pre> <p>Where src is a list of the previous n values of a column of the same dataframe.</p> <p>Thus if my data...
<p>Hello there MrOmnipotent. Do you mean something like this?</p> <pre><code>df['dev'] = 0 ##Create a column dev with dummy values for idx in df.index: #interating on the indexes dev = 0 for i in range(n+1): #interating on the n values if idx &gt;= i: print(idx, '-', i, '=', idx-i) #idx - i...
python|pandas|dataframe|apply
0
12,029
68,011,281
different outputs for checking if a nan value is in the list or not
<p>I have a list and I want to check if there is a missing value or not! I used two different ways to check it but didn't get the same outputs!</p> <pre><code>np.nan in lst1 </code></pre> <p>output for this one is &quot;False&quot;</p> <pre><code>n = 0 for i in range(len(lst1)): if lst1[i] is np.nan : n+=1 ...
<p>To use math.isnan(x) is preferred way of NaN finding. As I understand np.nan and pure python NaN are not the same objects. And you get False at checking.</p> <pre><code>import math import numpy as np lst1 = [1,2,3, float('nan'), 2, np.nan, 4] for ix, vl in enumerate(lst1): if math.isnan(vl): print(ix, v...
python|numpy
2
12,030
31,771,619
HTML table to pandas table: Info inside html tags
<p>I have a large table from the web, accessed via requests and parsed with BeautifulSoup. Part of it looks something like this:</p> <pre><code>&lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;265&lt;/td&gt; &lt;td&gt; &lt;a href="/j/jones03.shtml"&gt;Jones&lt;/a&gt;Blue&lt;/td&gt; &lt;td&gt;29&lt;/td&gt; &lt;/tr&gt;...
<p>Since this parsing job requires the extraction of both text and attribute values, it can not be done entirely "out-of-the-box" by a function such as <code>pd.read_html</code>. Some of it has to be done by hand.</p> <p>Using <a href="http://lxml.de/" rel="noreferrer">lxml</a>, you could extract the attribute values ...
python|pandas|beautifulsoup
10
12,031
41,593,778
create an 4-column Array from the 3D numpy array in Python
<p>I have a 3D numpy array of dimension(737,737,90) which contains the intensity values of type float32(i.e., Voxel Intensities). My query is How can i make an array that look a like A = [x-co_ordinate, y-co_ordinate, z-co_ordinate, I(x,y,z)].</p> <p>where I(x,y,z) value is the array(737,737,90) as mentioned above is ...
<p>One approach would be to get all those indices with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.indices.html" rel="nofollow noreferrer"><code>np.indices</code></a> and then stack it with the input array. The output would be in <code>(4, X, Y, Z)</code> format. So finally, to get it in <code>4...
python|numpy
1
12,032
61,540,358
Drop Rows if value of subset is [] from dtype Object
<p>my DataFrame looks like that:</p> <p><a href="https://i.stack.imgur.com/20UDb.png" rel="nofollow noreferrer">DataFrame</a></p> <p>I found this but it didn´t work for me. <a href="https://stackoverflow.com/questions/29314033/drop-rows-containing-empty-cells-from-a-pandas-dataframe">Drop rows containing empty cells...
<p>If the column contains 'list' objects:</p> <pre><code>df_model['Zustand'].apply(lambda x: np.nan if len(x)==0 else x) df_model.dropna(subset=['Zustand'], inplace=True) </code></pre>
pandas
0
12,033
68,597,762
Delete emojis or replace for text using regex in pandas
<p>I have this toy dataset:</p> <pre><code>df = pd.DataFrame({'id':[1,2,3,4,5,6], 'text':['Oh no Monday','Oh no Monday','Gotcha !', 'Coffee, please','Coffee, please','Mails '], 'dates':['2019-05-30T17:48:45+0000','2019-05-30T17:48:45+0000', ...
<p>You can delete emojis using regex:</p> <pre><code>pat = r'[\U0001F600-\U0001F64F]|[\U0001F300-\U0001F5FF]|[\U0001F680-\U0001F6FF]|[\U0001F1E0-\U0001F1FF]' </code></pre> <pre><code>&gt;&gt;&gt; df['text'].str.replace(pat, '', regex=True) 0 Oh no Monday 1 Oh no Monday 2 Gotcha ! 3 Coffee, please ...
python|regex|pandas
2
12,034
68,664,341
Converting 2D array into 3D by repeating same layer 3 times
<p>I have a 2d array of shape (512,512). I need to convert this to shape (512,512,3). All values of 2d dimension will be repeated on other two dims. How can I do this in python?</p>
<p>you can try using np dstack</p> <p>it would work for your case</p> <pre><code>np.dstack([a,a,a]) </code></pre>
python|numpy
2
12,035
68,492,173
"No columns to parse from file" error when trying to transform string into Pandas dataframe
<p>I have a string object (&quot;textData&quot;) which contains CSV data.</p> <p>I'm able to save it as CSV by:</p> <pre><code> with open(fileName, &quot;w&quot;) as text_file: print(textData, file=text_file) </code></pre> <p>but I would like to work with the data in pandas before saving the csv. So I'm tryi...
<p>The error is in the parts you aren't showing us, because your code works fine. I'm guessing you don't have newlines separating the lines.</p> <pre><code>C:\tmp&gt;type x.py textData=&quot;&quot;&quot;\ R$M21,2021-06-08,1.3236,1.3238,1.3226,1.3237,290,343 R$M21,2021-06-09,1.3232,1.3243,1.3231,1.3233,48,343 R$M21,20...
python|python-3.x|pandas|csv|stringio
2
12,036
36,671,519
Long to wide format for multiple column in python
<p>I am having a student examination dataset such as follows,</p> <pre><code>userid grade examid subject numberofcorrectanswers numberofwronganswers 4 5 8 Synonyms NULL NULL 4 5 8 Sentence NULL NULL 4 ...
<p>Something like this?</p> <pre><code>&gt;&gt;&gt; df.groupby(['userid', 'grade','examid','subject']).sum().unstack('subject') numberofcorrectanswers numberofwronganswers subject Decimals Sentence Synonyms Wh...
python|python-2.7|pandas
2
12,037
5,350,342
Can i set float128 as the standard float-array in numpy
<p>So I have a problem with my numerical program, and I'm curious about whether it is a precision problem (i.e. round-off error). Is there a quick way to change all the float arrays in my program into <code>float128</code> arrays, without going through my code and typing <code>dtype='float128'</code> all over the place...
<p>I don't think there is a central "configuration" you could change to achieve this. Some options what you could do:</p> <ol> <li><p>If you are creating arrays only by very few of NumPy's factory functions, substitute these functions by your own versions. If you import these functions like</p> <pre><code>from nump...
python|numpy|types
19
12,038
53,289,238
Convert a dictionary to DataFrame with specified column names
<p>I have a dictionary which is <code>dict['TimeStamp'] = [value1,value2,value3]</code> the dict has many times stamps and each time stamp has 3 values for example I want to make panda dataframe of all values of dictionary of column1, 2, 3</p> <pre><code>dict['timestamp1'] = [1,2,3] dict['timestamp2'] = [4,5,6] </cod...
<p>You can do this in one line by unpacking the dictionary and labeling your columns:</p> <pre><code>pd.DataFrame(data=[*dict.values()], columns=['firstcolumn','secondcolumn', 'thirdcolumn']) </code></pre> <p>Edit: You can add the timestamps in their own column, but the unpacking process is a little more complicated:...
python|pandas|dataframe|dictionary
4
12,039
53,036,990
Writing data to a SQL Server
<p>So I am trying to write a data frame to Microsoft SQL Server using the pandas <code>to_sql</code> function.</p> <p>I have created an engine using </p> <pre><code>engine = sqlalchemy.create_engine( 'mssql:///Server/Database?driver=SQL Server Native Client 11.0' ) con = engine.connect() switchers.to_sql('check',...
<p>Your connection string should be:</p> <pre><code>engine = sqlalchemy.create_engine('mssql+pyodbc://Server/Database?driver=SQL+Server+Native+Client+11.0') </code></pre>
python|sql|sql-server|pandas|sql-server-2016
0
12,040
65,886,711
Considering name with space (country name) as multiple columns when reading txt file
<p>I am trying to load the text file into Python, but due to the spaces in the string with multiple words, it is considering each word as a separate column. What's wrong, and how can I fix this?</p> <p>Data:</p> <pre><code>Name 2000–12 2012–13 2013–14 2012 2012 2012 2012 2012 2012 2012 Costa Rica 4.7 3.4 4.3 15.9 15.1 ...
<p>The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">Pandas <code>read_csv</code> function</a> accepts a custom delimiter <code>sep</code> which can be a regular expression. Now the task is to articulate a regex which only matches the last <em>n</em>...
python|pandas|csv|text|space
0
12,041
21,281,463
Appending to a DataFrame converts dtypes
<p>I am appending to a pandas.DataFrame, and the dtype of a column is converted in an unexpected way:</p> <pre><code>import pandas as pd df=pd.DataFrame({'a':1.0, 'b':'x'}, index=[0]) print df.dtypes df = df.append({'a':3.0}, ignore_index=True) print df.dtypes df = df.append({'a':3.0, 'b':'x'}, ignore_index=True) prin...
<p>Try this, convert the dict object to DataFrame first:</p> <pre><code>import pandas as pd df=pd.DataFrame({'a':1.0, 'b':'x'}, index=[0]) print df.dtypes df = df.append({'a':3.0}, ignore_index=True) print df.dtypes df = df.append(pd.DataFrame([{'a':3.0, 'b':'x'}]), ignore_index=True) print df.dtypes </code></pre> <p...
python|pandas
7
12,042
63,514,200
Pandas groupby and rolling window
<p>I`m trying to calculate the sum of one field for a specific period of time, after grouping function is applied.</p> <p>My dataset look like this:</p> <pre><code>Date Company Country Sold 01.01.2020 A BE 1 02.01.2020 A BE 0 03.01.2020 A BE 1...
<p>You can use a <code>.rolling</code> window of <code>8</code> and then subtract the sum of the Date (for each grouped row) to effectively get the previous 7 days. For this sample data, we should also pass <code>min_periods=1</code> (otherwise you will get <code>NaN</code> values, but for your actual dataset, you will...
pandas|dataframe|pandas-groupby
3
12,043
63,598,685
IndexError: index out of bound (Pandas)
<p>***I'm getting a error on Pandas please help</p> <pre><code>df.reset_index(drop=True) ind = list(df[df['BasePay'] == 0.0].index) df.drop(df.index[ind]) </code></pre> <p>And the error output is -</p> <pre><code>--------------------------------------------------------------------------- IndexError ...
<p>If I understand correctly you are trying to drop rows where 'BasePay' column is 0.0. You can simply do this using <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="nofollow noreferrer">boolean indexing</a> in order to keep the rows you want like this:</p> <pre><code>newDF = df[df['...
python|pandas
1
12,044
63,661,130
How can I remove \xa0$ from my dataframe?
<p>I am trying to clean my data which contains by making the columns[1:] float types.</p> <pre><code>for col_i in new_col_titles[1:]: df[col_i] = df[col_i].astype(float) </code></pre> <p>However, I get the following error.</p> <pre><code>ValueError: could not convert string to float: '\xa0$ 25,507,036' </code></pre...
<p>I solved it in a multistep process, Im sure someone can clean this up a little but for anyone else who is stuck by this:</p> <pre><code> for col_i in new_col_titles: df[col_i] = df[col_i].astype(str) df[col_i] = df[col_i].str.replace('\xa0', '', regex=True) df[col_i] = df[col_i].str.replace...
python|pandas|replace
0
12,045
21,435,482
Calculate increase between periods or rows
<p>I have one Dataframe like this:</p> <pre><code>year quarter value 2000 Q1 10 2000 Q2 12 2000 Q3 13 2000 Q4 13 2001 Q1 14 2001 Q2 15 2001 Q3 16 2001 Q4 12 </code></pre> <p>I would like to calculate the difference between the same q...
<p>You can pass the number of periods to difference to <code>DataFrame.diff</code></p> <pre><code>In [18]: df['value'].diff(4) Out[18]: 0 NaN 1 NaN 2 NaN 3 NaN 4 4 5 3 6 3 7 -1 Name: value, dtype: float64 </code></pre> <p>I would also recommend combining the year and quarter columns into a sin...
python|pandas
1
12,046
30,068,271
Python get get average of neighbours in matrix with na value
<p>I have very large matrix, so dont want to sum by going through each row and column.</p> <pre><code>a = [[1,2,3],[3,4,5],[5,6,7]] def neighbors(i,j,a): return [a[i][j-1], a[i][(j+1)%len(a[0])], a[i-1][j], a[(i+1)%len(a)][j]] [[np.mean(neighbors(i,j,a)) for j in range(len(a[0]))] for i in range(len(a))] </code></...
<h2>Shot #1</h2> <p>This assumes you are looking to get sliding windowed average values in an input array with a window of <code>3 x 3</code> and considering only the north-west-east-south neighborhood elements.</p> <p>For such a case, <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.signal.c...
python|numpy|matrix
6
12,047
53,727,464
Interpolate pandas missing datetime64 values
<p>I'm using Pandas 0.23.4 with Python 3.7.1.</p> <p>I've been gathering ICMP ping replies and want to analyse them with pandas. </p> <p>The input file contains data like:</p> <pre><code>13:27:19.651425 64 bytes from 1.1.1.1: icmp_seq=26 ttl=57 time=15.643 ms 13:27:20.652464 64 bytes from 1.1.1.1: icmp_seq=27 ttl=57...
<p>The interpolation methods expect real numbers, not <code>datetime</code> objects. You need to convert your numbers to floats. Do this by subtracting off the smallest timestamp so that you have enough precision to store your numbers. Interpolate and add the offset back.</p> <pre><code>import pandas as pd t0 = df.ti...
python|pandas|dataframe
3
12,048
53,356,253
Accessing an array by using another array of indexes in numpy
<p>I have an array A of shape [10, 10, 10].</p> <p>Now I want to access that array by using another array B of shape [10, 10, 10, 3] which contains indexes. </p> <p>As the output I want to get an array C of shape [10, 10, 10]. So each index in B is "replaced" by the corresponding value in A.</p> <p>Unfortunately I c...
<p>Here are two ways to do what you want. The first uses loops, and the second doesn't. The second is faster by a factor of about 10. </p> <p><strong>soltuion 1</strong> - loops</p> <pre><code>import numpy as np a = np.random.normal(0,1,(10,10,10)) # original array b = np.random.randint(0,10, (10,10,10,3)) # array o...
python|arrays|python-3.x|numpy
1
12,049
19,961,088
Finding minimum value element-wise in three 2d submatrices
<p>I'm trying to produce a color mapping of the convergence of a polynomial's roots in complex space. In order to do this, I have created a grid of points and applied Newton's method to those points, in order to find to which complex root they each converge. This gives me a 2d array of complex numbers, the elements of...
<p>You can pass an <code>axis</code> argument to <code>argmin</code>. You want to minimize along the first axis (what you're calling 'submatrices'), which is <code>axis=0</code>:</p> <pre><code>dist.argmin(0) dist = array([[[ 6.00e-15, 7.00e-15, 5.00e-01], [ 1.50e+00, 5.00e-15, 5.00e-01], ...
python|numpy|minimum
3
12,050
71,869,547
How to rename a column while merging in pandas
<p>I am using a for loop to merge many different dataframes. Each dataframe contains values from a specific time period. As such the column in each df is named &quot;balance&quot;. In order to avoid creating multiple balance_x, balance_y... I want to name the columns using the name of the df.</p> <p>so far, I have the ...
<p>I assume <code>topaccount_*</code> is a dataframe. I'm a bit confused in <code>top = top.rename(columns={'balance': i})</code> because what do you want to achieve here? <code>rename</code> function used to rename column given key as original column name and value as the renamed column name. but instead of giving a s...
python|pandas
1
12,051
71,835,907
I am building a Tensorflow graph using Tensorflow-rs and cant get individual Operations from ops::split
<p>I'm trying to complete this function:</p> <pre><code>///Split layers take in a single layer and splits it into a vector of layers. Since all tensors are two dimensional, ///we can split with a single usize on axis=0. fn split&lt;O1: Into&lt;Output&gt;&gt;( input: O1, num_splits: usize, scope: &amp;mut Sc...
<p>The shorthand functions are currently broken, I have raised issues as Ive encountered them but I solved with the following:</p> <pre><code>let axis_zero = ops::constant(0, scope)?; let split_operation = ops::Split::new() .num_split(num_splits) .build(axis_one.clone(), input.0, scope)?; </code></...
c++|tensorflow|rust
0
12,052
71,959,374
Pandas: How to convert series with an integer/fraction mix into a whole number
<p>So I'm iterating thru Excel columns containing numbers and I'm trying to round all the numbers using .apply(pd.to_numeric).round()</p> <p>This has always worked for me but recently, some of the Excel files contain columns with numbers mixed with fractions (e.g. 27 3/8, 50 17/32). When my script runs, I get &quot;Un...
<p>Here is one approach using <a href="https://docs.python.org/3/library/fractions.html" rel="nofollow noreferrer"><code>fractions.Fraction</code></a>:</p> <pre><code>from fractions import Fraction df2 = df['Qty'].str.extract(r'(\d+(?:\.\d+)?)?\s*(\d+/\d+)?') out = (pd.to_numeric(df2[0], errors='coerce') +df2[1]...
python|pandas|numpy
1
12,053
4,495,420
Passing Numpy arrays to C code wrapped with Cython
<p>I have a small bit of existing C code that I want to wrap using Cython. I want to be able to set up a number of numpy arrays, and then pass those arrays as arguments to the C code whose functions take standard c arrays (1d and 2d). I'm a little stuck in terms of figuring out how to write the proper .pyx code to prop...
<p>You probably want Cython's "typed memoryviews" feature, which you can read about in full gory detail <a href="http://docs.cython.org/src/userguide/memoryviews.html" rel="nofollow">here</a>. This is basically the newer, more unified way to work with numpy or other arrays. These can be exposed in Python-land as num...
arrays|numpy|cython
4
12,054
55,459,866
How to use columns in a dataframe to create rows in a new dataframe?
<p>I have a dataframe and want to create a new dataframe using some columns to create rows. </p> <p>Here is my dataframe:</p> <pre><code>import pandas as pd df=pd.DataFrame(columns=["TeamNumber", "C", "C1", "W", "W1", "W2","D","D1","G", "UTIL", "DATE", "TOP" ]) df=df.append({"TeamNumber": 1, "C": "PAUL", "C1": "BOB",...
<p>Check <code>DataFrame.melt()</code> in Pandas </p> <pre><code>df.melt(id_vars=['TOP','DATE' ,'TeamNumber'])[['TOP','DATE','TeamNumber','value']] </code></pre>
python|pandas|dataframe
3
12,055
55,511,941
How to remove special characters
<p>I have copied text "Revisions Analysis Dataset – Infra-annual Economic Indicators" from <a href="https://stats.oecd.org/Index.aspx?DataSetCode=MEI_ARCHIVE" rel="nofollow noreferrer">https://stats.oecd.org/Index.aspx?DataSetCode=MEI_ARCHIVE</a> and Exported to CSV file, but its showing some invalid characters "–" i...
<p>Sometimes <code>utf-8</code> not working for all types of encoding.</p> <p>Try below approaches:</p> <ol> <li><code>encoding=utf-8-sig</code></li> <li><code>encoding=utf-16</code></li> </ol>
python|python-3.x|pandas|dataframe
2
12,056
9,721,193
Manipulating indices to 2d numpy array
<p>I can index a 2d numpy array with a tuple or even a list of tuples</p> <pre><code>a = numpy.array([[1,2],[3,4]]) i = [(0,1),(1,0)] # edit: bad example, should have taken [(0,1),(0,1)] print a[i[0]], a[i] </code></pre> <p>(Gives <code>2 [2 3]</code>)</p> <p>However, I can not manipulate the tuples with vector arit...
<p>Yes. Convert the NumPy array to a tuple when you need to index:</p> <pre><code>a[tuple(k)] </code></pre> <p>Test:</p> <pre><code>&gt;&gt;&gt; a = numpy.array([[1,2],[3,4]]) &gt;&gt;&gt; i = numpy.array([(0,1),(1,0)]) &gt;&gt;&gt; k = i[0] + i[1] &gt;&gt;&gt; a[tuple(k)] 4 </code></pre>
python|numpy|indexing|multidimensional-array
2
12,057
7,489,956
Equivalent of named tuple in NumPy?
<p>Is it possible to create a NumPy object that behaves very much like a collections.namedtuple, in the sense that elements can be accessed like so:</p> <pre><code>data[1] = 42 data['start date'] = '2011-09-20' # Slight generalization of what is possible with a namedtuple </code></pre> <p>I tried to use a complex da...
<p>This is nicely implemented by "Series" in the <a href="http://pandas.sourceforge.net/index.html" rel="nofollow">Pandas</a> package.</p> <p>For example from the <a href="http://pandas.sourceforge.net/dsintro.html#series" rel="nofollow">tutorial</a>:</p> <pre><code>&gt;&gt;&gt; from pandas import * &gt;&gt;&gt; impo...
python|collections|numpy|namedtuple
3
12,058
56,849,900
How to deploy tensorflow model on spark to do inference only
<p>I want to deploy a big model, e.g. bert, on spark to do inference since I don't have enough GPUs. Now I have two problems.</p> <ol> <li>I export the model to be pb format and load the model using the SavedModelBundle interface.</li> </ol> <pre><code>SavedModelBundle bundle=SavedModelBundle.load(&quot;E:\\pb\\1561992...
<p>You could use Elephas (<a href="https://github.com/maxpumperla/elephas" rel="nofollow noreferrer">https://github.com/maxpumperla/elephas</a>), which enables distributed training and inference of Keras models on Spark. Since you mentioned it's a Tensorflow model, this may require a conversion (detailed here: <a href=...
java|apache-spark|tensorflow|hdfs|serving
-1
12,059
56,532,542
dataframe missing the header, after restricting original structure with pandas
<p>python 3.7.2. in pycharm/jupyter I was loading an excel sheet to a dataframe with the common pandas/read_excel this part worked perfectly. The headed is in the first line both in the excel file and also the loaded df. After wanted to create a secondary table out of it, by applying filters (including only the first 2...
<p>You are specifically asking it not to return the column names when you call <code>.values</code> in your line <code>df.iloc[].values</code></p> <p>If you want the same info with the column names, try <code>Z = df.iloc[:20 , 6:26]</code></p>
python|pandas
1
12,060
56,583,169
I have a mixed integer-string column: how can I change only the string?
<p>I have a dataframe with a column called <code>Text</code>. The rows of this column are all in the following format:</p> <pre><code>xxx - some sentence </code></pre> <p>where <code>xxx</code> is a random number. An example of what I have is:</p> <pre><code> Text 100 - Hello World 200 - Bye World 300 - Good W...
<h3><code>regex=True</code></h3> <pre><code>mapping = {"Hello World": "Bonjour Le Monde"} df.replace({"Text":mapping}, regex=True) Text 0 100 - Bonjour Le Monde 1 200 - Bye World 2 300 - Good World </code></pre>
python|string|pandas|dataframe|replace
1
12,061
25,593,594
Install scipy and numpy on Win 64 machine (python 2.7)
<p><em>I know there have been questions similar to this one before - I read them all and tried what they suggested</em></p> <p>Hi, I'm trying to install the scipy and numpy modules on my win 64 machine so I could call them from my IDE of choice. Alas, all my efforts were in vein. Here's what I tried:</p> <p><strong>1...
<p>I recommend using <a href="http://winpython.sourceforge.net/" rel="nofollow">Winpython</a> or <a href="https://code.google.com/p/pythonxy/" rel="nofollow">Python (x,y)</a>. These distributions provide full functionality for your purpose, have all neccessary packages precompiled (I you install them via pip, you need ...
python|python-2.7|numpy|scipy
0
12,062
25,938,309
Python Pandas: Changing One column based on another dynamically
<p>I have the following array:</p> <pre><code>Key, Value Up, a Up, b Up, b_regen Up, c_regen Down, a Down, b Down, b_regen Down, c </code></pre> <p>Where Value == *_regen change Key to (key)_regen *being wildcard</p> <p>Output would be:</p> <pre><code>Up, a Up, b Up_regen, b_regen Up_regen, c_regen Down, a Down, b...
<p>If you have a <code>DataFrame</code> like this:</p> <pre><code>a = pandas.DataFrame([['Up', 'a'], ['Up', 'a_regen'], ['Down', 'b_regen']], columns=['key', 'value']) &gt;&gt;&gt; a key value 0 Up a 1 Up a_regen 2 Down b_regen </code></pre> <p>You can create a function that determines if the v...
python|pandas
2
12,063
26,386,848
Pandas - How can I make every value within a column NaN?
<p>I want to clear all the data from a column within my dataframe but keep the dataframe exactly the same. </p> <p>The Excel equivalent of this would be to select all the data in a column beneath the header and right-click "Clear Contents". </p> <p>I tried this:</p> <pre><code>test = df.replace(to_replace=df('Column...
<p>Just do <code>df['Column Name'] = NaN</code>, <a href="http://www.youtube.com/watch?v=Hl545RF6dXA" rel="nofollow">simples</a></p>
python|pandas|dataframe
2
12,064
66,783,542
Why a.storage() is b.storage() returns false when a and b reference the same data?
<pre><code>&gt;&gt;&gt; a = torch.arange(12).reshape(2, 6) &gt;&gt;&gt; a tensor([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11]]) &gt;&gt;&gt; b = a[1:, :] &gt;&gt;&gt; b.storage() is a.storage() False </code></pre> <p>But</p> <pre><code>&gt;&gt;&gt; b[0, 0] = 999 &gt;&gt;&gt; b, a # both tensors are chang...
<p><code>torch.Tensor.storage()</code> returns a new instance of <a href="https://pytorch.org/docs/stable/storage.html" rel="nofollow noreferrer"><code>torch.Storage</code></a> on every invocation. You can see this in the following</p> <pre class="lang-py prettyprint-override"><code>a.storage() is a.storage() # False <...
python|pytorch|tensor
4
12,065
66,890,839
Count maximum value in each group with Pandas
<p>Suppose I have a dataframe <code>df</code> looking like</p> <pre><code> school score student_id 0 1 100.0 965 1 2 64.0 1483 2 2 100.0 1055 3 2 68.0 1806 4 1 100.0 971 </code></pre> <p>I want to find how many maximum scores in each group and get so...
<p>Assuming <code>count_max</code> means that the <code>score</code> column equals <code>100</code>, you can do:</p> <pre><code>df.loc[df.score==100, 'max_score'] = True df.max_score.fillna(False, inplace=True) df.groupby('school')['max_score'].sum() </code></pre>
python|pandas
0
12,066
68,410,040
Saving dict generated by pandas read_excel to multi-sheet excel file
<p>Pandas' <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html?highlight=read_excel" rel="nofollow noreferrer">read_excel()</a> method when called with <code>sheet_name=None</code> will return a dict with each excel sheet. How can I reverse this operation, i.e. take a dict and sav...
<p>I would say that generally this operation is performed using <code>pandas.ExcelWriter</code> (suppose df_dict is your dictionary with DataFrames):</p> <pre><code>import pandas as pd with pd.ExcelWriter('path/to/save/table.xlsx') as writer: for key, df in df_dict.items(): df.to_excel(writer, key) wri...
python|pandas
3
12,067
59,397,394
Python Pandas replace NaN in one column with value from another column of the same row it has be as list column
<p>Input dataframe</p> <pre><code>data = { 'id' :[70,70,1148,557,557,104,581,69], 'r_id' : [[70,34, 44, 23, 11, 71], [70, 53, 33, 73, 41], np.nan, np.nan, np.nan, np.nan,np.nan,[69, 68, 7],] } df = pd.DataFrame.from_dict(data) print (df) id r_id 0 70 [70, 34, 44, 23, 11, 71] ...
<p>We can use <code>list_comprehension</code> + <code>Series.fillna</code>.</p> <p>First we create a list with all the <code>id</code> values converted to <code>list</code> type. Then we replace <code>NaN</code> here by our list values:</p> <pre><code>df['temp'] = [[x] for x in df['id']] df['r_id'] = df['r_id'].filln...
python|pandas|dataframe
2
12,068
59,091,979
generating colored image with fixed colors out of a 2D array of integers
<p>Segmentation output gives me a 2D array with each pixel having a unique integer value corresponding to a class. I want to create a coloured image from this array with fixed colours for every class. Please help. If I just stack up the 2D array to create 3 channel image, the image is only different shades of grey for ...
<p>You can check the following code and modify according to your need:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt arr = np.array([[2,6,8,9], [1,2,7,8], [4,5,1,7]]) # this may be your array unique_values = set(np.unique(arr).tolist()) # getting unique classes colors = [plt.cm.Spectral(each) for ...
python|image|numpy|python-imaging-library|mask
0
12,069
59,259,935
getting rows that belong to hour range in pandas datetimeindex
<p>Minimal reproducible code:</p> <pre><code>import pandas as pd from datetime import datetime import numpy as np date_rng = pd.date_range(start='1/1/2018', end='1/08/2018', freq='H') df = pd.DataFrame(date_rng, columns=['date']) df['data'] = np.random.randint(0,100,size=(len(date_rng))) df.set_index("date", inplace=...
<p>You can simply use <code>between_time</code>:</p> <pre><code>print (df.between_time("06:00","12:00")) # data date 2018-01-01 06:00:00 51 2018-01-01 07:00:00 61 2018-01-01 08:00:00 37 2018-01-01 09:00:00 77 2018-01-01 10:00:00 7 2018-01-01 11:00:00 59 20...
python|pandas
2
12,070
59,364,298
Adding total row to a pandas DataFrame with tuples inside
<p>Here is my <a href="https://stackoverflow.com/questions/59326903/adding-total-row-to-pandas-dataframe-groupby">previous question</a> (that has been answered). It helped me for my initial problem but now I am stuck on another one.</p> <p>I have this below <code>pandas.DataFrame</code> which I try to add total rows f...
<p>Use:</p> <pre><code>#s=df.groupby(['Level', 'Company', 'Item'])['Value'].sum() def GetTupleSum(x): return tuple(sum(y) for y in zip(*x.dropna())) df= s.unstack('Item') df['total']=df.apply(GetTupleSum,axis=1) ( df.unstack() .assign(total_company=df['total'].groupby(level=0).apply(GetTupleSum) ) .stack...
python-3.x|pandas|group-by|pivot-table
1
12,071
45,242,347
Import Excel with bad characters to Python
<p>I have ~300 .xls files that I need to import to Python. I've tried xlrd and pandas read_excel and both fail the import with "Unsupported format, or corrupt file: Expected BOF record; found '="XS1351'.</p> <p>Roughly half the columns on each sheet have quotes and leading equalsign ="THISFORMAT"</p> <p>The other ha...
<p>I know it's not the solution you're looking for, but you could go to CSV first, then import to Python. <a href="https://stackoverflow.com/questions/1858195/convert-xls-to-csv-on-command-line">Here is a way to convert quickly.</a> I have also tried to import .xls files to great frustration and ended up manually openi...
python|excel|pandas|xls|xlrd
1
12,072
45,246,811
Python: binned_statistic_2d mean calculation ignoring NaNs in data
<p>I am using <code>scipy.stats.binned_statistic_2d</code> to bin irregular data onto a uniform grid by finding the mean of points within every bin.</p> <pre><code>x,y = np.meshgrid(sort(np.random.uniform(0,1,100)),sort(np.random.uniform(0,1,100))) z = np.sin(x*y) statistic, xedges, yedges, binnumber = sp.stats.binne...
<p>I had the same problem and changed the definition of binned_statistic_dd in scipy.stats and saved a local copy so that it won't be changed if scipy is updated.</p> <p>I added 'nanmean' to the list of known_stats and</p> <pre><code>elif statistic == 'nanmean': result.fill(np.nan) for i in np.unique(binnumbers...
python|numpy|nan|binning
2
12,073
45,237,703
android tensorflow ExtractImagePatches Op not found
<p>I am trying to run inference with tensorflow android on a <a href="https://github.com/thtrieu/darkflow" rel="nofollow noreferrer">darkflow</a> yolo model. I could successfully ran on the default tiny-yolo-voc model, but when I change my model (and it's parameters accordingly) to the yolo one, I get the following exc...
<p>Add the implementation to the build</p> <p>If you’re using Bazel, you’ll want to add the files you’ve found to the android_extended_ops_group1 or android_extended_ops_group2 targets. You may also need to include any .cc files they depend on in there. If the build complains about missing header files, add the .h’s t...
android|tensorflow|build|inference|darkflow
1
12,074
45,002,525
What happend after data augmentation done?
<p>I use Kaggle's "Dogs Vs cats" <a href="https://www.kaggle.com/c/dogs-vs-cats/data" rel="nofollow noreferrer">date set</a>, and follow the TensorFlow 's cifar-10 tutorial (I did not use weight decay, moving average and L2 loss for convenient), I have trained my network successful, but when I added the data augmentat...
<p>Make sure the limits you use (e.g. <code>max_delta=63</code> for brightness, <code>upper=1.8</code> for contrast) are low enough so that an image is still recognizable. One of other problems can be that augmentation is applied over and over again, so after a few iterations it's completely distorted (though I didn't ...
python|machine-learning|tensorflow|deep-learning
0
12,075
57,274,421
How to pre-cache dask.dataframe to all workers and partitions to reduce communication need
<p>It’s sometimes appealing to use <code>dask.dataframe.map_partitions</code> for operations like merges. In some scenarios, when doing merges between a <code>left_df</code> and a <code>right_df</code> using <code>map_partitions</code>, I’d like to essentially pre-cache <code>right_df</code> before executing the merge ...
<p>If you do any of the following then things should be ok:</p> <ul> <li>A merge with a single-partition dask dataframe</li> <li>A merge with a non-dask dataframe (like Pandas or cuDF)</li> <li>A map_partitions with a non-dask dataframe (like Pandas or cuDF)</li> </ul> <p>What happens is this:</p> <ol> <li>The singl...
python|pandas|dask|rapids|cudf
1
12,076
56,936,068
Python check dtype of array - float or complex
<p>How can I check that a numpy array if of float or complex dtype? For simple examples the following checks all work fine.</p> <pre><code># these are True a = np.zeros(10) a.dtype == float a.dtype == np.float a.dtype == np.float64 b = np.zeros(10,dtype=complex) b.dtype == complex b.dtype == np.complex b.dtype == np....
<p>Did you try <code>numpy.isrealobj()</code> and <code>np.iscomplexobj()</code>?</p> <p>Your examples:</p> <pre><code>import numpy as np a = np.zeros(10) print(np.isrealobj(a)) # -&gt; True print(np.iscomplexobj(a)) # -&gt; False b = np.zeros(10,dtype=complex) print(np.isrealobj(b)) # -&gt; False print(np.iscomple...
python|arrays|numpy|types
6
12,077
45,927,590
Pandas SQL equivalent for 'not equal' clause
<p>I do not see this in the SQL comparison documentation for Pandas. What would be the equivalent of this SQL in Pandas? </p> <pre><code>select a.var1, a.var2, b.var1, b.var2 from tablea a, tableb b where a.var1=b.var1 and a.var2=b.var2 and a.var3 &lt;&gt; b.var3 </code></pre> <p>I have the merge code as follows:</p...
<p>You can query the resulting frame:</p> <pre><code>a.merge(b, on=['VAR1','VAR2']).query('VAR3_x != VAR3_y') </code></pre>
python|sql|pandas
12
12,078
45,775,494
Extending a numpy.matrix gives __new__ and __class__ issues?
<p>I wanted to quickly write a Points class, where each column of the underlying 2D <code>numpy.matrix</code> is assigned to an attribute such that I can write stuff like this easily:</p> <pre class="lang-py prettyprint-override"><code>points = Points(np.mat(np.ones((2,3))), names=["a","b","c"]) points.a = poi...
<p>This works for me, with <code>numpy.version.full_version == '1.8.0'</code> in Python 3.5.1:</p> <pre><code>import numpy class Points(numpy.matrixlib.defmatrix.matrix): def __new__(subtype, data, names=[], **kwargs): tmp = super(Point, subtype).__new__(subtype, data, **kwargs) for i, name in zi...
python|numpy
0
12,079
23,261,233
finding the difference in years for two common values in a column
<p>I'm using pandas and I'm trying to find the difference in years when my data is grouped by labels and then by teams. i've tried to use a groupby for the problem that I'm dealing with but I can't quite get my desired result. here is the head(8) of my df</p> <pre><code>Team Year labels Hawks ...
<p>Not sure if <code>label</code> for the last row is supposed to be 'a' or 'b'. From your data snippet:</p> <pre><code>Hawks 2003 a </code></pre> <p>From you expected output:</p> <pre><code>Hawks 2003 b 2 </code></pre> <p>I'll assume <code>label</code> is supposed to be 'b' so ...
pandas|group-by
0
12,080
35,347,285
Calculating time range with timedelta & Boolean
<p>I need help doing a timedelta function to determine if the <code>actn_dt</code> is greater than or equal to 1 year ago and if it is, return experienced.</p> <p>dataframe <code>f2</code> looks like this:</p> <pre><code> nm_emp_lst actn_dt 14483 MACKENZIE 2015-03-22 132902 CAMPBELL 2...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a> - second row in <code>df</code> was changed for testing:</p> <pre><code>print df nm_emp_lst actn_dt 14483 MACKENZIE 2015-03-22 132902 CAMPBELL 2018-04-19 124182 S...
python|numpy|pandas|dataframe|timedelta
1
12,081
35,756,952
Quickly compute eigenvectors for each element of an array in python
<p>I want to compute eigenvectors for an array of data (in my actual case, i cloud of polygons)</p> <p>To do so i wrote this function:</p> <pre><code>import numpy as np def eigen(data): eigenvectors = [] eigenvalues = [] for d in data: # compute covariance for each triangle cov = np.cov...
<p><strong>Hack It!</strong></p> <p>Well I hacked into <a href="https://github.com/numpy/numpy/blob/v1.10.1/numpy/lib/function_base.py#L1891" rel="nofollow"><code>covariance func definition</code></a> and put in the stated input states : <code>ddof=0, rowvar=False</code> and as it turns out, everything reduces to just...
python|performance|numpy|scipy|vectorization
4
12,082
35,457,879
Evaluation of loss with session.run([]) in TensorFlow
<p>For simple gradient descent, I am using this :</p> <p><code>_, l, predictions = session.run([optimizer, loss, train_prediction])</code> where optimizer op minimizes loss. </p> <p>But I am feeding loss after optimizer, so will the loss, be evaluated two times at each .run(), one using initial weight, and then usin...
<p>The order of elements in the list of fetched tensors doesn't matter (except for capturing the values on the Python side). They will all be executed during the same evaluation.</p> <p>In your example, the loss will be evaluated only once and any computations that can be shared between the <code>[optimizer, loss, tra...
tensorflow
4
12,083
35,420,242
initialize matrix with vectors Python
<p>I want to initialize a Matrix with 3 vectors. The special part about is that I want the vectors to be the columns the matrix. </p> <pre><code>Vx= np.zeros((npoints,)) Vy=np.zeros((npoints,)) Vz=np.zeros((npoints,)) V=np.matrix(([Vx,Vy,Vz])) </code></pre> <p>Now the problem here is that the vectors form the rows of...
<p>You could use <code>np.column_stack</code>:</p> <pre><code>V = np.column_stack([Vx, Vy, Vz]) </code></pre>
python|numpy|matrix
1
12,084
11,956,458
How to write in python numpy: b = sum(v) - a as an implicitly elementwise (vector) computation?
<p>I'll start with a statement of the problem. Afterward I will demonstrate a brief sequence of coding which progressively builds the solution until the problem is reached. Obviously, here the goal is to compute b. I am asking how to do it most efficiently, ideally using an elementwise numpy vector expression, with no...
<p>For the particular view <code>v</code> you posted, the computation can be expressed as a <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html#numpy-convolve" rel="nofollow">convolution</a> with the kernel <code>[1, 1, 1]</code>:</p> <pre><code>In [78]: import numpy as np In [80]: a ...
python|vector|numpy
2
12,085
50,856,449
Get area between pixel wise masks and WSI patches
<p>So basically I have a WSI (Whole slide image) which looks like this:</p> <p><a href="https://i.stack.imgur.com/hgCn6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hgCn6.jpg" alt="enter image description here"></a></p> <p>And I have a png mask which looks like this:</p> <p><a href="https://i.s...
<p>You could apply the following algorithm:</p> <ul> <li><p>For each patch <code>(x, y, width, height)</code> in the WSI, compute its coordinates relative to the mask position: <code>(x2, y2, width2, height2)</code>. There are some calculations to do here with <code>min</code> and <code>max</code> but nothing impossib...
python|numpy|opencv|pillow
1
12,086
50,866,850
Ask user to continue viewing the next 5 lines of data
<p>I am trying to get the next 5 data rows without writing a loop every time ([:5], [5:10], [10:15],etc...). I have some idea but I been stuck on this one for awhile, what are some ways to go about this to get the user to show the next 5?</p> <pre><code>def raw_data(df): ask_user = input('Would you like to view more r...
<p>Add a variable that accumulates each time the function runs. (Let's call it <code>runs</code>) Initialize it outside of the function and add one to it inside of the function. From here, multiply it by 5 to get your range.</p> <pre><code>runs = 0 def raw_data(df): while True: ask_user = input('Would you...
python|pandas
3
12,087
50,872,972
Interpolation in Pandas horizontally independent to each rows
<p>I have a dataframe like this </p> <pre><code>ID,Time0,Sum0,Average0,Time1,Sum1,Average1 1,1520320347531.0,59.3635,18.2828,1520324772351.0,59.5031,18.4745 1,1519860442638.0,60.1159,20.3027,1519861181524.0,60.1033,20.31705 </code></pre> <p>And I want to interpolate horizontally in every 5 mins. </p> <p>this code in...
<p>I have an answer but it's a bit ugly, to anyone seing overmanipulation of the data, feel free to correct it. </p> <p>First, from your data, I change the value <code>1520324772351.0</code> (first row, column Time1) to <code>1520321086417.0</code>, otherwise it's way more than 10 minutes and make the example with to ...
python|pandas|resampling
1
12,088
50,868,589
Python try to use .map()
<p>I am learning Machine Learning and trying to write a code from myself using the Iris Dataset.</p> <p>I open the dataset with pandas and then I am trying to pass a dictionary in my dataset to convert the last column from Strings into Int but when try this:</p> <pre><code>dataset.columns = ['sepal length', 'sepal wi...
<p>Finally I managed to solve this problem. Instead of using for loop, I used this:</p> <p>    <code>dataset ['class'] = dataset ['class']. map (class_mapping)</code></p> <p>I didn't need a for loop because <code>.map</code> iterates for me.</p>
python|pandas|dictionary|dataset|indices
0
12,089
33,292,944
Calculation between groups in a Pandas multiindex dataframe
<p>Suppose I generate a multi-index data frame as follows:</p> <pre><code>arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']), np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])] df = pd.DataFrame(np.random.randn(8, 4), index=arrays) 0 1 ...
<p>With different random numbers. Use a <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="nofollow">transform</a>:</p> <pre><code>In [11]: df.groupby(level=0)[3].transform(lambda x: x[0]/ x[1]) Out[11]: bar one -1.391651 two -1.391651 baz one -1.688734 two -1.68...
python|pandas
4
12,090
33,404,492
Filtering Pandas Dataframe Aggregate
<p>I have a pandas dataframe that I groupby, and then perform an aggregate calculation to get the mean for:</p> <pre><code>grouped = df.groupby(['year_month', 'company']) means = grouped.agg({'size':['mean']}) </code></pre> <p>Which gives me a dataframe back, but I can't seem to filter it to the specific company and ...
<p>The issue is that you are grouping based on <code>'year_month'</code> and <code>'company'</code> . Hence in the <code>means</code> DataFrame, <code>year_month</code> and <code>company</code> would be part of the index (MutliIndex). You cannot access them as you access other columns.</p> <p>One method to do this wou...
python|pandas
2
12,091
66,714,059
Calculate Decile with condition
<p>I am looking to create a 'decile' column based on client attributes (type of account). I can get a decile for the entire dataset using <code>qcut</code> function:</p> <pre><code>df['Decile_rank'] = pd.qcut(df['bps_impact'], 10, labels = False) </code></pre> <p>But I cannot add the filter by client attribute.</p> <p>...
<p>Simple case of <code>groupby()</code> <code>apply()</code></p> <pre><code>df = pd.DataFrame({&quot;client&quot;:np.repeat([&quot;A&quot;,&quot;B&quot;,&quot;C&quot;],10),&quot;val&quot;:np.random.randint(10,100,30)}) df[&quot;quantile&quot;] = df.groupby(&quot;client&quot;, as_index=False).apply(lambda dfa: pd.qcut...
python|pandas|numpy
0
12,092
66,567,227
Populate new column added from check between columns from different Dataframes
<p>I am trying to add a new column to a dataframe (<strong>df_pgthsim</strong>) containing the values from another column in another dataframe (<strong>df_bn</strong>) only if the value itself it is contained at the beginning of the string in the first dataframe. If not, then it should insert False value (or '', Null, ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.startswith.html" rel="nofollow noreferrer"><code>DataFrame.str.startswith</code></a></p> <pre><code>df_pgthsim['is_brand'] = df_pgthsim['bn'].str.startswith('bn') </code></pre> <p>This will create a column <code>is_brand</code>...
python|pandas|dataframe
0
12,093
66,366,580
Need to figure out overlapping when I have a panda dataframe of start and end
<p>Example: panda dataframe is,</p> <pre><code> start end 0. 10 20 1. 30 40 2. 50 60 3. 25 35 4. 70 80 </code></pre> <p>need to create a list,</p> <pre><code>ovrlap = [false, true, false, true, false] </code></pre> <p>as idx 1 and 3 are overlapping so in the list also in those 2 idx are true.</p> <ul> ...
<p>I'm using this code:</p> <pre><code>def overlapDetect(arr): res = [False for i in range(len(arr))] arr_srt = sorted(arr, key=lambda l:l[0]) for i in range(len(arr_srt) - 1): cur_s, cur_e = arr_srt[i] nxt_s, nxt_e = arr_srt[i+1] if nxt_s &lt;= cur_e &lt;= nxt_e: cur_idx...
python|pandas|algorithm|dataframe
0
12,094
66,715,081
Numpy array of numpy arrays
<p>When I create a numy array of a list of sublists of equal length, it implicitly converts it to a <code>(len(list), len(sub_list))</code> 2d array:</p> <pre><code>&gt;&gt;&gt; np.array([[1,2], [1,2]],dtype=object).shape (2, 2) </code></pre> <p>But when I pass variable length sublists it creates a vector of length <co...
<p>You can create an array of objects of the desired size, and then set the elements like so:</p> <pre class="lang-py prettyprint-override"><code>elements = [np.array([1,2]), np.array([1,2])] arr = np.empty(len(elements), dtype='object') arr[:] = elements </code></pre> <p>But if you try to cast to an array directly wi...
python|python-3.x|numpy|vector
1
12,095
16,301,546
Swapping Axes in Pandas
<p>What is the most efficient way to swap the axes of a Pandas Dataframe?</p> <p>For example, how could df1 be converted to df2 below?</p> <pre><code>In [2]: import pandas as pd In [3]: df1 = pd.DataFrame({'one' : [1., 2., 3., 4.], 'two' : [4., 3., 2., 1.]}) In [4]: df1 Out[4]: one two 0 1 4 1 2 3 ...
<p>Take a look at <a href="http://pandas-docs.github.io/pandas-docs-travis/generated/pandas.DataFrame.transpose.html?highlight=transpose#pandas.DataFrame.transpose" rel="nofollow noreferrer">transpose</a></p> <pre><code>In [4]: df1.T Out[4]: 0 1 2 3 one 1 2 3 4 two 4 3 2 1 </code></pre>
python|indexing|pandas|swap
31
12,096
57,633,680
Pandas: grouping by a slice of a string
<p>I have a large data set that I'm working on, it has about 6000 rows and couple hundred columns. I have managed to get most of the information sorted out as I need, but now I've gotten stuck since i can't manage to correctly group by a slice of a string.</p> <p>The original data is in the form:</p> <pre><code>6001 ...
<p>You can use the <code>str</code> attribute:</p> <pre><code>grouped_data = data_drill.groupby([data_drill['PeriodStartDate'].str[:9], 'Blast']) ['Calc_DRILLING_Holes'].sum() </code></pre> <p>This assumes that your indexing will work for all your dates. </p> <p>Alternatively, conve...
python|pandas
2
12,097
57,558,892
Pandas Pivot and Un Pivoting a table
<p>Given dataframe, df:</p> <pre><code>df = pd.DataFrame({'Store_ID': [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], 'Week_ID': [1,1,1,1,1,1,1, 2,2,2,2,2,2,2, 3,3,3,3,3,3,3], 'Day': ['Mo','Tu','We','Th','Fr','Sa','Su','Mo','Tu','We','Th','Fr','Sa','Su','Mo','Tu','We','Th','Fr','Sa','Su'], ...
<p>You can try this:</p> <pre><code>df_out = df.set_index(['Store_ID','Week_ID','Day']).unstack(-1) df_out.columns = [f'Day_{j}_{i}' for i, j in df_out.columns] df_out </code></pre> <p>Output:</p> <pre><code> Day_Fr_Manager Day_Mo_Manager Day_Sa_Manager Day_Su_Manager \ Store_ID Week_ID ...
python|pandas|dataframe
5
12,098
57,672,751
Filter a dataframe by a given condition
<p>So i have a dataframe that i wrote to a csv file that looks like this</p> <pre><code>Atrasos,Data 18,2019-08-24 22,2019-08-25 52,2019-09-21 31,2019-09-22 </code></pre> <p>When the last day of the atual month is reached i want to filter that dataframe to grab the values since the first day of the actual month to th...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.month.html" rel="nofollow noreferrer"><code>Series.dt.month</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></...
python-3.x|pandas
1
12,099
57,476,760
How to correct the output generated through str.contains in python
<p>I just have a column "methods_discussed" in CSV (link is <a href="https://github.com/pandas-dev/pandas/files/3496001/multiple_responses.zip" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/files/3496001/multiple_responses.zip</a>) file having values name of family plaaning methods like:</p> <pre><cod...
<p>Use words boundary around patterns - <code>\b\b</code> for avoid it, also parameter <code>na=False</code> is nice for avoid <code>NaN</code>s in output - here replaced by <code>False</code>:</p> <pre><code>for method in method_names: df1[method]=df1["methods_discussed"].str.contains(pat = r"\b{}\b".format(metho...
python|pandas
2