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
9,600
65,696,566
Pandas merge in a function
<p>I am trying to use pandas merge in a function as shown below.</p> <p>Here is what I am trying to use :</p> <pre><code>test = inv_level(left, right, 'user_id', 'new_id', 'left') #left.merge(right, on='user_id', how='left') </code></pre> <p>where inv_level is a function as defined below</p> <pre><code>def inv_level (...
<p>There are not swapped <code>parent_inv</code> and <code>child_inv</code>, so in your solution was tested column <code>new_id</code> in <code>left</code> instead <code>right</code>:</p> <pre><code>#swapped DataFrames def inv_level (parent_inv, child_inv, lefton, righton, how ): </code></pre>
python|pandas
0
9,601
65,872,965
How to get unique lists in a Pandas column of lists
<p>I have the following DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame({'name': [&quot;John&quot;, &quot;Jack&quot;, &quot;Jeff&quot;, &quot;Kate&quot;], &quot;hobbies&quot;:[[&quot;pirates&quot;], [&quot;pirates&quot;], [&quot;climbing&quot;, &quot;yoga&quot;], [&quot;yoga&quot;]]}) # name hobbies #...
<p>Let us change the <code>list</code> to <code>tuple</code> so we can do <code>drop_duplicates</code></p> <pre><code>out = df.hobbies.apply(tuple).drop_duplicates().apply(list).tolist() Out[143]: [['pirates'], ['climbing', 'yoga'], ['yoga']] </code></pre> <p>If you do not need converting back to <code>list</code>, you...
python|pandas
3
9,602
63,455,052
Redshift where clause using multiple columns
<p>Suppose I have the following table in <strong>redshift</strong>:</p> <pre><code>table | a | b | |----:|----:| | 3 | 1 | | 1 | 8 | | 7 | 6 | | 4 | 0 | | 5 | 6 | | 5 | 2 | | 5 | 9 | | 4 | 3 | | 7 | 9 | | 9 | 8 | </code></pre> <p>And in python, I have the following list of tu...
<p>We can use <code>.stack</code> with <code>isin</code> and <code>.loc</code> to filter along the index:</p> <pre><code>x = [(3,1), (4,2), (10, 1), (7,9), (5,2), (6,1)] df.loc[df.stack().groupby(level=0).agg(tuple).isin(x)] a b 1 3 1 6 5 2 9 7 9 </code></pre>
python|pandas|amazon-redshift
1
9,603
63,419,344
How to insert an elements from vector into matrix based on array of random indexes
<p>Basicly, im trying to insert an elements from vector into matrix based on random index</p> <pre><code>size = 100000 answer_count = 4 num_range = int(1e4) a = torch.randint(-num_range, num_range, size=(size, )) b = torch.randint(-num_range, num_range, size=(size, )) answers = torch.randint(-num_range, num_range, siz...
<p>I think you need to change the last line like this:</p> <pre><code>answers[np.arange(size), pos] = c </code></pre> <p>The problem lies in incorrect use of advanced indexing. To understand the difference of those indexing try printing out <code>answers[:, pos]</code> vs. <code>answers[np.arange(size), pos]</code> and...
python|arrays|numpy|torch
0
9,604
63,460,217
Assign labels: all values are false
<p>I have some problem to assign label whether a condition is satisfied. Specifically, I would like to assign False (or 0) to rows which contains at least one of these words</p> <pre><code>my_list=[&quot;maths&quot;, &quot;science&quot;, &quot;geography&quot;, &quot;statistics&quot;] </code></pre> <p>in one of these fi...
<ul> <li>The final values in <code>Labels</code> are Booleans <ul> <li>If you want <code>ints</code>, use <code>df.Label = df.Label.astype(int)</code></li> </ul> </li> <li><code>def test_words</code> <ul> <li>fill all <code>NaN</code>s, which are <code>float</code> type, with <code>''</code>, which is <code>str</code> ...
python|pandas
-1
9,605
55,401,003
Is there a way to apply a condition to a regex in pandas?
<p>I'm filtering a column in pandas but want to keep certain values.</p> <p>My goal is to change the values all players that aren't Federer, Nadal and Djokovic to "Other" so</p> <p>Before:</p> <pre><code>winner_name Federer Nadal Djokovic Kyrgios Hewitt </code></pre> <p>After:</p> <pre><code>...
<p><code>np.where</code> and <code>isin</code> are enough here:</p> <pre><code>df['winner_name'] = np.where(df['winner_name'].isin(['Federer', 'Nadal', 'Djokovic']), df['winner_name'], 'Other') </code></pre>
python|pandas
2
9,606
55,300,601
Python numpy reshape
<p>I have a variable of z storing features of length and height of image files where z is</p> <pre><code>z = [length, height] </code></pre> <p>and i want to change these dimension to just:</p> <pre><code>z = [area] where area = length * height </code></pre> <p>I tried using the numpy reshape function as follow:</p>...
<p>Simple example of how to use reshape:</p> <pre><code>import numpy as np a = np.random.randint(0,10,(10,10)) b = np.reshape(a, (100,)) print(b) </code></pre> <p>For your case it will be:</p> <pre><code>print(a.shape) # prints (length,height) b = np.reshape(a, (length * height,)) print(b.shape) # prints (length ...
python|numpy
1
9,607
56,482,227
Split sentences into substrings containing varying number of words using pandas
<p>My question is related to this past of question of mine: <a href="https://stackoverflow.com/q/56395681/9024698">Split text in cells and create additional rows for the tokens</a>.</p> <p>Let's suppose that I have the following in a <code>DataFrame</code> in <code>pandas</code>:</p> <pre><code>id text 1 I am the ...
<p>Define a function to extract chunks in a random fashion using <code>itertools.islice</code>:</p> <pre><code>from itertools import islice import random lo, hi = 3, 5 # change this to whatever def extract_chunks(it): chunks = [] while True: chunk = list(islice(it, random.choice(range(lo, hi+1)))) ...
python|string|pandas|tokenize
2
9,608
67,142,969
How to insert an array into another one using slices
<p>I want to create a large <code>NumPy array</code> (<code>L</code>) to hold the result of some operations. However, I can only compute one part of <code>L</code> at a time. Then, to have <code>L</code>, I need to create an array of zeros of shape <code>L.shape</code>, and fill it using these parts or subarrays. I'm c...
<p>Your example is not very clear, but maybe you can adapt something from this code snippet. It looks to me like you are generating your L array, shape (x, y, z, a, b, c), by computing <code>a</code> slices, of shape (x, y, z, b, c), equivalent to (x, y, z, 1, b, c). Let me know if I am completely wrong.</p> <pre><code...
python|arrays|pandas|numpy
0
9,609
47,404,102
How I reuse trained model in DNN?
<p>Everyone!</p> <p>I have a question releate in trained model reusing( tensorflow ).</p> <p>I have train model</p> <p>I want predict new data used trained model.</p> <p>I use DNNClassifier.</p> <p>I have a model.ckpt-200000.meta, model.ckpt-200000.index, checkpoint, and eval folder.</p> <p>but I don't know reuse...
<p>First, you need to import your graph,</p> <pre><code>with tf.Session() as sess: sess.run(tf.global_variables_initializer()) new_saver = tf.train.import_meta_graph('model.ckpt-200000.meta') new_saver.restore(sess, tf.train.latest_checkpoint('./')) </code></pre> <p>Then you can give input to the graph and get ...
tensorflow
0
9,610
68,328,242
Split rows to create new rows in Pandas Dataframe
<p>I have a pandas dataframe in which one column of text strings contains multiple comma-separated values. I want to split each field and create a new row per entry only where the number of commas is equal to 2. My entire dataframe has only values with either no. of commas =1 or 2. For example, a should become b:</p> <...
<ul> <li>have taken the approach that you want <strong>combinations</strong> of constituent parts</li> <li>specifically there is a <strong>combination</strong> you want to exclude</li> <li>have used an additional column just for purpose of transparency of solution</li> </ul> <pre><code>import io import itertools df = ...
python-3.x|pandas|dataframe|python-2.7|split
1
9,611
68,191,705
Convert tuple to int - python
<p>I have the following table ( df):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>shape</th> <th>data</th> </tr> </thead> <tbody> <tr> <td>POLYGON</td> <td>((1280 16068.18, 1294 16059, 1297 16060, 1300 16063, 1303 16065, 1308 16066))</td> </tr> <tr> <td>POINT</td> <td>POINT ((37916311947...
<p>The first part of your code seems fine - In the second part you are probably trying to split <code>i</code> instead of <code>j</code></p> <pre><code>x = '1280 16068.18, 1294 16059, 1297 16060, 1300 16063, 1303 16065, 1308 16066' x_split = [tuple(map(lambda x: int(float(x)), i.strip().split())) for i in x.strip().spl...
python|pandas|string|integer|parentheses
1
9,612
59,367,908
Sum the values of certain rows to another nearest row based on condition
<p>I have the dataframe as below</p> <pre><code>id log loc pos_evnts neg_evnts As non_As pos_wrds neg_wrds As/Ac A c City 8 0 48 0 0 0 1 A d City 2 6 0 180 4 10 0 A e City 0 22 ...
<p>moys, with some help from jezrael, i finished up my solution, i was missing two lines that i've added below</p> <pre><code>df['Truth'] = df['As/Ac'] == 0 | ( (df['As/Ac'].shift() == 0) &amp; (df['As/Ac'] == 1) ) df['T'] = df['Truth'].ne(df['Truth'].shift()).cumsum() # from jezrael cols = df.select_dtypes(np.numbe...
python|python-3.x|pandas|pandas-groupby
2
9,613
57,284,345
How to install nvidia apex on Google Colab
<p>what I did is follow the instruction on the official github site</p> <pre><code>!git clone https://github.com/NVIDIA/apex !cd apex !pip install -v --no-cache-dir ./ </code></pre> <p>it gives me the error:</p> <pre><code>ERROR: Directory './' is not installable. Neither 'setup.py' nor 'pyproject.toml' found. Excep...
<p>Worked for me after adding CUDA_HOME enviroment variable:</p> <pre><code>%%writefile setup.sh export CUDA_HOME=/usr/local/cuda-10.1 git clone https://github.com/NVIDIA/apex pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./apex </code></pre> <pre><code>!sh setup.sh </code></...
python|gpu|pytorch|nvidia|google-colaboratory
18
9,614
57,007,490
How to find which values of a dataframe 'significantly' differ from a specific mean
<p>I am creating a Pandas DataFrame where one column is the temperature at half hourly intervals for the year. </p> <blockquote> <p>I want to create a column which on each row contains the mean value for that month at that time. </p> </blockquote> <p>For example, in the row containing the value: "13:00:00 2018-02-...
<p>I think you can use pandas' <code>groupby()</code> method to achieve what you want (instead of the for loops).</p> <p>Here is the code:</p> <pre><code>means = df_train.groupby(['Month', 'Time']).Temp.mean() df_train.set_index(['Month', 'Time'], inplace=True) df_train['Mean'] = means df_train.reset_index(inplace=Tr...
python|pandas
1
9,615
45,976,111
How can i use Seaborn.lmplot function without naming DataFrame columns?
<p>I want to use <strong><em>Seaborn.lmplot</em></strong> for scattering Dataframe's <strong>"column 1"</strong> vs <strong>"column 2"</strong> , but in according to Seaborn documentation :</p> <blockquote> <p>Seaborn.lmplot(x, y, data, hue=None, ...)</p> </blockquote> <p>We should provide names of columns for usin...
<p>Seaborn does not allows for unnamed columns.<br> However, an easy solution is to rename the columns just for the purpose of plotting. Mapping the integer to a string (<code>lambda x: str(x)</code>) would allow to use strings as column names for the seaborn plot.</p> <pre><code>sns.lmplot(x="0", y="1", data=df.renam...
python|pandas|dataframe|seaborn
5
9,616
51,080,169
Tensorflow: JRE Fatal error (SIGILL (0x4)) at loading _clustering_ops.so
<p>Created a test java application which loads a trained python model through Tensorflow.</p> <p>Had to add the below line to fix this exception "Op type not registered 'NearestNeighbors' in binary"</p> <pre><code>TensorFlow.loadLibrary(/tmp/path/to/_clustering_ops.so); </code></pre> <p>My application runs with no i...
<blockquote> <p>I am suspecting this is an issue with the server. However cannot figure out what it is</p> </blockquote> <p>The issue very likely is similar to <a href="https://stackoverflow.com/a/50980619/50617">this one</a>.</p> <p>Your development machine and your server have different processors with different ...
tensorflow|gdb
0
9,617
66,711,884
vectorized quadratic formula, why is the runtime warning invalid value in numpy.sqrt() still raised?
<p>numpy version 1.20.1</p> <p>Bob lawblaw's Law Blog, I need more details, this post has tooooo much code.</p> <pre><code>def quadratic_formula(a, b, c): &quot;&quot;&quot;just like the song Args: a (numpy.ndarray): shape(N,1) b (numpy.ndarray): shape(N,1) c (numpy.ndarray): shape(N,1)...
<p>Note that you are still computing <code>np.sqrt(det)</code> for all values of <code>det</code> hence the warning. The where filters the x and y arrays <em>after</em> they have been computed.</p> <p>The implementation can be fixed by simply casting the a,b and c arrays to complex.</p> <pre><code> a = np.array(a).a...
python|numpy
1
9,618
57,511,783
How to group by value for certain time period
<p>I had a DataFrame like below:</p> <pre><code> Item Date Count a 6/1/2018 1 b 6/1/2018 2 c 6/1/2018 3 a 12/1/2018 3 b 12/1/2018 4 c 12/1/2018 1 a 1/1/2019 2 b 1/1/2019 3 c 1/1/2019 2 </code></pre> <p>I would like to get the sum of ...
<p>We can use <code>query</code> with <code>Series.between</code> and chain that with <code>GroupBy.sum</code>:</p> <pre><code>df.query('Date.between("07-01-2018", "06-01-2019")').groupby('Item')['Count'].sum() </code></pre> <p><strong>Output</strong></p> <pre><code>Item a 5 b 7 c 3 Name: Count, dtype: int6...
python-3.x|pandas
1
9,619
51,264,932
How to properly make an assignment to a slice of a multiindexed dataframe in pandas?
<p>I am running Pandas 0.20.3 with Python 3.5.3 on macOS.</p> <p>I have a multiindexed dataframe similar to the following <code>df</code>:</p> <pre><code>import pandas as pd import numpy as np refs = ['A', 'B'] dates = pd.date_range(start='2018-01-01', end='2018-12-31') df = pd.DataFrame({'ref': np.repeat(refs, len...
<p>I think need chain 2 boolean masks with select values of levels of <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_level_values.html" rel="nofollow noreferrer"><code>get_level_values</code></a>:</p> <pre><code>m1 = df.index.get_level_values(0) == 'A' m2 = d...
python|pandas|dataframe
1
9,620
51,536,771
pandas left join on column with list values
<p>Giving this two Data samples, I would like to join by a column that in the left join dataframe the value is a list of one element of several and in the other dataframe is the same colum (primary key) with aditional information without list as format. </p> <p>with this example</p> <pre><code>df1 = pd.DataFrame({'ID...
<p>You should convert your Ouput[2] to a map (a pandas series), e.g.:</p> <pre><code>df2.ID = df2.ID.apply(lambda x: x[0]) s2 = df2.set_index('ID')['ALT_NAME'] # let us rename it s2 as it is a series now! </code></pre> <p>When that is done you can simply use apply and fetch the values with a list comprehension:</p> ...
python|pandas
3
9,621
70,966,698
How to access the channel dimensions of a tensor
<p>I have an output of tensor shape [32,24,24,6] i.e [batch_size,height,width,channel dimension] . I want to access the channel dimension values and work on it, maybe get it as a tuple or list of tensors which i plan to use in the elems of tf.map_fn. I tried using indexing([-1, -1, -1, 0:6]) but i am not sure if it is...
<p>You can use the keras backend, which also works in graph mode. Here an example:</p> <pre><code>import tensorflow as tf testTensor = tf.random.uniform(shape = (32,128,128,3)) shape = tf.keras.backend.int_shape(testTensor) # (32,128,128,3) </code></pre>
python|numpy|tensorflow
0
9,622
37,530,228
How do I add an arbitrary value to a TensorFlow summary?
<p>In order to log a simple value <code>val</code> to a TensorBoard summary I need to</p> <pre><code>val = 5 test_writer.add_summary(sess.run(tf.scalar_summary('test', val)), global_step) </code></pre> <p>Is </p> <pre><code>sess.run(tf.scalar_summary('test', val)) </code></pre> <p>really necessary to get <code>val<...
<p>Here's another (perhaps slightly more up-to-date) solution with the tf.Summary.FileWriter class:</p> <pre><code>summary_writer = tf.summary.FileWriter(logdir=output_dir) value = tf.Summary.Value(tag='variable name', simple_value=value) summary_writer.add_event(summary=tf.summary.Event(tf.Summary([value]), ...
logging|tensorflow|tensorboard
12
9,623
42,108,321
Doing Pandas properly... rather than using a loop
<p>I'm just getting started with Pandas and I'm finding it hard to treat dataframes like dataframes. Every now and again, I just can't work out how to do something without iterating through rows.</p> <p>For example, I've got a dataframe with budget info. I want to extract the 'vendor' from the 'short description', whi...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>str.split</code></a> by <code>to</code> or <code>at</code> and then select last value of list by <code>str[-1]</code>:</p> <p>I implemented this <a href="https://stackover...
python|pandas|dataframe
3
9,624
37,736,730
Pandas GroupBy Two Text Columns And Return The Max Rows Based On Counts
<p>I'm trying to figure out the max <code>(First_Word, Group)</code> pairs </p> <pre><code>import pandas as pd df = pd.DataFrame({'First_Word': ['apple', 'apple', 'orange', 'apple', 'pear'], 'Group': ['apple bins', 'apple trees', 'orange juice', 'apple trees', 'pear tree'], 'Text': ['where to bu...
<p>Given <code>grouped</code>, you now want to group by the <code>First Word</code> index level, and find the index labels of the maximum row for each group (using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html" rel="nofollow"><code>idxmax</code></a>):</p> <pre><code>In [39...
python|pandas|max
3
9,625
38,054,160
pandas wont add columns in order
<p>I have two data frames </p> <p>numbers:</p> <pre><code>Unnamed: 0 Name Number 42 42 Aberavon 1742 43 43 Aberconwy 2769 16 16 Aberdeen North 3253 25 25 Aberdeen South 4122 355 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow"><code>values</code></a> for converting column <code>Number</code> to <code>numpy array</code>, so align is corrected:</p> <pre><code>numbers['No. Voters] = electorate['Number'].values </code></pre> ...
python|numpy|pandas|multiple-columns
1
9,626
37,781,319
plot N planes parallel to XZ axis in 3D in python
<p>I want to plot N planes (say 10) parallel to XZ axis and equidistant to each other using python. If possible it would be nice to select the number of planes from user. It will be like, if user gives "20" then 20 planes will be drawn in 3D. This is what I did.But I would like to know is there a method to call each pl...
<p>Here is an example how to implement what you need in a very generic way.</p> <pre><code>from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt from matplotlib import cm from pylab import meshgrid,linspace,zeros,dot,norm,cross,vstack,array,matrix,sqrt def rotmatrix(axis,costheta): """ Calcula...
python|python-2.7|numpy|matplotlib
4
9,627
64,502,496
how to specify to use pandas .replace() instead of str.replace() when defining a function?
<p>I want to filter out certain words from a pandas dataframe column and make a new column of the filtered text. I attempted the solution from <a href="https://stackoverflow.com/questions/48684774/how-to-delete-words-from-a-dataframe-column-that-are-present-in-dictionary-in-pa">here</a>, but I think im having the issue...
<p>From this line:</p> <pre><code>txt.replace(rf&quot;\b({'|'.join(words)})\b&quot;, '', regex=True) </code></pre> <p>This is the signature for <code>pd.Series.replace</code> so your function takes a series as input. On the other hand,</p> <pre><code>df['old_text'].apply(removeWords) </code></pre> <p>applies the functi...
python|regex|pandas
2
9,628
64,499,856
WASM backend for tensorflowjs throws "Unhandled Rejection (RuntimeError): index out of bounds" error in Reactjs
<p>I am trying to set up a WASM back-end for blazeface face detection model in a react app. Although the demo with the vanillajs can run it without any error for hours, in react it throws &quot;Unhandled Rejection (RuntimeError): index out of bounds error&quot; after leaving the cam open for more than 3-5 minutes.</p> ...
<p>After using a tensor to make predictions you will need to free the tensor up from the devices memory otherwise it will build up and the cause a potential error you are having. This can simply be done using <code>tf.dispose()</code> to manually specify the place at which you want to dispose the tensors. You do it rig...
javascript|reactjs|webassembly|tensorflow.js
2
9,629
47,646,312
group all directly and indirectly related records using python pandas
<p>thanks in advance:</p> <p>I am trying to generate a group identifier in a many to many relationship table which has 2 columns defining IDs of parent entities and a child entities:</p> <p>Example dataframe below: (parent (p), and child (c))</p> <pre><code>df = pd.DataFrame(np.array([[1,7],[1,3],[1,4],[3,2],[5,1],[...
<p>You can check <a href="https://networkx.github.io/documentation/networkx-1.10/index.html" rel="nofollow noreferrer"><code>networkx</code></a> </p> <pre><code>import networkx as nx G=nx.from_pandas_dataframe(df, 'c', 'p') l=list(nx.connected_components(G)) dfmap=pd.DataFrame.from_dict(l) dfmap.index=['B','A'] dfmap...
python|pandas|many-to-many|relationship
4
9,630
47,778,162
Python/Numpy have I already written the swiftest code for large array?
<p> <strong>GOAL:</strong> I have a large 1d array (3000000+) of distances with many duplicate distances. I am trying to write the swiftest function that returns all distances that appear n times in the array. I have written a function in numpy but there is a bottleneck at one line in the code. Swift performance is an ...
<p>Use <code>np.unique</code> :</p> <pre><code>a=np.random.randint(0,10**6,3*10**6) uniques,counts=np.unique(a,return_counts=True) In [293]: uniques[counts==14] Out[293]: array([ 4541, 250510, 622471, 665409, 881697, 920586]) </code></pre> <p>This takes less than a second. but I don't understand why your <code>where...
python|numpy
3
9,631
49,061,441
Adding 100 2D Arrays of different sizes (numpy)
<p>Is it possible to add two different sized arrays without broadcasting?</p> <p>To my knowledge, broadcasting adds values to the smaller array in order to fill that space. But that would skew my results. I was wondering if there was some way to add two different sized arrays without having to compromise the values?</...
<p>Try this:</p> <pre><code>P + np.pad(L, (0,1), 'constant', constant_values=0) </code></pre> <p>So:</p> <pre><code>&gt;&gt;&gt; P array([[1, 2, 3], [2, 1, 6], [7, 9, 1]]) &gt;&gt;&gt; np.pad(L, (0,1), 'constant', constant_values=0) array([[1, 2, 0], [4, 1, 0], [0, 0, 0]]) &gt;&gt;&gt; P ...
python|arrays|numpy
0
9,632
59,000,621
Pandas iloc() to identify specific columns from headers row?
<p>I'm trying to create a list of the column headers excluding the initial columns. I am trying to use Pandas' iloc function for this and I feel I am halfway there.</p> <pre><code>column_dates = list(pronto.iloc[[0][2:]]) print(column_dates) </code></pre> <p>Right now, this is returning </p> <pre><code>['Unwanted Va...
<p>if the names of the columns have been properly parsed, then you want</p> <pre><code>pronto.columns[2:] </code></pre> <p>if the names of your columns are appearing in your dataframe as the first row (which they shouldn't), this should work</p> <pre><code>pronto.iloc[0, 2:] </code></pre>
python|pandas
1
9,633
70,227,908
Iterating over rows in a dataframe in Pandas: is there a difference between using df.index and df.iterrows() as iterators?
<p>When iterating through rows in a dataframe in Pandas, is there a difference in performance between using:</p> <pre><code>for index in df.index: .... </code></pre> <p>And:</p> <pre><code>for index, row in df.iterrows(): .... </code></pre> <p>? Which one should be preferred?</p>
<p>Pandas is significantly faster for column-wise operations so consider transposing your dataset and carrying out whatever operation you want. If you absolutely need to iterate through rows and want to keep it simple, you can use</p> <pre><code>for row in df.itertuples(): print(row.column_1) </code></pre> <p><code...
python|pandas|dataframe
2
9,634
70,097,166
how do i change the format in python
<p>i have a table like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">grade</th> <th style="text-align: center;">name</th> <th style="text-align: center;">price</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">1</td> <td style="text-align: c...
<p>To get your output, your input should be:</p> <pre><code>&gt;&gt;&gt; df grade name price # your grade column 0 1 abc 25 # 1 1 2 abc 30 # 1 2 3 abc 35 # 1 3 1 mno 55 # 2 4 2 mno 60 # 2 5 3 mno 65 # 2 6 1 xyz 40 # 3 7 2 xy...
python|pandas|dataframe
1
9,635
70,252,159
AttributeError: 'Functional' object has no attribute 'predict_segmentation' When importing TensorFlow model Keras
<p>I have successfully trained a Keras model like:</p> <pre><code>import tensorflow as tf from keras_segmentation.models.unet import vgg_unet # initaite the model model = vgg_unet(n_classes=50, input_height=512, input_width=608) # Train model.train( train_images=train_images, train_annotations=train_annotatio...
<p><code>predict_segmentation</code> isn't a function available in normal Keras models. It looks like it was added after the model was created in the <a href="https://github.com/divamgupta/image-segmentation-keras/blob/dc830bbd76371aaedbf8cb997bdedca388c544c4/keras_segmentation/models/model_utils.py#L101" rel="nofollow...
python|tensorflow|keras|deep-learning
2
9,636
70,153,833
Dimensional Error for text classification using conv2d layer in keras
<p>I have a dataframe which I split into train and test set and the input shape for the train set is (4115,588). Now I want to create a neural network with Conv2D layers but face this error when I pass in the input shape arguement. ValueError: Input 0 of layer sequential_8 is incompatible with the layer: : expected min...
<p>Conv2D expects input of shape, 4+D tensor with shape: <code>batch_shape + (channels, rows, cols)</code> if data_format='channels_first' or 4+D tensor with shape: <code>batch_shape + (rows, cols, channels)</code> if data_format='channels_last'.</p> <p>I tested your code with mnist dataset its working. <strong>Working...
python|tensorflow|keras
0
9,637
70,059,059
Finding the distance (Haversine) between all elements in a single dataframe
<p>I currently have a dataframe which includes five columns as seen below. I group the elements of the original dataframe such that they are within a 100km x 100km grid. For each grid element, I need to determine whether there is at least one set of points which are 100m away from each other. In order to do this, I am ...
<ol> <li><p>Convert all points to carthesian coordinates to have much easier task (distance of 100m is small enough to disregard that Earth is not flat)</p> </li> <li><p>Divide each grid into NxN subgrids (20x20, 100x100? check what is faster), for each point determine in which subgrid it is located. Determine distance...
python|pandas|numpy|performance
0
9,638
56,069,564
how to draw outlines of objects on an image to a separate image
<p>i am working on a puzzle, my final task here is to identify edge type of the puzzle piece.</p> <p><a href="https://i.stack.imgur.com/n7wGa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n7wGa.png" alt="enter image description here"></a></p> <p>as shown in the above image i have mange to rotate ...
<p>First convert your color image to grayscale. Then apply a threshold, say zero to obtain a binary image. You may have to use morphological operations to further process the binary image if there are holes. Then find the contours of this image and draw them to a new image.</p> <p><a href="https://i.stack.imgur.com/8K...
python|image|numpy|opencv|matplotlib
2
9,639
56,055,359
Tensorflow Lite arm64 error: cannot convert ‘const int8x8_t?
<p>I tried building AARCH64 on ubuntu 16.04. I followed this guide(Native Compling) <a href="https://tensorflow.google.cn/lite/guide/build_arm64" rel="nofollow noreferrer">https://tensorflow.google.cn/lite/guide/build_arm64</a>.</p> <p>But I got this error. What is problem ? Also I want try example on Orange Pi 3. Ho...
<p>After trying to solve the problem for hours, I think i found a solution for this:</p> <p>Just add the "-flax-vector-conversions" parameter to the CXXFLAGS variable in the tensorflow/lite/tools/make/Makefile file.</p> <p>For me it was in line 58:</p> <pre><code>CXXFLAGS := -O3 -DNDEBUG -fPIC -flax-vector-conversio...
c++|c|tensorflow|artificial-intelligence|tensorflow-lite
2
9,640
56,128,642
How can I trasform a (1,16) array in a (1,16,1) array with np.newaxis?
<p>I want to trasform this array (1, 16) </p> <pre><code>[[4 4 4 4 4 4 4 4 4 4 4 4 0 0 0 0]] </code></pre> <p>in a (1,16,1) array. </p> <p>I tried: </p> <pre><code>board = board[np.newaxis, :] </code></pre> <p>but it is not the expeted output. </p> <p>How can i do that?</p>
<p>You have to put the <code>np.newaxis</code> on the location of the dimenstion where you want this new axis.</p> <pre><code>board[np.newaxis,:] -&gt; puts the axis in the first dimension [1,1,16] board[:,np.newaxis] -&gt; puts the axis in the second dimension [1,1,16] board[:,:,np.newaxis] -&gt; puts the axis in the...
python|arrays|numpy
3
9,641
56,178,968
Repeat rows in pandas data frame with a sequential change in a column value
<p>I want to repaet the rows in my df in a time sequence with forward filling.</p> <p>Original df:</p> <pre><code> A B C Year 0 ABC 0 A 1950 1 CDE 1 A 1950 2 XYZ 1 B 1954 3 123 1 C 1954 4 X12 1 B 1956 5 123 1 D 1956 6 124 1 D 1956 </code></pre> <p>Desired df:</p> <pre><cod...
<p>I feel like this is a <a href="https://stackoverflow.com/questions/53218931/how-to-unnest-explode-a-column-in-a-pandas-dataframe/53218939#53218939"><code>unnesting</code></a> problem </p> <pre><code>s=df.astype(str).groupby('Year').agg(list) s.index=s.index.astype(int) s1=s.reindex(np.arange(s.index.min(),s.index.m...
pandas
3
9,642
56,134,319
Convert the text string K & M to 10^3 & 10^6
<p>I have data frame with column values -</p> <pre><code>[Themangoescosts$1K] [needtopay20K,10Kdollarsmakesagrand] </code></pre> <p>I need to convert K - 10^3</p> <p>I am not sure how to use the regex option to replace the match value at its location for the list in data frame column</p> <p>Used the below regex to ...
<p>I suggest using </p> <pre><code>df['c'] = df['offer2'].str.replace(r'(?&lt;!\d)(\d{1,3})([KM])', lambda x: '{}000'.format(x.group(1)) if x.group(2) == 'K' else '{}000000'.format(x.group(1)) ) </code></pre> <p>The point is that you may use a callable as the replacement argument when using <code>Series.str.replace</...
python|regex|pandas
0
9,643
64,946,234
can not import numpy
<p>I have a problem with importing numpy. i did the reinstalling and also used the &quot;pip3 install numpy&quot; command but when i try to import it i face this problem:</p> <pre><code>&gt;&gt;&gt; import numpy Traceback (most recent call last): File &quot;&lt;pyshell#0&gt;&quot;, line 1, in &lt;module&gt; impor...
<p>There seems to be a problem with version 1.19.4. Just open a command prompt and run</p> <pre><code>pip install numpy==1.19.3 </code></pre>
python|numpy|import|pip
0
9,644
65,012,956
Is there a way to get the number of items I print as a result of a FOR cycle in Python?
<p>I have this code:</p> <pre><code>C = 50000 threshold = 0.3 for i in range(1, 18598): if binned_orcs[i] &gt; C and ori[i] &gt; threshold: Origins = print(i) </code></pre> <p>I would like to then have a way to know how many items that for cycle with those conditions printed but because every origin is printed on a...
<p>You could add a counter and track the number yourself:</p> <pre class="lang-py prettyprint-override"><code>count = 0 for i in range(1, 18598): if binned_orcs[i] &gt; C and ori[i] &gt; threshold: print(i) count += 1 print(count) </code></pre>
python|python-3.x|numpy|string-length
2
9,645
64,968,250
How to solve Runtime Error: Empty min/max for tensor Cast while doing post-training quantization (fully quantized tflite model from saved_model)?
<p>I try to create fully quantized tflite model to be able to run it on coral. I downloaded SSD MobileNet V2 FPNLite 640x640 from <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/res...
<p>I trained the same model, <code>SSD MobileNet V2 FPNLite 640x640</code>, using the script <code>model_main_tf2.py</code> and then exported the checkpoint to <code>saved_model</code> using the script <code>exporter_main_v2.py</code>. When trying to convert to &quot;.tflite&quot; for use on Edge TPU I was having the ...
python|tensorflow|tensorflow-lite|google-coral|edge-tpu
2
9,646
40,075,106
Replace values in pandas Series with dictionary
<p>I want to replace values in a pandas <code>Series</code> using a dictionary. I'm following @DSM's <a href="https://stackoverflow.com/questions/20250771/remap-values-in-pandas-column-with-a-dict">accepted answer</a> like so:</p> <pre><code>s = Series(['abc', 'abe', 'abg']) d = {'b': 'B'} s.replace(d) </code></pre> <p...
<p>You can do it using <code>regex=True</code> parameter:</p> <pre><code>In [37]: s.replace(d, regex=True) Out[37]: 0 aBc 1 aBe 2 aBg dtype: object </code></pre> <p>As you have already <a href="https://stackoverflow.com/questions/40075106/replace-values-in-pandas-series-with-dictionary/40075212#comment674236...
python|pandas|dictionary|replace
7
9,647
40,138,031
How to read realtime microphone audio volume in python and ffmpeg or similar
<p>I'm trying to read, in <em>near-realtime</em>, the volume coming from the audio of a USB microphone in Python. </p> <p>I have the pieces, but can't figure out how to put it together. </p> <p>If I already have a .wav file, I can pretty simply read it using <strong>wavefile</strong>:</p> <pre><code>from wavefile im...
<p>Thanks to @Matthias for the suggestion to use the sounddevice module. It's exactly what I need. </p> <p>For posterity, here is a working example that prints real-time audio levels to the shell: </p> <pre><code># Print out realtime audio volume as ascii bars import sounddevice as sd import numpy as np def print_s...
python|linux|numpy|audio|ffmpeg
38
9,648
39,582,754
Running a Python function on Spark Dataframe
<p>I have a python function which basically does some sampling from the original dataset and converts it into training_test. </p> <p>I have written that code to work on pandas data frame. </p> <p>I was wondering if anyone knows how to implement the same on Spark DAtaframe in pyspark?. Instead of Pandas data frame or ...
<p>You can use randomSplit function on Spark dataframe. </p> <pre><code>(train, test) = dataframe.randomSplit([0.8, 0.2]) </code></pre>
python|pandas|apache-spark
-1
9,649
39,481,516
Acquire the data from a row in a Pandas
<p>Instructions given by Professor: 1. Using the list of countries by continent from World Atlas data, load in the countries.csv file into a pandas DataFrame and name this data set as countries. 2. Using the data available on Gapminder, load in the Income per person (GDP/capita, PPP$ inflation-adjusted) as a pandas Dat...
<p>Pandas uses three types of indexing.</p> <p>If you are looking to use integer indexing, you will need to use <code>.iloc</code></p> <pre><code>df_1 Out[5]: consId fan-cnt 0 1155696024483 34.0 1 1155699007557 34.0 2 1155694005571 34.0 3 1155691016680 12.0 4 1155697016945 34.0 d...
python|pandas|matplotlib|dataframe|data-science
1
9,650
39,807,845
argmin in dataset containing NaN python
<pre><code> SGSIN VNVUT CNSHK HKHKG JPOSA To MYPKL 1 4 8 9 13 SGSIN NaN 3 7 8 12 VNVUT NaN NaN 3 4 8 CNSHK 1 NaN NaN 1 5 HKHKG NaN NaN NaN NaN 3 </code></pre> <p>Let say we have the above dataset using...
<p>You can use numpy's <code>argwhere</code></p> <pre><code>import numpy as np np.argwhere(df['SGSIN'].eq(df['SGSIN'].min())) array([[0], [3]]) </code></pre>
python|pandas|machine-learning
0
9,651
44,351,398
Grouping and numbering items in a pandas dataframe
<p>I want to add a column to a dataframe in python/pandas as follows:</p> <pre><code>| MarketID | SelectionID | Time | SelectNumber | | 112337406 | 3819251.0 | 13:38:32 | 4 | | 112337406 | 3819251.0 | 13:39:03 | 4 | | 112337406 | 4979206.0 | 11:29:34 | 1 | | 112337406 | ...
<p>First, you need the combinations of 'MarketID' and 'SelectionID' in order of occurrence, so lets sort on the time. Then, for each 'MarketID' get the unique 'SelectionID's and number them in order of occurrence (already ordered, because df is ordered on column time). Secondly, the combination of number 'MarketID' and...
python-3.x|pandas|dataframe
0
9,652
69,608,359
How to convert 6 first values in column to date based on some assumption in Python Pandas?
<p>I have Pandas Data Frame in Python like below:</p> <pre><code>VAL -------- 99050605188 00102255789 20042388956 02111505667 </code></pre> <p>Values are in str format.</p> <p>First 6 numbers means date, for example:</p> <ul> <li>99050605188 --&gt; 1999-05-06</li> <li>00102255789 --&gt; 2000-10-22</li> <li>20042388956 ...
<p>You can parse the first 6 characters of the string using the format, <code>%y%m%d</code> and then change the year as per your requirement.</p> <p><strong>Demo:</strong></p> <pre><code>from datetime import datetime import pandas as pd df = pd.DataFrame( {'val': ['99050605188', '00102255789', '20042388956', '0211...
python|pandas|string|dataframe|date
1
9,653
41,174,249
Looping through pandas data frame while changing row values using regex
<hr> <p><em>-EDIT-</em></p> <p>As Daniel Kasatchkow (below) suggested, I have attempted the following:</p> <pre><code>df._links.str.findall('qwer://abc\\\.x-data\\\.orc/v1/i/\d+/users') </code></pre> <p>But I get the following output:</p> <pre><code>0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN ... </code>...
<p>Try something like this</p> <pre><code>import pandas as pd df = pd.DataFrame(["{u'users': {u'href': u'qwer://abc\.x-data\.orc/v1/i/32/users'}, u'self': {u'href': ...","{u'users': {u'href': u'qwer://abc\.x-data\.orc/v1/i/87/users'}, u'self': {u'href': ..."], columns=['_links']) df._links.str.findall('qwer://abc\\\...
python|regex|python-2.7|pandas|for-loop
1
9,654
54,121,263
Speed issues with pandas and list comprehensions
<p>I have a dataset with 4m rows of data, and I split this into chunks using pd.read_csv(chunk size...) and then perform some simple data cleaning code to get it into a format I need.</p> <pre><code>tqdm.pandas() print("Merging addresses...") df_adds = chunk.progress_apply(merge_addresses, axis = 1) [(chunk.append(d...
<p>Calling <code>DataFrame.append</code> too frequently can be expensive (<a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html</a>):</p> <blockquote> <p>Iteratively a...
python|pandas|list-comprehension
2
9,655
38,256,180
How to make shared libraries with Bazel at Tensorflow
<p>I've tried building <a href="https://www.tensorflow.org/" rel="noreferrer">tensorflow</a> with <a href="http://www.bazel.io/" rel="noreferrer">bazel</a> as follows:</p> <blockquote> <p>bazel build -c opt --copt="-fPIC" --copt="-g0" //tensorflow/tools/pip_package:build_pip_package</p> </blockquote> <p>I couldn'...
<p><code>//tensorflow:libtensorflow.so</code> is the target you are looking for.</p> <pre><code>bazel build -c opt //tensorflow:libtensorflow.so </code></pre> <p>should produce the file in <code>bazel-bin/tensorflow</code>.</p>
shared-libraries|tensorflow|bazel
8
9,656
38,243,318
Get the string from the DataFrame column an assign to the other column in pandas
<p>I Have a input data frame with columns:</p> <pre><code>Template Template Name This is String This is String line This is Int This is Int Name This is String Name String Name is none Int is empty </code></pre> <p>Expected Output Dataframe:</p> <pre><code>Template Temp...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow"><code>extract</code></a>:</p> <pre><code>df['Template Name'] = df.Template.str.extract('(String|Int)', expand=False) print (df) Template Template Name 0 This is String ...
python|pandas
3
9,657
38,251,786
How to display out of range values on image histogram?
<p>I want to plot the RGB histograms of an image using <code>numpy.histogram</code>.</p> <p>(See my function <code>draw_histogram</code> below)</p> <p>It works well for a regular range of [0, 255] :</p> <pre><code>import numpy as np import matplotlib.pyplot as plt im = plt.imread('Bulbasaur.jpeg') draw_histogram(im...
<p>You should pass x values to 'plt.plot'</p> <p>I changed:</p> <pre><code>plt.plot(hist, color=col) </code></pre> <p>to this:</p> <pre><code>plt.plot(np.arange(minimum,maximum),hist, color=col) </code></pre> <p>With this change, the graph began to appear normally. Essentially, plt.plot was trying to start plottin...
python|numpy|image-processing|histogram|rgb
1
9,658
66,122,744
Pandas - get_loc nearest for whole column
<p>I have a df with date and price. Given a datetime, I would like to find the price at the nearest date.</p> <p>This works for one input datetime:</p> <pre><code>import requests, xlrd, openpyxl, datetime import pandas as pd file = &quot;E:/prices.csv&quot; #two columns: Timestamp (UNIX epoch), Price (int) df = pd.rea...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a> (cannot test, because no sample data):</p> <pre><code>df = df.sort_index('Timestamp') dfinput = dfinput.sort_values('Date') df = pd.merge_asof(df, dfinput...
pandas|dataframe
1
9,659
66,236,117
Does pandas index have advantage on performance than column?
<p>Till now, I used to put timestamps as the index for my time series dataframe. I felt that if I put the timestamps as the index, I might have performance gain when I search the data comparing to the search with the timestamps in a column. (It's kind of my feeling from the name, 'index'. I felt it might be indexed.) ...
<p>One answer is in terms of data frame size. I have a data frame with 50M rows</p> <pre><code>df_Usage.info() </code></pre> <p>output</p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 49991484 entries, 0 to 49991483 Data columns (total 7 columns): BILL_ACCOUNT_NBR int64 MM_ADJ_BILLING_YEAR...
python|pandas|indexing
1
9,660
52,776,332
Tensorflow-GPU without NVIDIA,possible?
<p>I don't have a NVIDIA graphics card, but I need to use tensorflow-gpu. Is this feasible? what should I do?</p>
<p>You can use Google's colab for free directly in your browser:</p> <blockquote> <p><a href="https://colab.research.google.com/notebooks/welcome.ipynb#recent=true" rel="nofollow noreferrer">https://colab.research.google.com/notebooks/welcome.ipynb#recent=true</a> <a href="https://colab.research.google.com/noteboo...
python|tensorflow|nvidia
2
9,661
58,530,051
How to relabel a Pandas Dataframe starting at 1 with RangeIndex when stop is not known?
<p>So I'm building software that takes large csv files of amino acid data and converts them to a pandas DataFrame. I need to relabel the columns 1-n. Is there a way to do this when the stop value is not known? I've tried the following: </p> <pre><code>df = pd.read_csv(file, encoding='utf-8', header=None) df.index = p...
<p>You are way overthinking it. Since you index started at 0 and you now want to change it to 1-based, simply add 1 to the index:</p> <pre><code>df.index += 1 </code></pre>
python|python-3.x|pandas|bioinformatics
0
9,662
58,470,330
Reassigning dataframe rows or variables with iloc returns NaN
<p>I have a "dataframe A" that is partially complete; some rows are missing data. The missing data can be found on rows in another "dataframe B" (with the same labels, but not position).</p> <p>When I try to reassign the rows of dataframe A, python returns NaN for all the rows I tried to reassign.</p> <p>I have trie...
<p>If you have the two pandas dataframe in the same shape then you can do something like this</p> <pre><code>dfA[dfA.isnull()] = dfB </code></pre> <p>If this solves your question, please accept the answer.</p>
python|pandas|dataframe|variable-assignment
0
9,663
58,357,525
df.loc - ValueError: Buffer has wrong number of dimensions (expected 1, got 0)
<p>I currently have the following code - I am trying to get a matching row in one dataframe based on the <code>Last Name</code> column.</p> <pre class="lang-py prettyprint-override"><code>def rule(row): name = row['Last Name'] return rules.loc[rules['Last Name'] == name]['Type'] df['Type'] = df.apply(rule, ax...
<pre><code>df1 = pd.DataFrame({'First Name': ['John', 'Jane','John'], 'Last Name': ['Smith','Doe','Doe']}) print(df1) rules = pd.DataFrame({'Last Name':['Smith', 'Doe'], 'Type': ['A','B']}) print(rules) </code></pre> <p>Output is:</p> <pre><code> First Name Last Name 0 John Smith 1 Jane Doe...
python|pandas
2
9,664
58,584,909
In Pandas frame make column entry that is a list break up its items so that they are listed vertical individually
<p>I've been working on this for hours trying to figure out how to make this json </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>{ "method": "STATIC", "type": "IEEE_...
<p>Thanks set_index did help. </p> <p>Unfortunately, if I decide to add another column of data with a list of a different length compared to columns to "dns_search_domains" and "dns_servers" then I get this error</p> <pre><code>ValueError: arrays must all be same length </code></pre> <p>At this point I've opted to j...
python|pandas
0
9,665
58,462,173
Training Accuracy increases, then drops sporadically and abruptly. Fix? [Keras] [TensorFlow backend]
<p>I'm doing binary classification.</p> <p>So while training my Model, the training accuracy is increasing, but in some epochs its drops abrupty. Below is an image to illustrate. what am i doing wrong? Why is this happening? What is the explanation? How can I fix this?</p> <p>Also, both the training accuracy and the ...
<p>You should shuffle and randomize your data prior to training it</p> <pre><code>def Randomizing(): df = pd.DataFrame({"D1":range(5), "D2":range(5)}) print(df) df2 = df.reindex(np.random.permutation(df.index)) print(df2) Randomizing() </code></pre> <p>This is a sample code which you can perform for...
python|tensorflow|keras|neural-network|deep-learning
0
9,666
69,253,628
Plugging in pre-trained model on top of embeddings from another pre-trained model, how to make input dimensions work?
<p>I am experimenting with placing a pre-trained model (e.g. VGG, AlexNet, etc...) on top of the embeddings outputted from another model. I think the only unclear part for me is how would I go about making the input dimension work with that newly added pre-trained model? In more concrete terms:</p> <ol> <li>Grab the em...
<p>If you already have extracted an embedding from your image, you should not be looking to use a CNN. A typical CNN architecture is comprised of a <em>feature extractor</em> (the convolutional layers) and a <em>classifier</em> (a fully connected layer). The purpose of the convolution part is to extract relevant inform...
machine-learning|deep-learning|neural-network|pytorch|computer-vision
0
9,667
68,967,837
Numpy - count of duplicate rows in 3D array
<p>I am looking to count the number of unique rows in a 3D NumPy array. Take the following array:</p> <pre><code>a = np.array([[[1, 2], [1, 2], [2, 3]], [[2, 3], [2, 3], [3, 4]], [[1, 2], [1, 2], [1, 2]]]) </code></pre> <p>My desired output is a 1-D array of the same length as axis 0 of the 3-D array. <code>array([2, 2...
<p>Calling <code>np.unique</code> for each 2D plan appear to be extremely slow. Actually, it is <code>np.unique</code> which is slow and not really the pure Python loop.</p> <p>A better approach is to to that manually with <strong>Numba</strong> (using a <code>dict</code>). While this strategy is faster, it is not a si...
numpy
1
9,668
44,621,681
Tensorflow: TypeError: helper must be a Helper, received: <class 'helper.GreedyEmbeddingHelper'>
<p>Hello I am trying to create a BasicDecoder with a GreedyEmbeddingHelper but it is giving an error:</p> <pre><code>TypeError: helper must be a Helper, received: &lt;class 'helper.GreedyEmbeddingHelper'&gt; </code></pre> <p>Here is a simplified version of my code:</p> <pre><code> elif self.mode == 'decode': ...
<p>GreedyEmbeddingHelper is defined at tf.contrib.seq2seq.GreedyEmbeddingHelper. So instead of <code>helper.GreedyEmbeddingHelper</code>, use <code>tf.contrib.seq2seq.GreedyEmbeddingHelper</code></p>
python|tensorflow|deep-learning|lstm
0
9,669
44,379,949
Pandas: Pivot to True/False, drop column
<p>I'm trying to create what I think is a simple pivot table but am having serious issues. There are two things I'm unable to do:</p> <ol> <li>Get rid of the "partner" column at the end.</li> <li>Set the values to either True or False if each company has that partner.</li> </ol> <p><strong>Setup:</strong></p> <pre>...
<p><strong>Option 1</strong> </p> <pre><code>df.groupby(['company', 'partner']).size().unstack(fill_value=0).astype(bool) partner x y company a True False b True True c False True </code></pre> <p>Get rid of names on columns object</p> <pre><code>df.groupby(['co...
python|pandas|pivot
9
9,670
60,800,389
slicing with iloc and negative integer in Pandas
<p>I have been following this Python linear regression tutorial: <a href="https://medium.com/@contactsunny/linear-regression-in-python-using-scikit-learn-f0f7b125a204" rel="nofollow noreferrer">https://medium.com/@contactsunny/linear-regression-in-python-using-scikit-learn-f0f7b125a204</a></p> <p>Using the following d...
<p>It means, get all columns except the last column:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,100,(5,5)), index=[*'abcde'], columns=[*'ABCDE']) df.iloc[:,:-1] </code></pre> <p>Output:</p> <pre><code> A B C D a 79 23 9 89 b 67 60 32 82 c 66 18 41 67 d 90 51 63 29 e 34 65 82 ...
python|pandas|machine-learning
2
9,671
71,473,205
Jupyter Notebook stuck at loading when importing data with pymongo to a pandas dataframe
<p>Everytime I run it, the cell stays loading and it never finishes. Data is 2mbs so it should load really fast. Pymongo was installed with pymongo[srv]. My code:</p> <pre><code>import pandas as pd import pymongo import os pwd = os.getenv(&quot;mongodb_pwd&quot;) client = pymongo.MongoClient( f&quot;mongodb+srv:...
<p>restarted the pc and everything worked fast again. No idea what happened.</p>
python|pandas|jupyter-notebook|pymongo
0
9,672
71,618,942
Monai : RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 7 but got size 8 for tensor number 1 in the list
<p>I am using <a href="https://github.com/Project-MONAI" rel="nofollow noreferrer">Monai</a> for the 3D Multilabel segmentation task. My input image size is 512x496x49 and my label size is 512x496x49. An Image can have 3 labels in one image. With transform, I have converted the image in size 1x512x512x49 and Label in 3...
<p>Your images have a depth of 49, but due to the 4 downsampling steps, each with stride 2, your images need to be divisible by a factor of 2**4=16. Adding in <code>DivisiblePadd([&quot;image&quot;, &quot;label&quot;], 16)</code> should solve it.</p>
pytorch|image-segmentation|multilabel-classification|medical-imaging
0
9,673
69,921,335
Cumulative difference of numbers starting from an initial value
<p>I have a Pandas dataframe containing a series of numbers:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'deduction':[10,60,70,50,60,10,10,60,60,20,50,20,10,90,60,70,30,50,40,60]}) deduction 0 10 1 60 2 70 3 50 4 60 5 10 6 10...
<pre><code>df['total'] = start_value - df[&quot;deduction&quot;].cumsum() </code></pre> <p>If you need the start value at the beginning of the series then shift and insert (there's a few ways to do it, and this is one of them):</p> <pre><code>df['total'] = -df[&quot;deduction&quot;].shift(1, fill_value=-start_value).c...
python|pandas|dataframe
2
9,674
72,279,786
pandas can't read my list of numeric values
<p>I am having an issue with pandas reading my data file. The relevant code I'm using at the moment is this:</p> <pre><code>import pandas as pd file_data = pd.read_csv('14_May_2022.csv') complete_df = pd.DataFrame(file_data) print(complete_df.info()) Current_Players_df = complete_df[[&quot;Game&quot;,&quot;Current_Pla...
<p>First off, it may be hard for us to help without having your data.</p> <p>That said, in your <code>pd.to_numeric()</code> call, the keyword is <code>errors</code> with an 's', you just have error. Fixing that might get you somewhere.</p> <p>Also, why do you have your second line calling <code>pd.DataFrame(file_data)...
python|pandas
1
9,675
50,576,732
Different functions for calculating phase/argument of complex numbers
<p>Are there any differences between the </p> <pre><code>cmath.phase() </code></pre> <p>function from the <code>cmath</code> module, and the</p> <pre><code>np.angle() </code></pre> <p>function from <code>numpy</code>.</p>
<p>Mathematically, there is no difference between these two functions. Both compute the phase or argument of a complex number as:</p> <pre><code>arg = arctan2(zimag, zreal) </code></pre> <p>See documentation for <a href="https://docs.python.org/2/library/cmath.html#cmath.phase" rel="nofollow noreferrer"><code>cmath.p...
python|numpy|phase|cmath
4
9,676
50,326,076
how to calculate how many times is changed in the column
<p>how I can calculate on the most easy way, how much values changes I have in the specific DataFrame columns. For example I have follow DF:</p> <pre><code>a b 0 1 1 1 2 1 3 2 4 1 5 2 6 2 7 3 8 3 9 3 </code></pre> <p>In this Data Frame the values in the column <code>b</code> have been changed 4 times (in the rows 4,5...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <code>index</code>:</p> <pre><code>idx = df.index[df['b'].diff().shift().fillna(0).ne(0)] print (idx) Int64Index([4, 5, 6, 8], dtype='int64') </code></pr...
pandas
1
9,677
50,620,755
How to create an array/dataframe populated by 1 or 0 based on whether time is within a range?
<p>Basically, I have a <em>dataframe</em> which has 2 columns, both of which are hours:</p> <pre><code> 0 1 +-----+----+ 0| 11 | 12 | +-----+----+ 1| 3 | 4 | +-----+----+ 2| 11 | 12 | +-----+----+ 3| 6 | 7 | +-----+----+ 4| 16 | 16 | etc... </code></pre> <p>This has a few thousand rows. ...
<p>You can compare and multiply the values by creating a dataframe i.e </p> <pre><code>temp = pd.DataFrame([np.arange(1,25)],index = df.index,) begin = (temp.values&gt;=df['0'].values[:,None]).astype(int) end = (temp.values&lt;=df['1'].values[:,None]).astype(int) pd.DataFrame(begin*end,columns=np.arange(1,25)) ...
python|pandas|loops|time
1
9,678
62,670,041
batch_size in tf model.fit() vs. batch_size in tf.data.Dataset
<p>I have a large dataset that can fit in host memory. However, when I use tf.keras to train the model, it yields GPU out-of-memory problem. Then I look into tf.data.Dataset and want to use its batch() method to batch the training dataset so that it can execute the model.fit() in GPU. According to its documentation, an...
<p>You do not need to pass the <code>batch_size</code> parameter in <code>model.fit()</code> in this case. It will automatically use the BATCH_SIZE that you use in <code>tf.data.Dataset().batch()</code>.</p> <p>As for your other question : the batch size hyperparameter indeed needs to be carefully tuned. On the other h...
tensorflow|tensorflow2.0|tensorflow2.x
5
9,679
62,749,100
JSON to Pandas dataframe conversion
<p>I have trouble with conversion of JSON formatted data to Pandas dataframe. My JSON data looks like this and is stored in the variable active_assets -</p> <pre><code>Asset({ 'class': 'us_equity', 'easy_to_borrow': True, 'exchange': 'NYSE', 'id': '879ac630-107f-43ce-a01d-1fd9da89453c', 'marginable': ...
<p>You are iterating over a dictionary in your dictionary comprehension. Try to have i equal to your json object.</p> <p>You can also try to use the read_json method from pandas.</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html" rel="nofollow noreferrer">https://pandas.py...
python|json|pandas|dictionary
0
9,680
62,702,703
Descriptor 'date' requires a 'datetime.datetime' object but received a 'Series' (Python)
<p>So, I have the following DataFrame:</p> <p><a href="https://i.stack.imgur.com/ITbRK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ITbRK.png" alt="enter image description here" /></a></p> <p>I would like to convert those datetime values to date, so I tried:</p> <pre><code>df['Notification Date']=...
<p>You should use <code>pd.to_datetime</code> for pandas series:</p> <pre><code>df['Notification Date'] = pd.to_datetime(df['Notification Date']) </code></pre>
python|pandas|datetime
2
9,681
62,652,886
How to count unique combinations of values in selected columns in pandas data frame including frequencies with the value of 0?
<p>In my dataframe (assume it is called df), I have two columns: one labeled colour and one labeled TOY_ID. Using <code>df.groupby(['Colour', 'TOY_ID']).size()</code> I was able to generate a third column which is unnamed that represents the frequency of the number of times that the other two columns' values have appea...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reindex.html" rel="nofollow noreferrer"><code>Series.reindex</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.from_product.html" rel="nofollow noreferrer"><code>MultiIndex.from_pro...
python|pandas
1
9,682
62,583,096
Plotting filtered rows
<p>I have this dataset (it is just a sample):</p> <pre><code>Date Name Surname Text 2020/03/20 Joe Smith Include details 2020/03/20 Michael Jordan Describe what you've tried 2020/03/21 Bill Gates Pres...
<p>You should extract the associated dates along with the names, then can do something like this:</p> <pre><code>(df.loc[df['Text'].str.contains('details', flags=re.IGNORECASE)] .plot.scatter('Date','Name') ) </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/H7uVj.png" rel="nofollow noreferrer"><img...
python|pandas|matplotlib
1
9,683
62,857,991
Advice on how to shape data for lstm
<p>I have a time series of 933 matrices, each matrix is a 8x10 matrix. This is my X (input). So X has shape (933, 8, 10). The Y (output) is a time series of 933 vectors, each vector is a 5-dimensional vector. So Y has shape (933, 1, 5).</p> <p>I can also reshape the data (should I?) such as X is (933, 80) and Y is (933...
<p>For LSTM, the input must be <code>3D</code> that is <code>(samples, time steps, features)</code>.<br /> In your case, you need to reshape your data to <code>(933,8,10)</code></p> <p>In the LSTM layer, the argument <code>input_shape</code> takes a tuple of two values that defines the number of <code>time steps</code>...
python|tensorflow|keras|regression|lstm
1
9,684
62,700,540
My script is only executed to the first element on my dataframe Python
<p>I need your help on a loop here:</p> <p>I have a dataframe df that looks like this:</p> <pre><code> OC OZ ON WT DC DZ DN 0 PL 97 TP 59 DE 63 DC 1 US 61 SU 95 US 95 SU 2 SA 32 FS 57 DQ 09 PO 3 QS 54 FS 13 HR 78 LK 4 DQ 76 DS 65 SQ 94 PO </code></pre> <p>I have some op...
<p>I could solve the issue.</p> <p>The problem was that i had to instantiate the <code>dic = {}</code> and <code>dic['section'] = []</code> inside the loop.</p> <p>Below the final code that works.</p> <pre><code>for ix, row in df_road.iterrows(): in_dict1 = {'location': dic = {} dic['section'] = [] ...
python|python-3.x|pandas
1
9,685
62,508,022
Extract range-start and range-end records from a dataframe
<p>I'd like to calculate the time periods for which <code>Value</code> is in range (41 - 46) and remain at the same value for <code>df</code> below. <code>Value</code> should only update when there is a change, otherwise remains constant.</p> <pre><code> Id Timestamp Value 34213951 ...
<p>Here's a vectorized way of doing that. Mostly using <code>shift</code> to compare adjacent rows.</p> <pre><code>df[&quot;in_range&quot;] = (df.Value &gt;= 41) &amp; (df.Value &lt;= 46) df[&quot;end_of_range&quot;] = df.in_range.shift() &amp; ~df.in_range df[&quot;start_of_range&quot;] = ~df.in_range.shift(1).fillna(...
python|pandas
1
9,686
73,703,110
merge two dataframe based on intersection
<p>i have two dataframes df1 and df2</p> <p>df1:</p> <pre><code>categories ; ['hello','world'] ['gogo','albert'] ['dodo'] </code></pre> <p>df2:</p> <pre><code>categories ; ['hello','world'] ['albert'] ['dodji'] </code></pre> <p>i want to have as result only lines of df1 based on : if the intersection of df1 and df2 ...
<p>Pandas isn't optimised for Series consisting of lists. I think the best solution is just to use Python sets and check length is nonzero, then use that to mask <code>df1</code>:</p> <pre><code># Set up data df1 = pd.DataFrame({'categories': [['hello','world'],['gogo','albert'],['dodo']]}) df2 = pd.DataFrame({'categor...
python|pandas|dataframe
1
9,687
73,581,722
How to Compare Two Columns From Two Dataframes for Differences?
<p>I have two DataFrames, and I need to compare two columns in my first DataFrame with two columns in another DataFrame to compare the differences in the values.</p> <p>This is what my first DataFrame looks like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>item_number</th> <th>sell_pric...
<p>Here's an example:</p> <pre><code>import pandas as pd df1=pd.DataFrame({'item_number':[10,20],'sell_price':[20,40]},index=[0,1]) df2=pd.DataFrame({'item_number':[10,20],'price':[15,20]},index=[0,1]) df1['price']=df2['price'] </code></pre> <p>Note you're effectively adding a column to the original df1. You can always...
python|pandas|dataframe|compare|comparison
-1
9,688
73,788,242
Shift value by month within a group
<p>Consider the following data frame:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ &quot;id&quot;: [0, 0, 0, 1, 1, 1, 1, 2, 2, 2], &quot;date&quot;: [&quot;2017-01-31&quot;, &quot;2017-02-28&quot;, &quot;2017-03-31&quot;, &quot;2017-01-31&quot;, &quot;2017-03-31&q...
<p>Here's another way to do what your question asks:</p> <pre class="lang-py prettyprint-override"><code>df = df.set_index('id') for shift in [1, 2]: df = df.assign(shift_date=df.date + MonthEnd(shift)) df[f'value_{shift}'] = df.set_index('shift_date', append=True).index.map(df.set_index('date', append=True).va...
python|pandas|dataframe|performance|optimization
1
9,689
71,428,904
ValueError: Layer "sequential" expects 1 input(s), but it received 10 input tensors
<p>I am following TFF tutorials to build my FL model My data is contained in different CSV files which are considered as different clients. Following this <a href="https://www.tensorflow.org/federated/tutorials/building_your_own_federated_learning_algorithm" rel="nofollow noreferrer">tutorial</a>, and build the Keras m...
<p>A couple problems: Your data has ten separate features, which means you actually need 10 separate inputs for your model. However, you can also stack the features into a tensor and then use a single input with the shape <code>(10,)</code>. Here is a working example, but please note that it uses dummy data and therefo...
python|tensorflow|keras|tensorflow-federated
1
9,690
71,332,423
I am unable to read data into my Jupyter notebook
<p>I cloned a repo from GitHub to the Google Cloud Workbench. I haven't been able to read in my data to the Jupyter notebook. It seems like it is unable to locate the file. I have checked the file spellings and location, it all seems to be in place. I also tried to read it in as</p> <pre><code>PATH = &quot;data/countyp...
<p>Try this:</p> <pre><code>PATH = r&quot;/data/countypres_2000-2020.csv&quot; df = pd.read_csv(PATH) </code></pre>
pandas|jupyter-notebook
0
9,691
71,196,836
Finding a quicker method to construct a matrix in python
<p>I'm trying to construct a (p+1,n) matrix with the code below:</p> <pre><code>import numpy as np p = 3 xh = np.linspace(0.5,1.5,p+1) n = 7 x = np.linspace(0,2,n) M = np.zeros([p+1,n]) l2 = 1 for i in range(len(x)): for k in range(len(xh)): for j in range(len(xh)): if k != j: ...
<p>Your code can be nicely compiled by decorating a function with <a href="https://numba.pydata.org/numba-doc/latest/user/performance-tips.html" rel="nofollow noreferrer"><code>@nb.njit</code></a> from the <a href="https://numba.pydata.org/" rel="nofollow noreferrer"><code>numba</code></a> package. Some minor redundant...
python|numpy
2
9,692
71,286,703
How can I change a string in a cell with my pre-made dictionary?
<p>I have a big dataset (pandas df). It's about news reading. I'm trying to clean it. But it's a bit messy. I want to work on coutries but in some (most!) rows it has the city name not the country. I created a dict, keys are countries and values are cities. I want to change city names to country names. I</p> <p>To pic...
<p>I have written the code what @Tobias suggested in the comments.</p> <pre><code>cities, countries = [],[] for key, value in checklist.items(): for i in value: cities.append(i) countries.append(key) new_checklist = dict(zip(cities,countries)) </code></pre> <p>The above inverts your checklist. You can then ...
python|pandas|dataframe
0
9,693
60,612,985
Python list has none type elements even though filled with dataframe elements
<p>I initialize a list of length n using <code>df_list = [None] * n</code>. Then I have a for loop where I fill each element of <code>df_list</code> with a dataframe. Then, when I concat all these dataframes together using <code>df = pd.concat(df_list, axis=0)</code> I end up with fewer rows than expected, and upon fur...
<p>Why do you even need to initialize the list with None values. Just create empty list and append your dataframes to it. </p>
python|pandas|dataframe|concat|nonetype
1
9,694
72,693,016
Find intersections in all dataset rows
<p>I need to write a function.</p> <p>It takes any value from the dataset as input and should look for an intersection in all rows.</p> <p>For example: phone = 87778885566</p> <p>The table is represented by the following fields:</p> <ol> <li>key</li> <li>id</li> <li>phone</li> <li>email</li> </ol> <p>Test data:</p> <ul...
<p>You could use <code>recurssion</code>:</p> <pre><code>import numpy as np def relation(dat, values): d = dat.apply(lambda x: x.isin(values.ravel())) values1 = dat.iloc[np.unique(np.where(d)[0]),:] if set(np.array(values)) == set(values1.to_numpy().ravel()): return values1 else: return...
python|python-3.x|pandas|numpy
0
9,695
72,717,049
Scipy Optimize Minimize: Optimization terminated successfully but not iterating at all
<p>I am trying to code an optimizer finding the optimal constant parameters so as to minimize the MSE between an array y and a generic function over X. The generic function is given in pre-order, so for example if the function over X is x1 + c*x2 the function would be [+, x1, *, c, x2]. The objective in the previous ex...
<p>It seems that scipy optimize minimize does not work well with Pytorch. Changing the code to use numpy ndarrays solved the problem.</p>
python|pytorch|scipy-optimize-minimize
0
9,696
59,589,975
Count the duplicate rows in excel using python and i am getting error TypeError: a bytes-like object is required, not 'str'
<p>Format Like this email excel file</p> <pre><code>name email A A@gmail.com B B@gmailcom C c@gmail.com A A@gmail.com B B@gmail.com </code></pre> <p>In second excel file outfile.csv This is the output </p> <pre><code>name email count A ...
<p>If you just want to count the duplicates, use pandas.DataFrame.unique()!</p> <pre><code>import pandas as pd data = pd.read_excel('email.xlsx') unique = data.column_name.unique() duplicates = len(data)-len(unique) print("number of duplicate rows is:",duplicates) </code></pre> <p>you just need to know the column_n...
python|excel|pandas|csv
2
9,697
59,675,306
Bar chart with customised width in Python
<p>I have this dataframe <code>df</code> which contains -</p> <pre><code>Name Team Name Category Challenge Points Time A B 1 1ABC 50 2019-11-04 07:37:02 D B 2 2ACE 150 ...
<p>Does this look like what you want?</p> <p><a href="https://i.stack.imgur.com/ifsTK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ifsTK.png" alt="enter image description here"></a></p> <p>You can accomplish this by manually plotting the 'blocks' via <code>matplotlib.patches</code>, it just requ...
python|pandas|matplotlib|data-visualization
2
9,698
59,765,712
OPTICS parallelism
<p>I have the following script (<code>optics.py</code>) to estimate clustering with precomuted distances:</p> <pre><code>from sklearn.cluster import OPTICS import numpy as np distances = np.load(r'distances.npy') clust = OPTICS(metric='precomputed', n_jobs=-1) clust = clust.fit(distances) </code></pre> <p>Looking at...
<p>I'm the primary author of the sklearn OPTICS module. Parallelism is difficult because there is an ordering loop which <em>cannot</em> be run in parallel; that said, the most computationally intensive task is distance calculations, and these can be run in parallel. More specifically, sklearn OPTICS calculates the upp...
python|numpy|scikit-learn|optics-algorithm
4
9,699
32,491,339
Python Pandas with functions and column equal values
<p>I am trying to create a function that takes an already formatted json.loads(). </p> <pre><code>def data_fp(fp): for line in fp: try: data=json.loads(line) json_data.append(data) except: continue </code></pre> <p>I take the json_data and am trying to clean it. I created a blan...
<p>Any variable assigned in a function is local to that function, unless it is specifically declared global. So without assignment you access the global variable and everything goes fine, with assignment you access a non-declared local variable hence an error.</p> <p>Look here: <a href="http://effbot.org/pyfaq/how-do-...
python|pandas|global-variables|dataframe
1